diff --git a/.claude/settings.json b/.claude/settings.json new file mode 100644 index 0000000..671a084 --- /dev/null +++ b/.claude/settings.json @@ -0,0 +1,6 @@ +{ + "attribution": { + "commit": "", + "pr": "" + } +} diff --git a/api/android-sdk-core.api b/api/android-sdk-core.api index c7b001e..11d117c 100644 --- a/api/android-sdk-core.api +++ b/api/android-sdk-core.api @@ -8,6 +8,7 @@ public final class com.mapconductor.core.BitmapIconCache { } public interface com.mapconductor.core.ComponentState { public abstract java.lang.String getId(); + public abstract com.mapconductor.core.StateMutationSignal getMutations(); } public final class com.mapconductor.core.EventsKt { } @@ -32,15 +33,6 @@ public final class com.mapconductor.core.MathExtKt { public static final java.lang.String toFixed(double, int); public static final java.lang.String toFixed(float, int); } -public final class com.mapconductor.core.OverlayCollector implements com.mapconductor.core.OverlayCollectorInterface { - public com.mapconductor.core.OverlayCollector(kotlin.jvm.functions.Function1, long, kotlinx.coroutines.CoroutineScope, int, kotlin.jvm.internal.DefaultConstructorMarker); - public kotlinx.coroutines.flow.MutableStateFlow> getFlow(); - public java.lang.Object add(T, kotlin.coroutines.Continuation); - public void remove(java.lang.String); - public void setUpdateHandler(kotlin.jvm.functions.Function2, ? extends java.lang.Object>); - public void replaceAll(java.util.List); - public com.mapconductor.core.OverlayCollector(kotlin.jvm.functions.Function1, long, kotlinx.coroutines.CoroutineScope, kotlin.jvm.internal.DefaultConstructorMarker); -} public interface com.mapconductor.core.OverlayCollectorInterface { public abstract kotlinx.coroutines.flow.MutableStateFlow> getFlow(); public abstract java.lang.Object add(T, kotlin.coroutines.Continuation); @@ -103,7 +95,7 @@ public interface com.mapconductor.core.circle.CircleCapableInterface { public abstract void setOnCircleClickListener(kotlin.jvm.functions.Function1); public abstract boolean hasCircle(com.mapconductor.core.circle.CircleState); } -public abstract class com.mapconductor.core.circle.CircleController implements com.mapconductor.core.controller.SlottedOverlayController> { +public abstract class com.mapconductor.core.circle.CircleController implements com.mapconductor.core.controller.SlottedOverlayController>, com.mapconductor.core.controller.OnCameraChangeReceiverInterface { public com.mapconductor.core.circle.CircleController(com.mapconductor.core.circle.CircleManagerInterface, com.mapconductor.core.circle.CircleOverlayRendererInterface); public final com.mapconductor.core.circle.CircleManagerInterface getCircleManager(); public com.mapconductor.core.circle.CircleOverlayRendererInterface getRenderer(); @@ -111,11 +103,14 @@ public abstract class com.mapconductor.core.circle.CircleController getClickListener(); public final void setClickListener(kotlin.jvm.functions.Function1); + public final com.mapconductor.core.circle.CircleTiler getTiler(); + public final void setTiler(com.mapconductor.core.circle.CircleTiler); public final void dispatchClick(com.mapconductor.core.circle.CircleEvent); public java.lang.Object add(java.util.List, kotlin.coroutines.Continuation); public java.lang.Object update(com.mapconductor.core.circle.CircleState, kotlin.coroutines.Continuation); public java.lang.Object clear(kotlin.coroutines.Continuation); public com.mapconductor.core.circle.CircleEntityInterface find(com.mapconductor.core.features.GeoPointInterface); + public java.lang.Object onCameraChanged(com.mapconductor.core.map.MapCameraPosition, kotlin.coroutines.Continuation); public void destroy(); public boolean has(java.lang.String); public com.mapconductor.core.controller.OverlayKind getKind(); @@ -173,14 +168,17 @@ public final class com.mapconductor.core.circle.CircleKt { } public final class com.mapconductor.core.circle.CircleManager implements com.mapconductor.core.circle.CircleManagerInterface { public com.mapconductor.core.circle.CircleManager(); + public boolean setTiledSource(com.mapconductor.core.circle.CircleTiler); public com.mapconductor.core.circle.CircleEntityInterface getEntity(java.lang.String); public boolean hasEntity(java.lang.String); public com.mapconductor.core.circle.CircleEntityInterface removeEntity(java.lang.String); public void registerEntity(com.mapconductor.core.circle.CircleEntityInterface); public final void updateEntity(com.mapconductor.core.circle.CircleEntityInterface); + public java.util.List> nativeEntities(); public java.util.List> allEntities(); public void clear(); public com.mapconductor.core.circle.CircleEntityInterface find(com.mapconductor.core.features.GeoPointInterface); + public com.mapconductor.core.circle.CircleEntityInterface find(com.mapconductor.core.features.GeoPointInterface, com.mapconductor.core.map.MapCameraPosition); } public interface com.mapconductor.core.circle.CircleManagerInterface { public abstract void registerEntity(com.mapconductor.core.circle.CircleEntityInterface); @@ -188,13 +186,23 @@ public interface com.mapconductor.core.circle.CircleManagerInterface getEntity(java.lang.String); public abstract boolean hasEntity(java.lang.String); public abstract java.util.List> allEntities(); + public default java.util.List> nativeEntities(); + public default boolean setTiledSource(com.mapconductor.core.circle.CircleTiler); public abstract void clear(); public abstract com.mapconductor.core.circle.CircleEntityInterface find(com.mapconductor.core.features.GeoPointInterface); + public default com.mapconductor.core.circle.CircleEntityInterface find(com.mapconductor.core.features.GeoPointInterface, com.mapconductor.core.map.MapCameraPosition); +} +public final class com.mapconductor.core.circle.CircleManagerInterface$DefaultImpls { + public static java.util.List> nativeEntities(com.mapconductor.core.circle.CircleManagerInterface); + public static boolean setTiledSource(com.mapconductor.core.circle.CircleManagerInterface, com.mapconductor.core.circle.CircleTiler); + public static com.mapconductor.core.circle.CircleEntityInterface find(com.mapconductor.core.circle.CircleManagerInterface, com.mapconductor.core.features.GeoPointInterface, com.mapconductor.core.map.MapCameraPosition); } public final class com.mapconductor.core.circle.CircleOverlay implements com.mapconductor.core.map.MapOverlayInterface { - public com.mapconductor.core.circle.CircleOverlay(kotlinx.coroutines.flow.StateFlow>); + public com.mapconductor.core.circle.CircleOverlay(kotlinx.coroutines.flow.StateFlow>, kotlinx.coroutines.flow.StateFlow); + public com.mapconductor.core.circle.CircleOverlay(kotlinx.coroutines.flow.StateFlow, kotlinx.coroutines.flow.StateFlow, int, kotlin.jvm.internal.DefaultConstructorMarker); public kotlinx.coroutines.flow.StateFlow> getFlow(); public java.lang.Object render(java.util.Map, com.mapconductor.core.controller.MapViewControllerInterface, kotlin.coroutines.Continuation); + public com.mapconductor.core.circle.CircleOverlay(kotlinx.coroutines.flow.StateFlow>); } public interface com.mapconductor.core.circle.CircleOverlayRendererInterface { public abstract java.lang.Object onAdd(java.util.List, kotlin.coroutines.Continuation>); @@ -210,7 +218,8 @@ public interface com.mapconductor.core.circle.CircleOverlayRendererInterface$Cha public abstract com.mapconductor.core.circle.CircleEntityInterface getPrev(); } public final class com.mapconductor.core.circle.CircleState implements com.mapconductor.core.ComponentState { - public com.mapconductor.core.circle.CircleState(com.mapconductor.core.features.GeoPointInterface, double, boolean, boolean, long, float, long, java.lang.String, java.lang.Integer, java.io.Serializable, kotlin.jvm.functions.Function1, int, kotlin.jvm.internal.DefaultConstructorMarker); + public com.mapconductor.core.circle.CircleState(com.mapconductor.core.features.GeoPointInterface, double, boolean, boolean, long, float, long, java.lang.String, java.lang.Integer, java.io.Serializable, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, int, kotlin.jvm.internal.DefaultConstructorMarker); + public com.mapconductor.core.StateMutationSignal getMutations(); public final com.mapconductor.core.features.GeoPointInterface getCenter(); public final void setCenter(com.mapconductor.core.features.GeoPointInterface); public final boolean getClickable(); @@ -231,14 +240,115 @@ public final class com.mapconductor.core.circle.CircleState implements com.mapco public final void setZIndex(java.lang.Integer); public final kotlin.jvm.functions.Function1 getOnClick(); public final void setOnClick(kotlin.jvm.functions.Function1); + public final kotlin.jvm.functions.Function1 getOnAdded(); + public final void setOnAdded(kotlin.jvm.functions.Function1); + public com.mapconductor.core.circle.CircleState(com.mapconductor.core.features.GeoPointInterface, double, boolean, boolean, long, float, long, java.lang.String, java.lang.Integer, java.io.Serializable, kotlin.jvm.functions.Function1, int, kotlin.jvm.internal.DefaultConstructorMarker); public java.lang.String getId(); public final com.mapconductor.core.circle.CircleFingerPrint fingerPrint(); - public final kotlinx.coroutines.flow.Flow asFlow(); - public final com.mapconductor.core.circle.CircleState copy-H0InVkU(com.mapconductor.core.features.GeoPointInterface, double, boolean, boolean, long, float, long, java.lang.String, java.lang.Integer, java.io.Serializable, kotlin.jvm.functions.Function1); + public final com.mapconductor.core.circle.CircleState copy-Zc45R8w(com.mapconductor.core.features.GeoPointInterface, double, boolean, boolean, long, float, long, java.lang.String, java.lang.Integer, java.io.Serializable, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1); + public final com.mapconductor.core.circle.CircleState copy-H0InVkU(com.mapconductor.core.features.GeoPointInterface, double, boolean, boolean, long, float, long, java.lang.String, java.lang.Integer, java.io.Serializable, kotlin.jvm.functions.Function1); public boolean equals(java.lang.Object); public int hashCode(); + public com.mapconductor.core.circle.CircleState(com.mapconductor.core.features.GeoPointInterface, double, boolean, boolean, long, float, long, java.lang.String, java.lang.Integer, java.io.Serializable, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.internal.DefaultConstructorMarker); public com.mapconductor.core.circle.CircleState(com.mapconductor.core.features.GeoPointInterface, double, boolean, boolean, long, float, long, java.lang.String, java.lang.Integer, java.io.Serializable, kotlin.jvm.functions.Function1, kotlin.jvm.internal.DefaultConstructorMarker); } +final class com.mapconductor.core.circle.CircleState$Values { + public final com.mapconductor.core.features.GeoPointInterface getCenter(); + public final boolean getClickable(); + public final double getRadiusMeters(); + public final boolean getGeodesic(); + public final long getStrokeColor-0d7_KjU(); + public final float getStrokeWidth-D9Ej5fM(); + public final long getFillColor-0d7_KjU(); + public final java.io.Serializable getExtra(); + public final java.lang.Integer getZIndex(); + public final kotlin.jvm.functions.Function1 getOnClick(); + public final long getRevision(); + public final int getChangedFields(); + public final int difference(com.mapconductor.core.circle.CircleState$Values); + public final com.mapconductor.core.features.GeoPointInterface component1(); + public final boolean component2(); + public final double component3(); + public final boolean component4(); + public final long component5-0d7_KjU(); + public final float component6-D9Ej5fM(); + public final long component7-0d7_KjU(); + public final java.io.Serializable component8(); + public final java.lang.Integer component9(); + public final kotlin.jvm.functions.Function1 component10(); + public final long component11(); + public final int component12(); + public final com.mapconductor.core.circle.CircleState$Values copy-Zc45R8w(com.mapconductor.core.features.GeoPointInterface, boolean, double, boolean, long, float, long, java.io.Serializable, java.lang.Integer, kotlin.jvm.functions.Function1, long, int); + public java.lang.String toString(); + public int hashCode(); + public boolean equals(java.lang.Object); +} +public interface com.mapconductor.core.circle.CircleTileFileStorage$RecordAction { + public abstract void record(int, java.nio.ByteBuffer, int, com.mapconductor.core.circle.TileCircle); +} +public final class com.mapconductor.core.circle.CircleTileSet { + public static final com.mapconductor.core.circle.CircleTileSet$Companion Companion; + public com.mapconductor.core.circle.CircleTileSet(com.mapconductor.core.tileserver.LocalTileServer, kotlinx.coroutines.CoroutineScope); + public com.mapconductor.core.circle.CircleTileSet(com.mapconductor.core.tileserver.LocalTileServer, kotlinx.coroutines.CoroutineScope, int, kotlin.jvm.internal.DefaultConstructorMarker); + public final java.lang.String getRouteId(); + public final kotlin.jvm.functions.Function2, java.lang.Object> getOnTemplateChanged(); + public final void setOnTemplateChanged(kotlin.jvm.functions.Function2, ? extends java.lang.Object>); + public final int getTileSize(); + public final java.lang.Object setCircles(java.util.List, kotlin.coroutines.Continuation); + public final boolean has(java.lang.String); + public final void update(com.mapconductor.core.circle.CircleState); + public final void remove(java.lang.String); + public final java.lang.String template(); + public final void dispose(); + public com.mapconductor.core.circle.CircleTileSet(); +} +public final class com.mapconductor.core.circle.CircleTileSet$Companion { + public final boolean canTile(com.mapconductor.core.circle.CircleState); +} +public final class com.mapconductor.core.circle.CircleTiler { + public static final double MAX_LATITUDE; + public static final double TAP_STROKE_SLACK_PX; + public static final double TAP_SLACK_METERS; + public com.mapconductor.core.circle.CircleTiler(com.mapconductor.core.circle.CircleTilingOptions); + public com.mapconductor.core.circle.CircleTiler(com.mapconductor.core.circle.CircleTilingOptions, int, kotlin.jvm.internal.DefaultConstructorMarker); + public final com.mapconductor.core.circle.CircleTilingOptions getOptions(); + public final void setOptions(com.mapconductor.core.circle.CircleTilingOptions); + public final kotlin.jvm.functions.Function3, java.lang.Object> getOnTemplate(); + public final void setOnTemplate(kotlin.jvm.functions.Function3, ? extends java.lang.Object>); + public final java.lang.Object route(java.util.List, kotlin.coroutines.Continuation>); + public final java.util.List tiledStates(); + public final boolean isTiled(java.lang.String); + public final void update(com.mapconductor.core.circle.CircleState); + public final void remove(java.lang.String); + public final void dispose(); + public final java.lang.Object clear(kotlin.coroutines.Continuation); + public com.mapconductor.core.circle.CircleTiler(); +} +final class com.mapconductor.core.circle.CircleTiler$Companion { +} +public final class com.mapconductor.core.circle.CircleTilerKt { + public static final java.lang.String CIRCLE_TILE_LAYER_ID; + public static final com.mapconductor.core.raster.RasterLayerState circleTileRasterLayerState(java.lang.String, int); +} +public final class com.mapconductor.core.circle.CircleTilingOptions { + public static final com.mapconductor.core.circle.CircleTilingOptions$Companion Companion; + public com.mapconductor.core.circle.CircleTilingOptions(boolean, int); + public com.mapconductor.core.circle.CircleTilingOptions(boolean, int, int, kotlin.jvm.internal.DefaultConstructorMarker); + public final boolean getEnabled(); + public final int getMinCircleCount(); + public final boolean shouldUseTiles(int); + public final boolean component1(); + public final int component2(); + public final com.mapconductor.core.circle.CircleTilingOptions copy(boolean, int); + public java.lang.String toString(); + public int hashCode(); + public boolean equals(java.lang.Object); + public com.mapconductor.core.circle.CircleTilingOptions(); +} +public final class com.mapconductor.core.circle.CircleTilingOptions$Companion { + public final com.mapconductor.core.circle.CircleTilingOptions getDefault(); + public final com.mapconductor.core.circle.CircleTilingOptions getDisabled(); +} public abstract class com.mapconductor.core.controller.BaseMapViewController implements com.mapconductor.core.controller.MapViewControllerInterface,com.mapconductor.core.marker.MarkerCapableInterface,com.mapconductor.core.polyline.PolylineCapableInterface,com.mapconductor.core.polygon.PolygonCapableInterface,com.mapconductor.core.circle.CircleCapableInterface,com.mapconductor.core.groundimage.GroundImageCapableInterface,com.mapconductor.core.raster.RasterLayerCapableInterface { public static final double ZOOM_EPS; public static final double COORD_EPS; @@ -267,6 +377,7 @@ public abstract class com.mapconductor.core.controller.BaseMapViewController imp public final void setMapClickListener(kotlin.jvm.functions.Function1); public final void setMapLongClickListener(kotlin.jvm.functions.Function1); public void registerOverlayController(com.mapconductor.core.controller.OverlayControllerInterface); + protected final java.lang.Object clearStrategyMarkerControllers(kotlin.coroutines.Continuation); protected java.util.List getOverlayCascadeOrder(); protected boolean dispatchMarkerTap(com.mapconductor.core.features.GeoPointInterface); public final boolean dispatchOverlayTap(com.mapconductor.core.features.GeoPointInterface); @@ -305,6 +416,10 @@ public abstract class com.mapconductor.core.controller.BaseMapViewController imp public java.lang.Object compositionRasterLayers(java.util.List, kotlin.coroutines.Continuation); public java.lang.Object updateRasterLayer(com.mapconductor.core.raster.RasterLayerState, kotlin.coroutines.Continuation); public boolean hasRasterLayer(com.mapconductor.core.raster.RasterLayerState); + public void mountRasterLayer(com.mapconductor.core.raster.RasterLayerState); + public void unmountRasterLayer(java.lang.String); + public final kotlin.jvm.functions.Function0 addStyleLoadedListener(kotlin.jvm.functions.Function0); + protected final void notifyStyleLoaded(); public final void setMapInitializedListener(kotlin.jvm.functions.Function0); protected final void notifyMapInitialized(); protected final java.lang.Object notifyMapCameraPosition(com.mapconductor.core.map.MapCameraPosition, kotlin.coroutines.Continuation); @@ -356,6 +471,13 @@ public final class com.mapconductor.core.controller.OverlayKind extends java.lan public static com.mapconductor.core.controller.OverlayKind valueOf(java.lang.String); public static kotlin.enums.EnumEntries getEntries(); } +public final class com.mapconductor.core.controller.OverlayLayerStack { + public com.mapconductor.core.controller.OverlayLayerStack(); + public final void put(java.lang.String, com.mapconductor.core.controller.OverlayStacking$Key); + public final void remove(java.lang.String); + public final com.mapconductor.core.controller.OverlayStacking$Key keyOf(java.lang.String); + public final java.lang.String beforeId(java.util.List, com.mapconductor.core.controller.OverlayStacking$Key); +} public interface com.mapconductor.core.controller.OverlayRendererInterface { public abstract java.lang.Object onAdd(java.util.List, kotlin.coroutines.Continuation>); public abstract java.lang.Object onChange(java.util.List>, kotlin.coroutines.Continuation>); @@ -366,6 +488,26 @@ public interface com.mapconductor.core.controller.OverlayRendererInterface$Chang public abstract EntityType getCurrent(); public abstract EntityType getPrev(); } +public final class com.mapconductor.core.controller.OverlayStacking { + public static final com.mapconductor.core.controller.OverlayStacking INSTANCE; + public static final float BAND_WIDTH; + public final java.util.List getBOTTOM_TO_TOP(); + public final int band(com.mapconductor.core.controller.OverlayKind); + public final float flatZIndex(com.mapconductor.core.controller.OverlayKind, int); + public final L insertBefore(java.util.List, com.mapconductor.core.controller.OverlayStacking$Key, kotlin.jvm.functions.Function1); +} +public final class com.mapconductor.core.controller.OverlayStacking$Key implements java.lang.Comparable { + public final com.mapconductor.core.controller.OverlayKind getKind(); + public final int getZIndex(); + public int compareTo(com.mapconductor.core.controller.OverlayStacking$Key); + public final com.mapconductor.core.controller.OverlayKind component1(); + public final int component2(); + public final com.mapconductor.core.controller.OverlayStacking$Key copy(com.mapconductor.core.controller.OverlayKind, int); + public java.lang.String toString(); + public int hashCode(); + public boolean equals(java.lang.Object); + public int compareTo(java.lang.Object); +} public final class com.mapconductor.core.controller.SlottedOverlayController$DefaultImpls { public static boolean has(com.mapconductor.core.controller.SlottedOverlayController, java.lang.String); public static void setClickListenerAny(com.mapconductor.core.controller.SlottedOverlayController, java.lang.Object); @@ -434,46 +576,17 @@ public final class com.mapconductor.core.geocell.Direction6 extends java.lang.En public static kotlin.enums.EnumEntries getEntries(); } public final class com.mapconductor.core.geocell.HexCell { + public com.mapconductor.core.geocell.HexCell(com.mapconductor.core.geocell.HexCoord, com.mapconductor.core.features.GeoPointInterface, com.mapconductor.core.projection.ProjectedPoint, java.lang.String); public final com.mapconductor.core.geocell.HexCoord getCoord(); public final com.mapconductor.core.features.GeoPointInterface getCenterLatLng(); - public final long getCenterXY-F1C5BW0(); + public final com.mapconductor.core.projection.ProjectedPoint getCenterXY(); public final java.lang.String getId(); public final java.lang.String idPrefix(int); public final com.mapconductor.core.geocell.HexCoord component1(); public final com.mapconductor.core.features.GeoPointInterface component2(); - public final long component3-F1C5BW0(); + public final com.mapconductor.core.projection.ProjectedPoint component3(); public final java.lang.String component4(); - public final com.mapconductor.core.geocell.HexCell copy-Rg1IO4c(com.mapconductor.core.geocell.HexCoord, com.mapconductor.core.features.GeoPointInterface, long, java.lang.String); - public java.lang.String toString(); - public int hashCode(); - public boolean equals(java.lang.Object); - public com.mapconductor.core.geocell.HexCell(com.mapconductor.core.geocell.HexCoord, com.mapconductor.core.features.GeoPointInterface, long, java.lang.String, kotlin.jvm.internal.DefaultConstructorMarker); -} -public final class com.mapconductor.core.geocell.HexCellRegistry { - public com.mapconductor.core.geocell.HexCellRegistry(com.mapconductor.core.geocell.HexGeocellInterface, double); - public final com.mapconductor.core.geocell.HexCell getCell(com.mapconductor.core.marker.MarkerEntityInterface); - public final com.mapconductor.core.geocell.HexCell setPoint(com.mapconductor.core.marker.MarkerEntityInterface); - public final boolean contains(java.lang.String); - public final boolean removePoint(com.mapconductor.core.marker.MarkerEntityInterface); - public final void clear(); - public final com.mapconductor.core.geocell.HexCell findNearest(com.mapconductor.core.features.GeoPointInterface); - public final com.mapconductor.core.geocell.HexCellWithDistance findNearestWithDistance(com.mapconductor.core.features.GeoPointInterface); - public final java.util.List findNearestKWithDistance(com.mapconductor.core.features.GeoPointInterface, int); - public final java.util.List findWithinRadiusWithDistance(com.mapconductor.core.features.GeoPointInterface, double); - public final java.util.List all(); - public final java.util.Set getEntryIDsByHexCell(com.mapconductor.core.geocell.HexCell); - public final double metersPerPixel(com.mapconductor.core.features.GeoPointInterface, double, double, int); - public final java.util.List findWithinPixelRadius(com.mapconductor.core.features.GeoPointInterface, double, double, int); - public final java.util.List findByIdPrefix(java.lang.String); - public final com.mapconductor.core.geocell.RegistryStats getStats(); -} -public final class com.mapconductor.core.geocell.HexCellWithDistance { - public com.mapconductor.core.geocell.HexCellWithDistance(com.mapconductor.core.geocell.HexCell, double); - public final com.mapconductor.core.geocell.HexCell getCell(); - public final double getDistanceMeters(); - public final com.mapconductor.core.geocell.HexCell component1(); - public final double component2(); - public final com.mapconductor.core.geocell.HexCellWithDistance copy(com.mapconductor.core.geocell.HexCell, double); + public final com.mapconductor.core.geocell.HexCell copy(com.mapconductor.core.geocell.HexCoord, com.mapconductor.core.features.GeoPointInterface, com.mapconductor.core.projection.ProjectedPoint, java.lang.String); public java.lang.String toString(); public int hashCode(); public boolean equals(java.lang.Object); @@ -537,48 +650,6 @@ public final class com.mapconductor.core.geocell.IdentifiedHexCell { public int hashCode(); public boolean equals(java.lang.Object); } -public final class com.mapconductor.core.geocell.KDTree { - public com.mapconductor.core.geocell.KDTree(java.util.List); - public final com.mapconductor.core.geocell.HexCell nearest-k-4lQ0M(long); - public final com.mapconductor.core.geocell.HexCellWithDistance nearestWithDistance-k-4lQ0M(long); - public final java.util.List nearestKWithDistance-3MmeM6k(long, int); - public final java.util.List withinRadiusWithDistance-3MmeM6k(long, double); - public final com.mapconductor.core.geocell.KDTreeStats getStats(); -} -final class com.mapconductor.core.geocell.KDTree$Node { - public final com.mapconductor.core.geocell.HexCell getCell(); - public final com.mapconductor.core.geocell.KDTree$Node getLeft(); - public final com.mapconductor.core.geocell.KDTree$Node getRight(); - public final int getAxis(); -} -public final class com.mapconductor.core.geocell.KDTreeStats { - public com.mapconductor.core.geocell.KDTreeStats(int, int, boolean); - public final int getNodeCount(); - public final int getMaxDepth(); - public final boolean isEmpty(); - public final int component1(); - public final int component2(); - public final boolean component3(); - public final com.mapconductor.core.geocell.KDTreeStats copy(int, int, boolean); - public java.lang.String toString(); - public int hashCode(); - public boolean equals(java.lang.Object); -} -public final class com.mapconductor.core.geocell.RegistryStats { - public com.mapconductor.core.geocell.RegistryStats(int, int, boolean, boolean); - public final int getTotalCells(); - public final int getTotalEntries(); - public final boolean getKdTreeBuilt(); - public final boolean getNeedsRebuild(); - public final int component1(); - public final int component2(); - public final boolean component3(); - public final boolean component4(); - public final com.mapconductor.core.geocell.RegistryStats copy(int, int, boolean, boolean); - public java.lang.String toString(); - public int hashCode(); - public boolean equals(java.lang.Object); -} public final class com.mapconductor.core.geometry.CircleGeometryKt { public static final int DEFAULT_CIRCLE_SEGMENTS; public static final java.util.List circleToRing(com.mapconductor.core.features.GeoPointInterface, double, boolean, int); @@ -591,6 +662,7 @@ public final class com.mapconductor.core.geometry.OverlayGeoJson { } public final class com.mapconductor.core.geometry.OverlayGeometryKt { public static final java.util.List densifyAndNormalize(java.util.List, boolean); + public static final java.util.List densifyPolygonRing(java.util.List, boolean, double); public static final java.util.List> buildPolylineSegments(java.util.List, boolean); public static final com.mapconductor.core.geometry.PolygonRings buildPolygonRings(java.util.List, java.util.List>, boolean); public static final java.util.List closeRing(java.util.List); @@ -725,13 +797,16 @@ public interface com.mapconductor.core.groundimage.GroundImageOverlayRendererInt public abstract com.mapconductor.core.groundimage.GroundImageEntityInterface getPrev(); } public final class com.mapconductor.core.groundimage.GroundImageState implements com.mapconductor.core.ComponentState { - public com.mapconductor.core.groundimage.GroundImageState(com.mapconductor.core.features.GeoRectBounds, android.graphics.drawable.Drawable, float, int, boolean, java.lang.String, java.io.Serializable, kotlin.jvm.functions.Function1); - public com.mapconductor.core.groundimage.GroundImageState(com.mapconductor.core.features.GeoRectBounds, android.graphics.drawable.Drawable, float, int, boolean, java.lang.String, java.io.Serializable, kotlin.jvm.functions.Function1, int, kotlin.jvm.internal.DefaultConstructorMarker); + public com.mapconductor.core.groundimage.GroundImageState(com.mapconductor.core.features.GeoRectBounds, android.graphics.drawable.Drawable, float, int, boolean, java.lang.String, java.io.Serializable, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1); + public com.mapconductor.core.groundimage.GroundImageState(com.mapconductor.core.features.GeoRectBounds, android.graphics.drawable.Drawable, float, int, boolean, java.lang.String, java.io.Serializable, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, int, kotlin.jvm.internal.DefaultConstructorMarker); public java.lang.String getId(); + public com.mapconductor.core.StateMutationSignal getMutations(); public final com.mapconductor.core.features.GeoRectBounds getBounds(); public final void setBounds(com.mapconductor.core.features.GeoRectBounds); public final android.graphics.drawable.Drawable getImage(); public final void setImage(android.graphics.drawable.Drawable); + public final java.lang.String getImageUrl(); + public final void setImageUrl(java.lang.String); public final float getOpacity(); public final void setOpacity(float); public final int getTileSize(); @@ -742,9 +817,17 @@ public final class com.mapconductor.core.groundimage.GroundImageState implements public final void setExtra(java.io.Serializable); public final kotlin.jvm.functions.Function1 getOnClick(); public final void setOnClick(kotlin.jvm.functions.Function1); + public final kotlin.jvm.functions.Function1 getOnAdded(); + public final void setOnAdded(kotlin.jvm.functions.Function1); + public com.mapconductor.core.groundimage.GroundImageState(com.mapconductor.core.features.GeoRectBounds, java.lang.String, float, int, boolean, java.lang.String, java.io.Serializable, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1); + public com.mapconductor.core.groundimage.GroundImageState(com.mapconductor.core.features.GeoRectBounds, java.lang.String, float, int, boolean, java.lang.String, java.io.Serializable, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, int, kotlin.jvm.internal.DefaultConstructorMarker); + public com.mapconductor.core.groundimage.GroundImageState(com.mapconductor.core.features.GeoRectBounds, android.graphics.drawable.Drawable, float, int, boolean, java.lang.String, java.io.Serializable, kotlin.jvm.functions.Function1); + public com.mapconductor.core.groundimage.GroundImageState(com.mapconductor.core.features.GeoRectBounds, android.graphics.drawable.Drawable, float, int, boolean, java.lang.String, java.io.Serializable, kotlin.jvm.functions.Function1, int, kotlin.jvm.internal.DefaultConstructorMarker); + public com.mapconductor.core.groundimage.GroundImageState(com.mapconductor.core.features.GeoRectBounds, java.lang.String, float, int, boolean, java.lang.String, java.io.Serializable, kotlin.jvm.functions.Function1); + public com.mapconductor.core.groundimage.GroundImageState(com.mapconductor.core.features.GeoRectBounds, java.lang.String, float, int, boolean, java.lang.String, java.io.Serializable, kotlin.jvm.functions.Function1, int, kotlin.jvm.internal.DefaultConstructorMarker); public final com.mapconductor.core.groundimage.GroundImageFingerPrint fingerPrint(); - public final kotlinx.coroutines.flow.Flow asFlow(); - public final com.mapconductor.core.groundimage.GroundImageState copy(com.mapconductor.core.features.GeoRectBounds, android.graphics.drawable.Drawable, float, int, boolean, java.lang.String, java.io.Serializable, kotlin.jvm.functions.Function1); + public final com.mapconductor.core.groundimage.GroundImageState copy(com.mapconductor.core.features.GeoRectBounds, android.graphics.drawable.Drawable, float, int, boolean, java.lang.String, java.io.Serializable, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1); + public final com.mapconductor.core.groundimage.GroundImageState copy(com.mapconductor.core.features.GeoRectBounds, android.graphics.drawable.Drawable, float, int, boolean, java.lang.String, java.io.Serializable, kotlin.jvm.functions.Function1); public boolean equals(java.lang.Object); public int hashCode(); } @@ -756,6 +839,7 @@ public final class com.mapconductor.core.groundimage.GroundImageTileProvider imp public final int getTileSize(); public final void update(com.mapconductor.core.groundimage.GroundImageState, float); public byte[] renderTile(com.mapconductor.core.tileserver.TileRequest); + public byte[] renderTile(com.mapconductor.core.tileserver.TileRequest, kotlin.jvm.functions.Function0); public com.mapconductor.core.groundimage.GroundImageTileProvider(); } public final class com.mapconductor.core.groundimage.GroundImageTileProvider$Companion { @@ -777,6 +861,9 @@ final class com.mapconductor.core.groundimage.GroundImageTileProvider$WebMercato public final double lonToPixelX(double, double); public final double latToPixelY(double, double); } +public final class com.mapconductor.core.map.ApplyStyleMutationsKt { + public static final java.util.List applyStyleMutations(com.mapconductor.core.map.StyleMutationTarget, java.util.List); +} public final class com.mapconductor.core.map.AttributionRule implements java.io.Serializable { public com.mapconductor.core.map.AttributionRule(java.lang.String, java.lang.Integer, java.lang.Integer, com.mapconductor.core.features.GeoRectBounds); public com.mapconductor.core.map.AttributionRule(java.lang.String, java.lang.Integer, java.lang.Integer, com.mapconductor.core.features.GeoRectBounds, int, kotlin.jvm.internal.DefaultConstructorMarker); @@ -805,6 +892,13 @@ public abstract class com.mapconductor.core.map.BaseMapViewSaver createSaver(); protected abstract java.lang.String getStateId(T); } +public final class com.mapconductor.core.map.BlankMapStyle { + public static final com.mapconductor.core.map.BlankMapStyle INSTANCE; + public static final java.lang.String BACKGROUND_COLOR; + public static final java.lang.String JSON; + public static final java.lang.String ASSET_URI; + public static final java.lang.String ASSET_FILE_URL; +} public final class com.mapconductor.core.map.CameraRestriction implements java.io.Serializable { public static final com.mapconductor.core.map.CameraRestriction$Companion Companion; public com.mapconductor.core.map.CameraRestriction(com.mapconductor.core.features.GeoRectBounds, java.lang.Double, java.lang.Double); @@ -850,16 +944,21 @@ public final class com.mapconductor.core.map.LocalMapOverlayRegistryKt { } public final class com.mapconductor.core.map.MapCameraPosition implements com.mapconductor.core.map.MapCameraPositionInterface { public static final com.mapconductor.core.map.MapCameraPosition$Companion Companion; - public com.mapconductor.core.map.MapCameraPosition(com.mapconductor.core.features.GeoPointInterface, double, double, double, com.mapconductor.core.map.MapPaddingsInterface, com.mapconductor.core.map.VisibleRegion); - public com.mapconductor.core.map.MapCameraPosition(com.mapconductor.core.features.GeoPointInterface, double, double, double, com.mapconductor.core.map.MapPaddingsInterface, com.mapconductor.core.map.VisibleRegion, int, kotlin.jvm.internal.DefaultConstructorMarker); - public double getZoom(); - public double getBearing(); - public double getTilt(); + public com.mapconductor.core.map.MapCameraPosition(com.mapconductor.core.features.GeoPointInterface, java.lang.Double, java.lang.Double, java.lang.Double, com.mapconductor.core.map.MapPaddingsInterface, com.mapconductor.core.map.VisibleRegion, java.lang.Double); + public com.mapconductor.core.map.MapCameraPosition(com.mapconductor.core.features.GeoPointInterface, java.lang.Double, java.lang.Double, java.lang.Double, com.mapconductor.core.map.MapPaddingsInterface, com.mapconductor.core.map.VisibleRegion, java.lang.Double, int, kotlin.jvm.internal.DefaultConstructorMarker); public com.mapconductor.core.map.MapPaddingsInterface getPaddings(); public com.mapconductor.core.map.VisibleRegion getVisibleRegion(); + public java.lang.Double getFov(); public com.mapconductor.core.features.GeoPoint getPosition(); + public double getZoom(); + public double getBearing(); + public double getTilt(); + public final boolean isZoomSpecified(); + public final boolean isBearingSpecified(); + public final boolean isTiltSpecified(); + public final com.mapconductor.core.map.MapCameraPosition resolvedOnto(com.mapconductor.core.map.MapCameraPositionInterface); public final boolean equals(com.mapconductor.core.map.MapCameraPositionInterface); - public final com.mapconductor.core.map.MapCameraPosition copy(com.mapconductor.core.features.GeoPointInterface, java.lang.Double, java.lang.Double, java.lang.Double, com.mapconductor.core.map.MapPaddingsInterface, com.mapconductor.core.map.VisibleRegion); + public final com.mapconductor.core.map.MapCameraPosition copy(com.mapconductor.core.features.GeoPointInterface, java.lang.Double, java.lang.Double, java.lang.Double, com.mapconductor.core.map.MapPaddingsInterface, com.mapconductor.core.map.VisibleRegion, java.lang.Double); public int hashCode(); public com.mapconductor.core.features.GeoPointInterface getPosition(); } @@ -873,6 +972,10 @@ public interface com.mapconductor.core.map.MapCameraPositionInterface { public abstract double getTilt(); public abstract com.mapconductor.core.map.MapPaddingsInterface getPaddings(); public abstract com.mapconductor.core.map.VisibleRegion getVisibleRegion(); + public default java.lang.Double getFov(); +} +public final class com.mapconductor.core.map.MapCameraPositionInterface$DefaultImpls { + public static java.lang.Double getFov(com.mapconductor.core.map.MapCameraPositionInterface); } public final class com.mapconductor.core.map.MapCapability extends java.lang.Enum { public static final com.mapconductor.core.map.MapCapability$Companion Companion; @@ -1017,15 +1120,22 @@ public final class com.mapconductor.core.map.MapOverlayRegistry { } public class com.mapconductor.core.map.MapPaddings implements com.mapconductor.core.map.MapPaddingsInterface { public static final com.mapconductor.core.map.MapPaddings$Companion Companion; + public com.mapconductor.core.map.MapPaddings(java.lang.Double, java.lang.Double, java.lang.Double, java.lang.Double); + public com.mapconductor.core.map.MapPaddings(java.lang.Double, java.lang.Double, java.lang.Double, java.lang.Double, int, kotlin.jvm.internal.DefaultConstructorMarker); public com.mapconductor.core.map.MapPaddings(double, double, double, double); - public com.mapconductor.core.map.MapPaddings(double, double, double, double, int, kotlin.jvm.internal.DefaultConstructorMarker); public double getTop(); public double getLeft(); public double getBottom(); public double getRight(); - public com.mapconductor.core.map.MapPaddings(double, double, double); - public com.mapconductor.core.map.MapPaddings(double, double); - public com.mapconductor.core.map.MapPaddings(double); + public final boolean isTopSpecified(); + public final boolean isLeftSpecified(); + public final boolean isBottomSpecified(); + public final boolean isRightSpecified(); + public final boolean isFullySpecified(); + public final com.mapconductor.core.map.MapPaddings resolvedOnto(com.mapconductor.core.map.MapPaddingsInterface); + public com.mapconductor.core.map.MapPaddings(java.lang.Double, java.lang.Double, java.lang.Double); + public com.mapconductor.core.map.MapPaddings(java.lang.Double, java.lang.Double); + public com.mapconductor.core.map.MapPaddings(java.lang.Double); public com.mapconductor.core.map.MapPaddings(); } public final class com.mapconductor.core.map.MapPaddings$Companion { @@ -1072,19 +1182,46 @@ public final class com.mapconductor.core.map.MapServiceRegistry$DefaultImpls { public final class com.mapconductor.core.map.MapServiceRegistryKt { public static final androidx.compose.runtime.ProvidableCompositionLocal getLocalMapServiceRegistry(); } +public interface com.mapconductor.core.map.MapStyleHost { + public abstract com.mapconductor.core.map.MapServiceRegistry getServiceRegistry(); + public abstract com.mapconductor.core.tileserver.LocalTileServer getTileServer(); + public default java.lang.String getVectorStyleUrl(); + public abstract com.mapconductor.core.map.MapStyleInstallation onStyleLoaded(kotlin.jvm.functions.Function0); + public abstract void upsertRaster(com.mapconductor.core.raster.RasterLayerState); + public abstract void removeRaster(java.lang.String); + public abstract void report(java.util.List); +} +public final class com.mapconductor.core.map.MapStyleHost$DefaultImpls { + public static java.lang.String getVectorStyleUrl(com.mapconductor.core.map.MapStyleHost); +} +public interface com.mapconductor.core.map.MapStyleInstallation { + public static final com.mapconductor.core.map.MapStyleInstallation$Companion Companion; + public static final com.mapconductor.core.map.MapStyleInstallation NONE; + public abstract void dispose(); + public default boolean update(com.mapconductor.core.map.MapViewStyle); + public static com.mapconductor.core.map.MapStyleInstallation of(kotlin.jvm.functions.Function0); +} +public final class com.mapconductor.core.map.MapStyleInstallation$Companion { + public final com.mapconductor.core.map.MapStyleInstallation of(kotlin.jvm.functions.Function0); +} +public final class com.mapconductor.core.map.MapStyleInstallation$DefaultImpls { + public static boolean update(com.mapconductor.core.map.MapStyleInstallation, com.mapconductor.core.map.MapViewStyle); +} public final class com.mapconductor.core.map.MapUISettings { public static final com.mapconductor.core.map.MapUISettings$Companion Companion; - public com.mapconductor.core.map.MapUISettings(boolean, boolean, boolean, boolean); - public com.mapconductor.core.map.MapUISettings(boolean, boolean, boolean, boolean, int, kotlin.jvm.internal.DefaultConstructorMarker); + public com.mapconductor.core.map.MapUISettings(boolean, boolean, boolean, boolean, com.mapconductor.core.map.MapPaddings); + public com.mapconductor.core.map.MapUISettings(boolean, boolean, boolean, boolean, com.mapconductor.core.map.MapPaddings, int, kotlin.jvm.internal.DefaultConstructorMarker); public final boolean getScrollGesture(); public final boolean getZoomGesture(); public final boolean getRotateGesture(); public final boolean getTiltGesture(); + public final com.mapconductor.core.map.MapPaddings getPaddings(); public final boolean component1(); public final boolean component2(); public final boolean component3(); public final boolean component4(); - public final com.mapconductor.core.map.MapUISettings copy(boolean, boolean, boolean, boolean); + public final com.mapconductor.core.map.MapPaddings component5(); + public final com.mapconductor.core.map.MapUISettings copy(boolean, boolean, boolean, boolean, com.mapconductor.core.map.MapPaddings); public java.lang.String toString(); public int hashCode(); public boolean equals(java.lang.Object); @@ -1105,18 +1242,24 @@ public interface com.mapconductor.core.map.MapViewHolderInterface); public default com.mapconductor.core.features.GeoPoint fromScreenOffsetSync-k-4lQ0M(long); + public default com.mapconductor.core.projection.MapCoordinateSystem getCoordinateSystem(); + public default com.mapconductor.core.projection.ProjectedPoint toProjectedPoint(com.mapconductor.core.features.GeoPointInterface); + public default com.mapconductor.core.features.GeoPoint fromProjectedPoint(com.mapconductor.core.projection.ProjectedPoint); } public final class com.mapconductor.core.map.MapViewHolderInterface$DefaultImpls { public static java.lang.Object fromScreenOffset-3MmeM6k(com.mapconductor.core.map.MapViewHolderInterface, long, kotlin.coroutines.Continuation); public static com.mapconductor.core.features.GeoPoint fromScreenOffsetSync-k-4lQ0M(com.mapconductor.core.map.MapViewHolderInterface, long); + public static com.mapconductor.core.projection.MapCoordinateSystem getCoordinateSystem(com.mapconductor.core.map.MapViewHolderInterface); + public static com.mapconductor.core.projection.ProjectedPoint toProjectedPoint(com.mapconductor.core.map.MapViewHolderInterface, com.mapconductor.core.features.GeoPointInterface); + public static com.mapconductor.core.features.GeoPoint fromProjectedPoint(com.mapconductor.core.map.MapViewHolderInterface, com.mapconductor.core.projection.ProjectedPoint); } public abstract class com.mapconductor.core.map.MapViewHolderStoreBaseAsync extends com.mapconductor.core.map.StaticHolder> { public com.mapconductor.core.map.MapViewHolderStoreBaseAsync(); public abstract java.lang.Object getOrCreate(android.content.Context, java.lang.String, TOptions, kotlin.coroutines.Continuation>); } public abstract class com.mapconductor.core.map.MapViewState implements com.mapconductor.core.map.MapViewStateInterface { - public com.mapconductor.core.map.MapViewState(com.mapconductor.core.map.MapCameraPosition, boolean); - public com.mapconductor.core.map.MapViewState(com.mapconductor.core.map.MapCameraPosition, boolean, int, kotlin.jvm.internal.DefaultConstructorMarker); + public com.mapconductor.core.map.MapViewState(com.mapconductor.core.map.MapCameraPosition, boolean, com.mapconductor.core.map.MapPaddings); + public com.mapconductor.core.map.MapViewState(com.mapconductor.core.map.MapCameraPosition, boolean, com.mapconductor.core.map.MapPaddings, int, kotlin.jvm.internal.DefaultConstructorMarker); public com.mapconductor.core.map.MutableMapServiceRegistry getServiceRegistry(); public com.mapconductor.core.map.MapUISettings getUiSettings(); public void setUiSettings(com.mapconductor.core.map.MapUISettings); @@ -1124,6 +1267,7 @@ public abstract class com.mapconductor.core.map.MapViewState, com.mapconductor.core.map.MapViewStyle, com.mapconductor.core.controller.BaseMapViewController, kotlin.jvm.functions.Function1, kotlin.Unit>, androidx.compose.runtime.Composer, int, int); +} +public final class com.mapconductor.core.map.MapViewStyleHost implements com.mapconductor.core.map.MapStyleHost { + public com.mapconductor.core.map.MapViewStyleHost(com.mapconductor.core.map.MapServiceRegistry, com.mapconductor.core.controller.BaseMapViewController); + public com.mapconductor.core.map.MapServiceRegistry getServiceRegistry(); + public final void apply(com.mapconductor.core.map.MapViewStyle, kotlin.jvm.functions.Function1, kotlin.Unit>); + public final void dispose(); + public com.mapconductor.core.tileserver.LocalTileServer getTileServer(); + public java.lang.String getVectorStyleUrl(); + public com.mapconductor.core.map.MapStyleInstallation onStyleLoaded(kotlin.jvm.functions.Function0); + public void upsertRaster(com.mapconductor.core.raster.RasterLayerState); + public void removeRaster(java.lang.String); + public void report(java.util.List); +} +public final class com.mapconductor.core.map.MapViewStyleHostKt { +} public final class com.mapconductor.core.map.MutableMapServiceRegistry implements com.mapconductor.core.map.MapServiceRegistry { public com.mapconductor.core.map.MutableMapServiceRegistry(); public final void clear(); @@ -1171,6 +1336,167 @@ public abstract class com.mapconductor.core.map.StaticHolder { public final void remove(java.lang.String); public final void clearAll(); } +public abstract class com.mapconductor.core.map.StyleMutation { + public static final com.mapconductor.core.map.StyleMutation$Companion Companion; + public abstract java.lang.String getLayerId(); + public abstract java.lang.String getTarget(); + public java.lang.String getPropertyName(); + public abstract com.mapconductor.core.map.StyleMutation reversed(); + public static final java.util.List parseList(java.lang.String); + public static final java.lang.String jsonTextOf(java.lang.Object); + public com.mapconductor.core.map.StyleMutation(kotlin.jvm.internal.DefaultConstructorMarker); +} +public final class com.mapconductor.core.map.StyleMutation$AddLayer extends com.mapconductor.core.map.StyleMutation { + public java.lang.String getLayerId(); + public final java.lang.String getLayer(); + public final java.lang.String getBeforeId(); + public java.lang.String getTarget(); + public com.mapconductor.core.map.StyleMutation$RemoveLayer reversed(); + public final java.lang.String component1(); + public final java.lang.String component2(); + public final java.lang.String component3(); + public final com.mapconductor.core.map.StyleMutation$AddLayer copy(java.lang.String, java.lang.String, java.lang.String); + public java.lang.String toString(); + public int hashCode(); + public boolean equals(java.lang.Object); + public com.mapconductor.core.map.StyleMutation reversed(); +} +public final class com.mapconductor.core.map.StyleMutation$Companion { + public final java.util.List parseList(java.lang.String); + public final java.lang.String jsonTextOf(java.lang.Object); +} +public final class com.mapconductor.core.map.StyleMutation$RemoveLayer extends com.mapconductor.core.map.StyleMutation { + public java.lang.String getLayerId(); + public java.lang.String getTarget(); + public com.mapconductor.core.map.StyleMutation reversed(); + public final java.lang.String component1(); + public final com.mapconductor.core.map.StyleMutation$RemoveLayer copy(java.lang.String); + public java.lang.String toString(); + public int hashCode(); + public boolean equals(java.lang.Object); +} +public final class com.mapconductor.core.map.StyleMutation$SetFilter extends com.mapconductor.core.map.StyleMutation { + public java.lang.String getLayerId(); + public final java.lang.String getValue(); + public final java.lang.String getPrevious(); + public java.lang.String getTarget(); + public java.lang.String getPropertyName(); + public com.mapconductor.core.map.StyleMutation$SetFilter reversed(); + public final java.lang.String component1(); + public final java.lang.String component2(); + public final java.lang.String component3(); + public final com.mapconductor.core.map.StyleMutation$SetFilter copy(java.lang.String, java.lang.String, java.lang.String); + public java.lang.String toString(); + public int hashCode(); + public boolean equals(java.lang.Object); + public com.mapconductor.core.map.StyleMutation reversed(); +} +public final class com.mapconductor.core.map.StyleMutation$SetLayout extends com.mapconductor.core.map.StyleMutation { + public java.lang.String getLayerId(); + public final java.lang.String getKey(); + public final java.lang.String getValue(); + public final java.lang.String getPrevious(); + public java.lang.String getTarget(); + public java.lang.String getPropertyName(); + public com.mapconductor.core.map.StyleMutation$SetLayout reversed(); + public final java.lang.String component1(); + public final java.lang.String component2(); + public final java.lang.String component3(); + public final java.lang.String component4(); + public final com.mapconductor.core.map.StyleMutation$SetLayout copy(java.lang.String, java.lang.String, java.lang.String, java.lang.String); + public java.lang.String toString(); + public int hashCode(); + public boolean equals(java.lang.Object); + public com.mapconductor.core.map.StyleMutation reversed(); +} +public final class com.mapconductor.core.map.StyleMutation$SetPaint extends com.mapconductor.core.map.StyleMutation { + public java.lang.String getLayerId(); + public final java.lang.String getKey(); + public final java.lang.String getValue(); + public final java.lang.String getPrevious(); + public java.lang.String getTarget(); + public java.lang.String getPropertyName(); + public com.mapconductor.core.map.StyleMutation$SetPaint reversed(); + public final java.lang.String component1(); + public final java.lang.String component2(); + public final java.lang.String component3(); + public final java.lang.String component4(); + public final com.mapconductor.core.map.StyleMutation$SetPaint copy(java.lang.String, java.lang.String, java.lang.String, java.lang.String); + public java.lang.String toString(); + public int hashCode(); + public boolean equals(java.lang.Object); + public com.mapconductor.core.map.StyleMutation reversed(); +} +public final class com.mapconductor.core.map.StyleMutation$SetZoomRange extends com.mapconductor.core.map.StyleMutation { + public java.lang.String getLayerId(); + public final java.lang.Double getMinZoom(); + public final java.lang.Double getMaxZoom(); + public final java.lang.Double getPreviousMinZoom(); + public final java.lang.Double getPreviousMaxZoom(); + public java.lang.String getTarget(); + public java.lang.String getPropertyName(); + public com.mapconductor.core.map.StyleMutation$SetZoomRange reversed(); + public final java.lang.String component1(); + public final java.lang.Double component2(); + public final java.lang.Double component3(); + public final java.lang.Double component4(); + public final java.lang.Double component5(); + public final com.mapconductor.core.map.StyleMutation$SetZoomRange copy(java.lang.String, java.lang.Double, java.lang.Double, java.lang.Double, java.lang.Double); + public java.lang.String toString(); + public int hashCode(); + public boolean equals(java.lang.Object); + public com.mapconductor.core.map.StyleMutation reversed(); +} +public final class com.mapconductor.core.map.StyleMutationStore implements com.mapconductor.core.map.VectorStyleMutationSupport { + public com.mapconductor.core.map.StyleMutationStore(kotlin.jvm.functions.Function1, ? extends java.util.List>); + public java.util.List apply(java.util.List); + public void clear(); + public final void onStyleLoaded(); + public final java.util.List getApplied(); +} +public interface com.mapconductor.core.map.StyleMutationTarget { + public default boolean isReady(); + public abstract boolean hasLayer(java.lang.String); + public abstract void setPaint(java.lang.String, java.lang.String, java.lang.String); + public abstract void setLayout(java.lang.String, java.lang.String, java.lang.String); + public abstract void setFilter(java.lang.String, java.lang.String); + public abstract void setZoomRange(java.lang.String, float, float); + public abstract void addLayer(java.lang.String, java.lang.String, java.lang.String); + public abstract void removeLayer(java.lang.String); +} +public final class com.mapconductor.core.map.StyleMutationTarget$DefaultImpls { + public static boolean isReady(com.mapconductor.core.map.StyleMutationTarget); +} +public final class com.mapconductor.core.map.VectorStyleAsDesign> implements com.mapconductor.core.map.VectorStyleSupport { + public static final long CLEAR_GRACE_MS; + public com.mapconductor.core.map.VectorStyleAsDesign(com.mapconductor.core.map.MapViewStateInterface, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function2, ? extends Design>); + public com.mapconductor.core.map.VectorStyleAsDesign(com.mapconductor.core.map.MapViewStateInterface, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function2, int, kotlin.jvm.internal.DefaultConstructorMarker); + public void showStyle(java.lang.String, java.util.List); + public void clearStyle(); + public java.lang.String getCurrentStyleUrl(); +} +final class com.mapconductor.core.map.VectorStyleAsDesign$Companion { +} +public interface com.mapconductor.core.map.VectorStyleMutationSupport { + public abstract java.util.List apply(java.util.List); + public abstract void clear(); +} +public final class com.mapconductor.core.map.VectorStyleMutationSupportKey implements com.mapconductor.core.map.MapServiceKey { + public static final com.mapconductor.core.map.VectorStyleMutationSupportKey INSTANCE; + public com.mapconductor.core.map.MapCapability getCapability(); +} +public interface com.mapconductor.core.map.VectorStyleSupport { + public abstract void showStyle(java.lang.String, java.util.List); + public abstract void clearStyle(); + public default java.lang.String getCurrentStyleUrl(); +} +public final class com.mapconductor.core.map.VectorStyleSupport$DefaultImpls { + public static java.lang.String getCurrentStyleUrl(com.mapconductor.core.map.VectorStyleSupport); +} +public final class com.mapconductor.core.map.VectorStyleSupportKey implements com.mapconductor.core.map.MapServiceKey { + public static final com.mapconductor.core.map.VectorStyleSupportKey INSTANCE; + public com.mapconductor.core.map.MapCapability getCapability(); +} public final class com.mapconductor.core.map.VisibleRegion { public com.mapconductor.core.map.VisibleRegion(com.mapconductor.core.features.GeoRectBounds, com.mapconductor.core.features.GeoPointInterface, com.mapconductor.core.features.GeoPointInterface, com.mapconductor.core.features.GeoPointInterface, com.mapconductor.core.features.GeoPointInterface); public final com.mapconductor.core.features.GeoRectBounds getBounds(); @@ -1194,6 +1520,9 @@ public final class com.mapconductor.core.map.VisibleRegionBuilderKt { public static final androidx.compose.ui.geometry.Size viewportSizePx(com.mapconductor.core.map.MapViewHolderInterface); } public abstract class com.mapconductor.core.marker.AbstractDefaultIcon extends com.mapconductor.core.marker.AbstractMarkerIcon { + public static final com.mapconductor.core.marker.AbstractDefaultIcon$Companion Companion; + public static final java.lang.String DEFAULT_LABEL_POSITION; + public static final java.lang.String DEFAULT_LABEL_WRITING_MODE; public com.mapconductor.core.marker.AbstractDefaultIcon(com.mapconductor.core.marker.AbstractDefaultIcon$BaseIconProperties); protected final com.mapconductor.core.marker.AbstractDefaultIcon$BaseIconProperties getBaseProperties(); public final long getStrokeColor-0d7_KjU(); @@ -1204,17 +1533,19 @@ public abstract class com.mapconductor.core.marker.AbstractDefaultIcon extends c public final long getLabelTextSize-XSAIIZE(); public final android.graphics.Typeface getLabelTypeFace(); public final long getLabelStrokeColor-0d7_KjU(); + public final java.lang.String getLabelPosition(); + public final java.lang.String getLabelWritingMode(); public final float getIconSize-D9Ej5fM(); + public final boolean getDebug(); public final long getAnchor-F1C5BW0(); public final long getInfoAnchor-F1C5BW0(); - public final boolean getDebug(); protected abstract void drawMarkerFill(android.graphics.Canvas, android.graphics.Path, float, float); protected abstract java.lang.Object getUniqueProperties(); public com.mapconductor.core.marker.BitmapIcon toBitmapIcon(); - protected final void drawMarker(android.graphics.Canvas, float, float, float); + protected final void drawMarker(android.graphics.Canvas, float, float, float, float); protected final android.graphics.Path createMarkerPath(float, float, float); protected final android.graphics.Paint createStrokePaint(float); - protected final void drawLabel-oYZNtH4(android.graphics.Canvas, float, float, long, float); + protected final void drawLabel-INMd_9Y(android.graphics.Canvas, float, long, float, float); protected final float convertTextUnitToPx-eAf_CNQ(long, float); public boolean equals(java.lang.Object); public int hashCode(); @@ -1232,6 +1563,8 @@ public final class com.mapconductor.core.marker.AbstractDefaultIcon$BaseIconProp public final long getInfoAnchor-F1C5BW0(); public final float getIconSize-D9Ej5fM(); public final boolean getDebug(); + public final java.lang.String getLabelPosition(); + public final java.lang.String getLabelWritingMode(); public final long component1-0d7_KjU(); public final float component2-D9Ej5fM(); public final float component3(); @@ -1243,12 +1576,37 @@ public final class com.mapconductor.core.marker.AbstractDefaultIcon$BaseIconProp public final long component9-F1C5BW0(); public final float component10-D9Ej5fM(); public final boolean component11(); - public final com.mapconductor.core.marker.AbstractDefaultIcon$BaseIconProperties copy-CIYJXf0(long, float, float, java.lang.String, androidx.compose.ui.graphics.Color, long, android.graphics.Typeface, long, long, float, boolean); + public final java.lang.String component12(); + public final java.lang.String component13(); + public final com.mapconductor.core.marker.AbstractDefaultIcon$BaseIconProperties copy-KrVDhP0(long, float, float, java.lang.String, androidx.compose.ui.graphics.Color, long, android.graphics.Typeface, long, long, float, boolean, java.lang.String, java.lang.String); public java.lang.String toString(); public int hashCode(); public boolean equals(java.lang.Object); } -public abstract class com.mapconductor.core.marker.AbstractMarkerController implements com.mapconductor.core.controller.SlottedOverlayController>, com.mapconductor.core.marker.MarkerEventHostInterface { +public final class com.mapconductor.core.marker.AbstractDefaultIcon$Companion { +} +final class com.mapconductor.core.marker.AbstractDefaultIcon$IconLayout { + public final int getMarkerSize(); + public final int getBitmapWidth(); + public final int getBitmapHeight(); + public final float getMarkerOffsetX(); + public final float getMarkerOffsetY(); + public final float getLabelCenterX(); + public final float getLabelCenterY(); + public final com.mapconductor.core.marker.LabelTypesetter$Metrics getLabel(); +} +final class com.mapconductor.core.marker.AbstractDefaultIcon$MarkerPathMetrics { + public final float getMarkerScale(); + public final float getOffsetX(); + public final float getOffsetY(); +} +final class com.mapconductor.core.marker.AbstractDefaultIcon$PinBounds { + public final float getLeft(); + public final float getRight(); + public final float getTop(); + public final float getBottom(); +} +public abstract class com.mapconductor.core.marker.AbstractMarkerController implements com.mapconductor.core.controller.SlottedOverlayController>, com.mapconductor.core.marker.MarkerEventHostInterface, com.mapconductor.core.marker.MarkerDrawOrderReceiver { public com.mapconductor.core.marker.AbstractMarkerController(com.mapconductor.core.marker.MarkerManager, com.mapconductor.core.marker.MarkerOverlayRendererInterface, kotlin.jvm.functions.Function1); public com.mapconductor.core.marker.AbstractMarkerController(com.mapconductor.core.marker.MarkerManager, com.mapconductor.core.marker.MarkerOverlayRendererInterface, kotlin.jvm.functions.Function1, int, kotlin.jvm.internal.DefaultConstructorMarker); public com.mapconductor.core.marker.MarkerManager getMarkerManager(); @@ -1284,6 +1642,7 @@ public abstract class com.mapconductor.core.marker.AbstractMarkerController getEntity(java.lang.String); public boolean has(java.lang.String); + public java.lang.Object onDrawOrderFrameChanged(com.mapconductor.core.marker.MarkerDrawOrder$Frame, kotlin.coroutines.Continuation); public void setClickListenerAny(java.lang.Object); public java.lang.Object update(java.lang.Object, kotlin.coroutines.Continuation); public java.lang.Object find(com.mapconductor.core.features.GeoPointInterface); @@ -1313,6 +1672,11 @@ public abstract class com.mapconductor.core.marker.AbstractMarkerOverlayRenderer public final com.mapconductor.core.marker.MarkerAnimationOverlayHost getAnimationOverlayHost(); public final void setAnimationOverlayHost(com.mapconductor.core.marker.MarkerAnimationOverlayHost); public boolean getSupportsAnimationOverlay(); + public final com.mapconductor.core.marker.MarkerDrawOrder$Frame getDrawOrderFrame(); + public final double drawOrderOf(com.mapconductor.core.marker.MarkerState); + public final int drawOrderIntOf(com.mapconductor.core.marker.MarkerState); + public java.lang.Object onDrawOrderFrameChanged(com.mapconductor.core.marker.MarkerDrawOrder$Frame, java.util.List>, kotlin.coroutines.Continuation); + protected java.lang.Object applyDrawOrder(java.util.List>, kotlin.coroutines.Continuation); public void setMarkerVisible(com.mapconductor.core.marker.MarkerEntityInterface, boolean); public abstract void setMarkerPosition(com.mapconductor.core.marker.MarkerEntityInterface, com.mapconductor.core.features.GeoPoint); public java.lang.Object onAnimate(com.mapconductor.core.marker.MarkerEntityInterface, kotlin.coroutines.Continuation); @@ -1361,45 +1725,63 @@ public final class com.mapconductor.core.marker.ClickableMarkerKt { public static final com.mapconductor.core.marker.MarkerEntityInterface clickableOnly(com.mapconductor.core.marker.MarkerEntityInterface); } public final class com.mapconductor.core.marker.ColorDefaultIcon extends com.mapconductor.core.marker.AbstractDefaultIcon { - public com.mapconductor.core.marker.ColorDefaultIcon(long, long, float, float, java.lang.String, androidx.compose.ui.graphics.Color, long, android.graphics.Typeface, long, long, float, boolean, int, kotlin.jvm.internal.DefaultConstructorMarker); + public com.mapconductor.core.marker.ColorDefaultIcon(long, long, float, float, java.lang.String, androidx.compose.ui.graphics.Color, long, android.graphics.Typeface, long, java.lang.String, java.lang.String, long, float, boolean, int, kotlin.jvm.internal.DefaultConstructorMarker); protected void drawMarkerFill(android.graphics.Canvas, android.graphics.Path, float, float); protected java.lang.Object getUniqueProperties(); - public final com.mapconductor.core.marker.ColorDefaultIcon copy-ArqVBMg(long, long, float, float, java.lang.String, androidx.compose.ui.graphics.Color, long, android.graphics.Typeface, long, float, boolean); + public final com.mapconductor.core.marker.ColorDefaultIcon copy-9HuT76Q(long, long, float, float, java.lang.String, androidx.compose.ui.graphics.Color, long, android.graphics.Typeface, long, java.lang.String, java.lang.String, float, boolean); public final com.mapconductor.core.marker.ColorDefaultIcon copy-3ABfNKs(float, float); public com.mapconductor.core.marker.ColorDefaultIcon(long, com.mapconductor.core.marker.AbstractDefaultIcon$BaseIconProperties, kotlin.jvm.internal.DefaultConstructorMarker); - public com.mapconductor.core.marker.ColorDefaultIcon(long, long, float, float, java.lang.String, androidx.compose.ui.graphics.Color, long, android.graphics.Typeface, long, long, float, boolean, kotlin.jvm.internal.DefaultConstructorMarker); + public com.mapconductor.core.marker.ColorDefaultIcon(long, long, float, float, java.lang.String, androidx.compose.ui.graphics.Color, long, android.graphics.Typeface, long, java.lang.String, java.lang.String, long, float, boolean, kotlin.jvm.internal.DefaultConstructorMarker); } public final class com.mapconductor.core.marker.ColorDefaultIconKt { } public final class com.mapconductor.core.marker.DrawableDefaultIcon extends com.mapconductor.core.marker.AbstractDefaultIcon { public com.mapconductor.core.marker.DrawableDefaultIcon(android.graphics.drawable.Drawable, com.mapconductor.core.marker.AbstractDefaultIcon$BaseIconProperties); - public com.mapconductor.core.marker.DrawableDefaultIcon(android.graphics.drawable.Drawable, long, float, float, java.lang.String, androidx.compose.ui.graphics.Color, long, android.graphics.Typeface, long, long, float, boolean, int, kotlin.jvm.internal.DefaultConstructorMarker); + public com.mapconductor.core.marker.DrawableDefaultIcon(android.graphics.drawable.Drawable, long, float, float, java.lang.String, androidx.compose.ui.graphics.Color, long, android.graphics.Typeface, long, java.lang.String, long, float, boolean, int, kotlin.jvm.internal.DefaultConstructorMarker); protected void drawMarkerFill(android.graphics.Canvas, android.graphics.Path, float, float); protected java.lang.Object getUniqueProperties(); - public final com.mapconductor.core.marker.DrawableDefaultIcon copy-NoBYCTc(android.graphics.drawable.Drawable, long, float, float, java.lang.String, androidx.compose.ui.graphics.Color, long, android.graphics.Typeface, long, float, boolean); + public final com.mapconductor.core.marker.DrawableDefaultIcon copy-cvAzyPI(android.graphics.drawable.Drawable, long, float, float, java.lang.String, androidx.compose.ui.graphics.Color, long, android.graphics.Typeface, long, java.lang.String, float, boolean); public final com.mapconductor.core.marker.DrawableDefaultIcon copy-3ABfNKs(float, float); - public com.mapconductor.core.marker.DrawableDefaultIcon(android.graphics.drawable.Drawable, long, float, float, java.lang.String, androidx.compose.ui.graphics.Color, long, android.graphics.Typeface, long, long, float, boolean, kotlin.jvm.internal.DefaultConstructorMarker); + public com.mapconductor.core.marker.DrawableDefaultIcon(android.graphics.drawable.Drawable, long, float, float, java.lang.String, androidx.compose.ui.graphics.Color, long, android.graphics.Typeface, long, java.lang.String, long, float, boolean, kotlin.jvm.internal.DefaultConstructorMarker); } public final class com.mapconductor.core.marker.ImageDefaultIcon extends com.mapconductor.core.marker.AbstractDefaultIcon { public com.mapconductor.core.marker.ImageDefaultIcon(android.graphics.Bitmap, com.mapconductor.core.marker.AbstractDefaultIcon$BaseIconProperties); - public com.mapconductor.core.marker.ImageDefaultIcon(android.graphics.Bitmap, long, float, float, java.lang.String, androidx.compose.ui.graphics.Color, long, android.graphics.Typeface, long, long, float, boolean, int, kotlin.jvm.internal.DefaultConstructorMarker); + public com.mapconductor.core.marker.ImageDefaultIcon(android.graphics.Bitmap, long, float, float, java.lang.String, androidx.compose.ui.graphics.Color, long, android.graphics.Typeface, long, java.lang.String, long, float, boolean, int, kotlin.jvm.internal.DefaultConstructorMarker); protected void drawMarkerFill(android.graphics.Canvas, android.graphics.Path, float, float); protected java.lang.Object getUniqueProperties(); - public final com.mapconductor.core.marker.ImageDefaultIcon copy-NoBYCTc(android.graphics.Bitmap, long, float, float, java.lang.String, androidx.compose.ui.graphics.Color, long, android.graphics.Typeface, long, float, boolean); + public final com.mapconductor.core.marker.ImageDefaultIcon copy-cvAzyPI(android.graphics.Bitmap, long, float, float, java.lang.String, androidx.compose.ui.graphics.Color, long, android.graphics.Typeface, long, java.lang.String, float, boolean); public final com.mapconductor.core.marker.ImageDefaultIcon copy-3ABfNKs(float, float); - public com.mapconductor.core.marker.ImageDefaultIcon(android.graphics.Bitmap, long, float, float, java.lang.String, androidx.compose.ui.graphics.Color, long, android.graphics.Typeface, long, long, float, boolean, kotlin.jvm.internal.DefaultConstructorMarker); + public com.mapconductor.core.marker.ImageDefaultIcon(android.graphics.Bitmap, long, float, float, java.lang.String, androidx.compose.ui.graphics.Color, long, android.graphics.Typeface, long, java.lang.String, long, float, boolean, kotlin.jvm.internal.DefaultConstructorMarker); } public final class com.mapconductor.core.marker.ImageIcon extends com.mapconductor.core.marker.AndroidDrawableIcon { - public com.mapconductor.core.marker.ImageIcon(android.graphics.drawable.Drawable, float, float, long, long, boolean, int, kotlin.jvm.internal.DefaultConstructorMarker); + public com.mapconductor.core.marker.ImageIcon(android.graphics.drawable.Drawable, float, float, long, long, boolean, java.lang.String, androidx.compose.ui.graphics.Color, long, android.graphics.Typeface, long, java.lang.String, java.lang.String, int, kotlin.jvm.internal.DefaultConstructorMarker); public float getIconSize-D9Ej5fM(); public float getScale(); + public boolean getDebug(); + public final java.lang.String getLabel(); + public final androidx.compose.ui.graphics.Color getLabelTextColor-QN2ZGVo(); + public final long getLabelTextSize-XSAIIZE(); + public final android.graphics.Typeface getLabelTypeFace(); + public final long getLabelStrokeColor-0d7_KjU(); + public final java.lang.String getLabelPosition(); + public final java.lang.String getLabelWritingMode(); + public com.mapconductor.core.marker.ImageIcon(java.lang.String, float, float, long, long, boolean, java.lang.String, androidx.compose.ui.graphics.Color, long, android.graphics.Typeface, long, java.lang.String, java.lang.String, int, kotlin.jvm.internal.DefaultConstructorMarker); + public final java.lang.String getImageUrl(); public long getAnchor-F1C5BW0(); public long getInfoAnchor-F1C5BW0(); - public boolean getDebug(); public boolean equals(java.lang.Object); public int hashCode(); public com.mapconductor.core.marker.BitmapIcon toBitmapIcon(); - public com.mapconductor.core.marker.ImageIcon(android.graphics.drawable.Drawable, float, float, long, long, boolean, kotlin.jvm.internal.DefaultConstructorMarker); + public final com.mapconductor.core.marker.ImageIcon copy-MQQ_14o(android.graphics.drawable.Drawable, float, float, long, long, boolean, java.lang.String, androidx.compose.ui.graphics.Color, long, android.graphics.Typeface, long, java.lang.String, java.lang.String); + public com.mapconductor.core.marker.ImageIcon(android.graphics.drawable.Drawable, float, float, long, long, boolean, java.lang.String, androidx.compose.ui.graphics.Color, long, android.graphics.Typeface, long, java.lang.String, java.lang.String, kotlin.jvm.internal.DefaultConstructorMarker); + public com.mapconductor.core.marker.ImageIcon(java.lang.String, float, float, long, long, boolean, java.lang.String, androidx.compose.ui.graphics.Color, long, android.graphics.Typeface, long, java.lang.String, java.lang.String, kotlin.jvm.internal.DefaultConstructorMarker); +} +final class com.mapconductor.core.marker.ImageIcon$Layout { + public final int getCanvasSize(); + public final com.mapconductor.core.marker.IconLabelLayout$Result getResult(); + public final com.mapconductor.core.marker.LabelTypesetter$Metrics getLabel(); + public final float getTextSizePx(); + public final float getOutlinePx(); } public final class com.mapconductor.core.marker.MarkerAnimation extends java.lang.Enum { public static final com.mapconductor.core.marker.MarkerAnimation Drop; @@ -1455,6 +1837,21 @@ public final class com.mapconductor.core.marker.MarkerCollector implements com.m public java.lang.Object add(com.mapconductor.core.ComponentState, kotlin.coroutines.Continuation); public com.mapconductor.core.marker.MarkerCollector(long, kotlinx.coroutines.CoroutineScope, kotlin.jvm.internal.DefaultConstructorMarker); } +public final class com.mapconductor.core.marker.MarkerDrawOrder$Frame { + public static final com.mapconductor.core.marker.MarkerDrawOrder$Frame$Companion Companion; + public final double getHeadingDegrees(); + public final double getOriginLongitude(); + public final boolean differsEnoughFrom(com.mapconductor.core.marker.MarkerDrawOrder$Frame); + public final double component1(); + public final double component2(); + public final com.mapconductor.core.marker.MarkerDrawOrder$Frame copy(double, double); + public java.lang.String toString(); + public int hashCode(); + public boolean equals(java.lang.Object); +} +public final class com.mapconductor.core.marker.MarkerDrawOrder$Frame$Companion { + public final com.mapconductor.core.marker.MarkerDrawOrder$Frame getNorthUp(); +} public final class com.mapconductor.core.marker.MarkerEntity implements com.mapconductor.core.marker.MarkerEntityInterface { public com.mapconductor.core.marker.MarkerEntity(ActualMarker, com.mapconductor.core.marker.MarkerState, boolean, boolean, boolean); public com.mapconductor.core.marker.MarkerEntity(java.lang.Object, com.mapconductor.core.marker.MarkerState, boolean, boolean, boolean, int, kotlin.jvm.internal.DefaultConstructorMarker); @@ -1546,10 +1943,10 @@ public class com.mapconductor.core.marker.MarkerManager { public com.mapconductor.core.marker.MarkerEntityInterface removeEntity(java.lang.String); public double metersPerPixel(com.mapconductor.core.features.GeoPointInterface, double, double, int); public com.mapconductor.core.marker.MarkerEntityInterface findNearest(com.mapconductor.core.features.GeoPointInterface); - public java.util.List findByIdPrefix(java.lang.String); public void registerEntity(com.mapconductor.core.marker.MarkerEntityInterface); public void updateEntity(com.mapconductor.core.marker.MarkerEntityInterface); public java.util.List> allEntities(); + public final java.util.List> findMarkersInBounds(com.mapconductor.core.features.GeoRectBounds, double); public final com.mapconductor.core.marker.MarkerManagerStats getMemoryStats(); public void clear(); public final java.util.List> findMarkersInBounds(com.mapconductor.core.features.GeoRectBounds); @@ -1592,6 +1989,7 @@ public interface com.mapconductor.core.marker.MarkerOverlayRendererInterface); public default void onDragSelectionChanged(com.mapconductor.core.marker.MarkerEntityInterface, com.mapconductor.core.marker.MarkerEntityInterface); public default void onDragPositionChanged(com.mapconductor.core.features.GeoPointInterface); + public default java.lang.Object onDrawOrderFrameChanged(com.mapconductor.core.marker.MarkerDrawOrder$Frame, java.util.List>, kotlin.coroutines.Continuation); } public interface com.mapconductor.core.marker.MarkerOverlayRendererInterface$AddParamsInterface { public abstract com.mapconductor.core.marker.MarkerState getState(); @@ -1605,6 +2003,7 @@ public interface com.mapconductor.core.marker.MarkerOverlayRendererInterface$Cha public final class com.mapconductor.core.marker.MarkerOverlayRendererInterface$DefaultImpls { public static void onDragSelectionChanged(com.mapconductor.core.marker.MarkerOverlayRendererInterface, com.mapconductor.core.marker.MarkerEntityInterface, com.mapconductor.core.marker.MarkerEntityInterface); public static void onDragPositionChanged(com.mapconductor.core.marker.MarkerOverlayRendererInterface, com.mapconductor.core.features.GeoPointInterface); + public static java.lang.Object onDrawOrderFrameChanged(com.mapconductor.core.marker.MarkerOverlayRendererInterface, com.mapconductor.core.marker.MarkerDrawOrder$Frame, java.util.List>, kotlin.coroutines.Continuation); } public interface com.mapconductor.core.marker.MarkerRenderingStrategyInterface { public abstract com.mapconductor.core.marker.MarkerManager getMarkerManager(); @@ -1629,11 +2028,12 @@ public final class com.mapconductor.core.marker.MarkerRenderingSupportKey implem public com.mapconductor.core.map.MapCapability getCapability(); } public final class com.mapconductor.core.marker.MarkerState implements com.mapconductor.core.ComponentState { - public com.mapconductor.core.marker.MarkerState(com.mapconductor.core.features.GeoPointInterface, java.lang.String, java.io.Serializable, com.mapconductor.core.marker.MarkerIconInterface, com.mapconductor.core.marker.MarkerAnimation, java.lang.Integer, boolean, boolean, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1); - public com.mapconductor.core.marker.MarkerState(com.mapconductor.core.features.GeoPointInterface, java.lang.String, java.io.Serializable, com.mapconductor.core.marker.MarkerIconInterface, com.mapconductor.core.marker.MarkerAnimation, java.lang.Integer, boolean, boolean, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, int, kotlin.jvm.internal.DefaultConstructorMarker); + public com.mapconductor.core.marker.MarkerState(com.mapconductor.core.features.GeoPointInterface, java.lang.String, java.io.Serializable, com.mapconductor.core.marker.MarkerIconInterface, com.mapconductor.core.marker.MarkerAnimation, java.lang.Integer, boolean, boolean, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1); + public com.mapconductor.core.marker.MarkerState(com.mapconductor.core.features.GeoPointInterface, java.lang.String, java.io.Serializable, com.mapconductor.core.marker.MarkerIconInterface, com.mapconductor.core.marker.MarkerAnimation, java.lang.Integer, boolean, boolean, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, int, kotlin.jvm.internal.DefaultConstructorMarker); public final java.io.Serializable getExtra(); public final void setExtra(java.io.Serializable); public java.lang.String getId(); + public com.mapconductor.core.StateMutationSignal getMutations(); public final com.mapconductor.core.marker.MarkerIconInterface getIcon(); public final void setIcon(com.mapconductor.core.marker.MarkerIconInterface); public final boolean getClickable(); @@ -1652,30 +2052,35 @@ public final class com.mapconductor.core.marker.MarkerState implements com.mapco public final void setOnAnimateStart(kotlin.jvm.functions.Function1); public final kotlin.jvm.functions.Function1 getOnAnimateEnd(); public final void setOnAnimateEnd(kotlin.jvm.functions.Function1); + public final kotlin.jvm.functions.Function1 getOnAdded(); + public final void setOnAdded(kotlin.jvm.functions.Function1); public final java.lang.Integer getZIndex(); public final void setZIndex(java.lang.Integer); + public com.mapconductor.core.marker.MarkerState(com.mapconductor.core.features.GeoPointInterface, java.lang.String, java.io.Serializable, com.mapconductor.core.marker.MarkerIconInterface, com.mapconductor.core.marker.MarkerAnimation, java.lang.Integer, boolean, boolean, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1); + public com.mapconductor.core.marker.MarkerState(com.mapconductor.core.features.GeoPointInterface, java.lang.String, java.io.Serializable, com.mapconductor.core.marker.MarkerIconInterface, com.mapconductor.core.marker.MarkerAnimation, java.lang.Integer, boolean, boolean, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, int, kotlin.jvm.internal.DefaultConstructorMarker); public final void animate(com.mapconductor.core.marker.MarkerAnimation); public final com.mapconductor.core.marker.MarkerAnimation getAnimation(); public final com.mapconductor.core.features.GeoPointInterface getPosition(); public final void setPosition(com.mapconductor.core.features.GeoPointInterface); - public final com.mapconductor.core.marker.MarkerState copy(java.lang.String, com.mapconductor.core.features.GeoPointInterface, java.io.Serializable, com.mapconductor.core.marker.MarkerIconInterface, com.mapconductor.core.marker.MarkerAnimation, java.lang.Integer, java.lang.Boolean, java.lang.Boolean, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1); + public final com.mapconductor.core.marker.MarkerState copy(java.lang.String, com.mapconductor.core.features.GeoPointInterface, java.io.Serializable, com.mapconductor.core.marker.MarkerIconInterface, com.mapconductor.core.marker.MarkerAnimation, java.lang.Integer, java.lang.Boolean, java.lang.Boolean, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1); + public final com.mapconductor.core.marker.MarkerState copy(java.lang.String, com.mapconductor.core.features.GeoPointInterface, java.io.Serializable, com.mapconductor.core.marker.MarkerIconInterface, com.mapconductor.core.marker.MarkerAnimation, java.lang.Integer, java.lang.Boolean, java.lang.Boolean, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1); public boolean equals(java.lang.Object); public int hashCode(); public final com.mapconductor.core.marker.MarkerFingerPrint fingerPrint(); - public final kotlinx.coroutines.flow.Flow asFlow(); } public interface com.mapconductor.core.marker.MarkerTileRasterLayerCallback { public abstract java.lang.Object onRasterLayerUpdate(com.mapconductor.core.raster.RasterLayerState, kotlin.coroutines.Continuation); } public final class com.mapconductor.core.marker.MarkerTileRenderer implements com.mapconductor.core.tileserver.TileProviderInterface { - public com.mapconductor.core.marker.MarkerTileRenderer(com.mapconductor.core.marker.MarkerManager, int, int, boolean, kotlin.jvm.functions.Function2, double); - public com.mapconductor.core.marker.MarkerTileRenderer(com.mapconductor.core.marker.MarkerManager, int, int, boolean, kotlin.jvm.functions.Function2, double, int, kotlin.jvm.internal.DefaultConstructorMarker); + public com.mapconductor.core.marker.MarkerTileRenderer(com.mapconductor.core.marker.MarkerManager, int, int, boolean, kotlin.jvm.functions.Function2, double, int, kotlin.jvm.functions.Function0); + public com.mapconductor.core.marker.MarkerTileRenderer(com.mapconductor.core.marker.MarkerManager, int, int, boolean, kotlin.jvm.functions.Function2, double, int, kotlin.jvm.functions.Function0, int, kotlin.jvm.internal.DefaultConstructorMarker); public final com.mapconductor.core.marker.MarkerManager getMarkerManager(); public final int getTileSize(); public final double getExtraIconScale(); public final void invalidate(); public final void clear(); public byte[] renderTile(com.mapconductor.core.tileserver.TileRequest); + public byte[] renderTile(com.mapconductor.core.tileserver.TileRequest, kotlin.jvm.functions.Function0); } final class com.mapconductor.core.marker.MarkerTileRenderer$Companion { } @@ -1685,25 +2090,30 @@ public final class com.mapconductor.core.marker.MarkerTileRenderer$renderTile$Pr public final float getDrawW(); public final float getDrawH(); public final long getAnchor(); + public final com.mapconductor.core.marker.MarkerTileLabel getLabel(); + public final float getScale(); public final android.graphics.Bitmap component1(); public final com.mapconductor.core.marker.PointD component2(); public final float component3(); public final float component4(); public final long component5(); - public final com.mapconductor.core.marker.MarkerTileRenderer$renderTile$PreparedMarker copy(android.graphics.Bitmap, com.mapconductor.core.marker.PointD, float, float, long); + public final com.mapconductor.core.marker.MarkerTileLabel component6(); + public final float component7(); + public final com.mapconductor.core.marker.MarkerTileRenderer$renderTile$PreparedMarker copy(android.graphics.Bitmap, com.mapconductor.core.marker.PointD, float, float, long, com.mapconductor.core.marker.MarkerTileLabel, float); public java.lang.String toString(); public int hashCode(); public boolean equals(java.lang.Object); } public final class com.mapconductor.core.marker.MarkerTilingOptions { public static final com.mapconductor.core.marker.MarkerTilingOptions$Companion Companion; - public com.mapconductor.core.marker.MarkerTilingOptions(boolean, boolean, int, int, kotlin.jvm.functions.Function2); - public com.mapconductor.core.marker.MarkerTilingOptions(boolean, boolean, int, int, kotlin.jvm.functions.Function2, int, kotlin.jvm.internal.DefaultConstructorMarker); + public com.mapconductor.core.marker.MarkerTilingOptions(boolean, boolean, int, int, kotlin.jvm.functions.Function2, int); + public com.mapconductor.core.marker.MarkerTilingOptions(boolean, boolean, int, int, kotlin.jvm.functions.Function2, int, int, kotlin.jvm.internal.DefaultConstructorMarker); public final boolean getEnabled(); public final boolean getDebugTileOverlay(); public final int getMinMarkerCount(); public final int getCacheSize(); public final kotlin.jvm.functions.Function2 getIconScaleCallback(); + public final int getDeclutterPx(); public final com.mapconductor.core.marker.MarkerViewportPolicy getViewport(); public final boolean shouldUseTiles(int); public final boolean component1(); @@ -1711,7 +2121,8 @@ public final class com.mapconductor.core.marker.MarkerTilingOptions { public final int component3(); public final int component4(); public final kotlin.jvm.functions.Function2 component5(); - public final com.mapconductor.core.marker.MarkerTilingOptions copy(boolean, boolean, int, int, kotlin.jvm.functions.Function2); + public final int component6(); + public final com.mapconductor.core.marker.MarkerTilingOptions copy(boolean, boolean, int, int, kotlin.jvm.functions.Function2, int); public java.lang.String toString(); public int hashCode(); public boolean equals(java.lang.Object); @@ -1785,7 +2196,7 @@ public final class com.mapconductor.core.marker.PointD { public int hashCode(); public boolean equals(java.lang.Object); } -public final class com.mapconductor.core.marker.StrategyMarkerController implements com.mapconductor.core.controller.SlottedOverlayController>, com.mapconductor.core.controller.OnCameraChangeReceiverInterface, com.mapconductor.core.marker.MarkerEventHostInterface { +public final class com.mapconductor.core.marker.StrategyMarkerController implements com.mapconductor.core.controller.SlottedOverlayController>, com.mapconductor.core.controller.OnCameraChangeReceiverInterface, com.mapconductor.core.marker.MarkerEventHostInterface, com.mapconductor.core.marker.MarkerDrawOrderReceiver { public com.mapconductor.core.marker.StrategyMarkerController(com.mapconductor.core.marker.MarkerRenderingStrategyInterface, com.mapconductor.core.marker.MarkerOverlayRendererInterface); public com.mapconductor.core.marker.MarkerOverlayRendererInterface getRenderer(); public com.mapconductor.core.marker.MarkerManager getMarkerManager(); @@ -1814,6 +2225,7 @@ public final class com.mapconductor.core.marker.StrategyMarkerController getEntity(java.lang.String); public com.mapconductor.core.marker.MarkerEntityInterface find(com.mapconductor.core.features.GeoPointInterface); public java.lang.Object onCameraChanged(com.mapconductor.core.map.MapCameraPosition, kotlin.coroutines.Continuation); + public java.lang.Object onDrawOrderFrameChanged(com.mapconductor.core.marker.MarkerDrawOrder$Frame, kotlin.coroutines.Continuation); public void destroy(); public com.mapconductor.core.controller.OverlayKind getKind(); public com.mapconductor.core.controller.OverlayHit resolveTap(com.mapconductor.core.features.GeoPointInterface); @@ -1858,10 +2270,31 @@ final class com.mapconductor.core.polygon.Edge { public int hashCode(); public boolean equals(java.lang.Object); } +final class com.mapconductor.core.polygon.EdgeGrid { + public com.mapconductor.core.polygon.EdgeGrid(java.util.List, double); + public final com.mapconductor.core.polygon.IntArrayList near(double, double, double, double, com.mapconductor.core.polygon.IntArrayList); +} public final class com.mapconductor.core.polygon.HoleBridgeKt { public static final java.util.List bridgeHolesIntoSingleRing(java.util.List, java.util.List>, double); public static final java.util.List bridgeHolesIntoSingleRingWrapAware(java.util.List, java.util.List>, double); } +final class com.mapconductor.core.polygon.IntArrayList { + public com.mapconductor.core.polygon.IntArrayList(); + public final int getSize(); + public final int get(int); + public final void add(int); + public final void clear(); +} +public final class com.mapconductor.core.polygon.IntList { + public com.mapconductor.core.polygon.IntList(int); + public com.mapconductor.core.polygon.IntList(int, int, kotlin.jvm.internal.DefaultConstructorMarker); + public final int getSize(); + public final void add(int); + public final int pop(); + public final int[] toArray(); + public final int[] toSortedDistinctArray(); + public com.mapconductor.core.polygon.IntList(); +} final class com.mapconductor.core.polygon.Node { public com.mapconductor.core.polygon.Node(double, double, com.mapconductor.core.features.GeoPointInterface); public final double getX(); @@ -1899,6 +2332,8 @@ public abstract class com.mapconductor.core.polygon.PolygonController getClickListener(); public final void setClickListener(kotlin.jvm.functions.Function1); + public final com.mapconductor.core.polygon.PolygonTiler getTiler(); + public final void setTiler(com.mapconductor.core.polygon.PolygonTiler); public final void dispatchClick(com.mapconductor.core.polygon.PolygonEvent); public java.lang.Object add(java.util.List, kotlin.coroutines.Continuation); public java.lang.Object update(com.mapconductor.core.polygon.PolygonState, kotlin.coroutines.Continuation); @@ -1959,6 +2394,14 @@ public final class com.mapconductor.core.polygon.PolygonFingerPrint { public int hashCode(); public boolean equals(java.lang.Object); } +public final class com.mapconductor.core.polygon.PolygonGridIndex { + public static final com.mapconductor.core.polygon.PolygonGridIndex$Companion Companion; + public com.mapconductor.core.polygon.PolygonGridIndex(java.util.HashMap, int[]); + public final int[] query(com.mapconductor.core.polygon.TilePolygon[], double, double, double, double); +} +public final class com.mapconductor.core.polygon.PolygonGridIndex$Companion { + public final com.mapconductor.core.polygon.PolygonGridIndex build(com.mapconductor.core.polygon.TilePolygon[]); +} public final class com.mapconductor.core.polygon.PolygonHolePieceSplitKt { public static final kotlin.Pair, java.util.List> splitPiece(java.util.List, java.util.List, java.util.List>); public static final com.mapconductor.core.features.GeoPointInterface mirrorLngPoint(com.mapconductor.core.features.GeoPointInterface); @@ -2021,8 +2464,9 @@ public interface com.mapconductor.core.polygon.PolygonOverlayRendererInterface$C public abstract com.mapconductor.core.polygon.PolygonEntityInterface getPrev(); } public final class com.mapconductor.core.polygon.PolygonState implements com.mapconductor.core.ComponentState { - public com.mapconductor.core.polygon.PolygonState(java.util.List, java.util.List, java.lang.String, long, float, long, boolean, boolean, int, java.io.Serializable, kotlin.jvm.functions.Function1, int, kotlin.jvm.internal.DefaultConstructorMarker); + public com.mapconductor.core.polygon.PolygonState(java.util.List, java.util.List, java.lang.String, long, float, long, boolean, boolean, int, java.io.Serializable, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, int, kotlin.jvm.internal.DefaultConstructorMarker); public java.lang.String getId(); + public com.mapconductor.core.StateMutationSignal getMutations(); public final long getStrokeColor-0d7_KjU(); public final void setStrokeColor-8_81llA(long); public final float getStrokeWidth-D9Ej5fM(); @@ -2043,13 +2487,109 @@ public final class com.mapconductor.core.polygon.PolygonState implements com.map public final void setExtra(java.io.Serializable); public final kotlin.jvm.functions.Function1 getOnClick(); public final void setOnClick(kotlin.jvm.functions.Function1); + public final kotlin.jvm.functions.Function1 getOnAdded(); + public final void setOnAdded(kotlin.jvm.functions.Function1); + public com.mapconductor.core.polygon.PolygonState(java.util.List, java.util.List, java.lang.String, long, float, long, boolean, boolean, int, java.io.Serializable, kotlin.jvm.functions.Function1, int, kotlin.jvm.internal.DefaultConstructorMarker); public boolean equals(java.lang.Object); public int hashCode(); public final com.mapconductor.core.polygon.PolygonFingerPrint fingerPrint(); - public final com.mapconductor.core.polygon.PolygonState copy-lqbfp2Q(java.util.List, java.util.List>, java.lang.String, long, float, long, boolean, boolean, int, java.io.Serializable, kotlin.jvm.functions.Function1); - public final kotlinx.coroutines.flow.Flow asFlow(); + public final com.mapconductor.core.polygon.PolygonState copy-OuNi0Z8(java.util.List, java.util.List>, java.lang.String, long, float, long, boolean, boolean, int, java.io.Serializable, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1); + public final com.mapconductor.core.polygon.PolygonState copy-lqbfp2Q(java.util.List, java.util.List, java.lang.String, long, float, long, boolean, boolean, int, java.io.Serializable, kotlin.jvm.functions.Function1); + public com.mapconductor.core.polygon.PolygonState(java.util.List, java.util.List, java.lang.String, long, float, long, boolean, boolean, int, java.io.Serializable, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.internal.DefaultConstructorMarker); public com.mapconductor.core.polygon.PolygonState(java.util.List, java.util.List, java.lang.String, long, float, long, boolean, boolean, int, java.io.Serializable, kotlin.jvm.functions.Function1, kotlin.jvm.internal.DefaultConstructorMarker); } +public final class com.mapconductor.core.polygon.PolygonTileGeometryKt { + public static final double POLYGON_CELL; + public static final int POLYGON_MAX_CELLS; + public static final double DP_TOLERANCE_PX; + public static final double MIN_OUTLINED_PX; + public static final boolean isVisibleColor(int); + public static final double[] toMercatorRing(java.util.List); + public static final double signedArea(double[]); + public static final double[] reversedRing(double[]); + public static final com.mapconductor.core.polygon.TileShape simplifyPolygon(com.mapconductor.core.polygon.TilePolygon, double); + public static final double[] simplifyRing(double[], double); + public static final double[] douglasPeucker(double[], int, double); + public static final int vertexCountOf(java.util.List); +} +public final class com.mapconductor.core.polygon.PolygonTileRenderer implements com.mapconductor.core.tileserver.TileProviderInterface { + public static final com.mapconductor.core.polygon.PolygonTileRenderer$Companion Companion; + public static final int DEFAULT_CACHE_BYTES; + public com.mapconductor.core.polygon.PolygonTileRenderer(int, int, kotlin.jvm.functions.Function0); + public com.mapconductor.core.polygon.PolygonTileRenderer(int, int, kotlin.jvm.functions.Function0, int, kotlin.jvm.internal.DefaultConstructorMarker); + public final int getTileSize(); + public final void setPolygons(java.util.List); + public final void update(java.util.List>); + public final void clear(); + public byte[] renderTile(com.mapconductor.core.tileserver.TileRequest); + public byte[] renderTile(com.mapconductor.core.tileserver.TileRequest, kotlin.jvm.functions.Function0); + public final android.graphics.Bitmap renderBitmap(int, int, int, int); + public com.mapconductor.core.polygon.PolygonTileRenderer(); +} +public final class com.mapconductor.core.polygon.PolygonTileRenderer$Companion { +} +public final class com.mapconductor.core.polygon.PolygonTileRenderer$TileRenderCancelled extends java.lang.Exception { +} +public final class com.mapconductor.core.polygon.PolygonTileSet { + public static final com.mapconductor.core.polygon.PolygonTileSet$Companion Companion; + public com.mapconductor.core.polygon.PolygonTileSet(com.mapconductor.core.tileserver.LocalTileServer, kotlinx.coroutines.CoroutineScope); + public com.mapconductor.core.polygon.PolygonTileSet(com.mapconductor.core.tileserver.LocalTileServer, kotlinx.coroutines.CoroutineScope, int, kotlin.jvm.internal.DefaultConstructorMarker); + public final java.lang.String getRouteId(); + public final kotlin.jvm.functions.Function2, java.lang.Object> getOnTemplateChanged(); + public final void setOnTemplateChanged(kotlin.jvm.functions.Function2, ? extends java.lang.Object>); + public final int getTileSize(); + public final java.lang.Object setPolygons(java.util.List, kotlin.coroutines.Continuation); + public final boolean has(java.lang.String); + public final void update(com.mapconductor.core.polygon.PolygonState); + public final void remove(java.lang.String); + public final java.lang.String template(); + public final void dispose(); + public com.mapconductor.core.polygon.PolygonTileSet(); +} +public final class com.mapconductor.core.polygon.PolygonTileSet$Companion { + public final boolean canTile(com.mapconductor.core.polygon.PolygonState); + public final int vertexCount(java.util.List); +} +public final class com.mapconductor.core.polygon.PolygonTiler { + public com.mapconductor.core.polygon.PolygonTiler(com.mapconductor.core.polygon.PolygonTilingOptions); + public com.mapconductor.core.polygon.PolygonTiler(com.mapconductor.core.polygon.PolygonTilingOptions, int, kotlin.jvm.internal.DefaultConstructorMarker); + public final com.mapconductor.core.polygon.PolygonTilingOptions getOptions(); + public final kotlin.jvm.functions.Function3, java.lang.Object> getOnTemplate(); + public final void setOnTemplate(kotlin.jvm.functions.Function3, ? extends java.lang.Object>); + public final java.lang.Object route(java.util.List, kotlin.coroutines.Continuation>); + public final java.util.List tiledStates(); + public final boolean isTiled(java.lang.String); + public final void update(com.mapconductor.core.polygon.PolygonState); + public final void remove(java.lang.String); + public final void dispose(); + public final java.lang.Object clear(kotlin.coroutines.Continuation); + public com.mapconductor.core.polygon.PolygonTiler(); +} +public final class com.mapconductor.core.polygon.PolygonTilerKt { + public static final java.lang.String POLYGON_TILE_LAYER_ID; + public static final com.mapconductor.core.raster.RasterLayerState polygonTileRasterLayerState(java.lang.String, int); +} +public final class com.mapconductor.core.polygon.PolygonTilingOptions { + public static final com.mapconductor.core.polygon.PolygonTilingOptions$Companion Companion; + public com.mapconductor.core.polygon.PolygonTilingOptions(boolean, int, int); + public com.mapconductor.core.polygon.PolygonTilingOptions(boolean, int, int, int, kotlin.jvm.internal.DefaultConstructorMarker); + public final boolean getEnabled(); + public final int getMinPolygonCount(); + public final int getMinVertexCount(); + public final boolean shouldUseTiles(int, int); + public final boolean component1(); + public final int component2(); + public final int component3(); + public final com.mapconductor.core.polygon.PolygonTilingOptions copy(boolean, int, int); + public java.lang.String toString(); + public int hashCode(); + public boolean equals(java.lang.Object); + public com.mapconductor.core.polygon.PolygonTilingOptions(); +} +public final class com.mapconductor.core.polygon.PolygonTilingOptions$Companion { + public final com.mapconductor.core.polygon.PolygonTilingOptions getDefault(); + public final com.mapconductor.core.polygon.PolygonTilingOptions getDisabled(); +} public final class com.mapconductor.core.polygon.PolygonUnionKt { public static final com.mapconductor.core.polygon.PolygonState unionHoles(com.mapconductor.core.polygon.PolygonState); public static final com.mapconductor.core.polygon.PolygonState union(com.mapconductor.core.polygon.PolygonState); @@ -2060,6 +2600,32 @@ public final class com.mapconductor.core.polygon.PolygonWindingUtilsKt { public static final java.util.List ensureCounterClockwise(java.util.List); public static final java.util.List ensureClockwiseRing(java.util.List); } +public final class com.mapconductor.core.polygon.TilePolygon { + public static final com.mapconductor.core.polygon.TilePolygon$Companion Companion; + public com.mapconductor.core.polygon.TilePolygon(double[][], double[], int, int, float); + public final double[][] getRings(); + public final double[] getBbox(); + public final int getFill(); + public final int getStroke(); + public final float getStrokeWidth(); + public final boolean getFillVisible(); + public final boolean getStrokeVisible(); + public final boolean sameBox(com.mapconductor.core.polygon.TilePolygon); +} +public final class com.mapconductor.core.polygon.TilePolygon$Companion { + public final com.mapconductor.core.polygon.TilePolygon from(com.mapconductor.core.polygon.PolygonState); +} +public abstract class com.mapconductor.core.polygon.TileShape { + public com.mapconductor.core.polygon.TileShape(kotlin.jvm.internal.DefaultConstructorMarker); +} +public final class com.mapconductor.core.polygon.TileShape$Dot extends com.mapconductor.core.polygon.TileShape { + public final double getX(); + public final double getY(); +} +public final class com.mapconductor.core.polygon.TileShape$Rings extends com.mapconductor.core.polygon.TileShape { + public final double[][] getRings(); + public final boolean getOutlined(); +} final class com.mapconductor.core.polygon.Vec { public com.mapconductor.core.polygon.Vec(double, double); public final double getX(); @@ -2119,6 +2685,8 @@ public abstract class com.mapconductor.core.polyline.PolylineController getClickListener(); public final void setClickListener(kotlin.jvm.functions.Function1); + public final com.mapconductor.core.polyline.PolylineTiler getTiler(); + public final void setTiler(com.mapconductor.core.polyline.PolylineTiler); public final void dispatchClick(com.mapconductor.core.polyline.PolylineEvent); public java.lang.Object add(java.util.List, kotlin.coroutines.Continuation); public java.lang.Object update(com.mapconductor.core.polyline.PolylineState, kotlin.coroutines.Continuation); @@ -2213,9 +2781,11 @@ public interface com.mapconductor.core.polyline.PolylineManagerInterface { - public com.mapconductor.core.polyline.PolylineOverlay(kotlinx.coroutines.flow.StateFlow>); + public com.mapconductor.core.polyline.PolylineOverlay(kotlinx.coroutines.flow.StateFlow>, kotlinx.coroutines.flow.StateFlow); + public com.mapconductor.core.polyline.PolylineOverlay(kotlinx.coroutines.flow.StateFlow, kotlinx.coroutines.flow.StateFlow, int, kotlin.jvm.internal.DefaultConstructorMarker); public kotlinx.coroutines.flow.StateFlow> getFlow(); public java.lang.Object render(java.util.Map, com.mapconductor.core.controller.MapViewControllerInterface, kotlin.coroutines.Continuation); + public com.mapconductor.core.polyline.PolylineOverlay(kotlinx.coroutines.flow.StateFlow>); } public interface com.mapconductor.core.polyline.PolylineOverlayRendererInterface { public abstract java.lang.Object onAdd(java.util.List, kotlin.coroutines.Continuation>); @@ -2231,8 +2801,9 @@ public interface com.mapconductor.core.polyline.PolylineOverlayRendererInterface public abstract com.mapconductor.core.polyline.PolylineEntityInterface getPrev(); } public final class com.mapconductor.core.polyline.PolylineState implements com.mapconductor.core.ComponentState { - public com.mapconductor.core.polyline.PolylineState(java.util.List, java.lang.String, long, float, boolean, boolean, int, java.io.Serializable, kotlin.jvm.functions.Function1, int, kotlin.jvm.internal.DefaultConstructorMarker); + public com.mapconductor.core.polyline.PolylineState(java.util.List, java.lang.String, long, float, boolean, boolean, int, java.io.Serializable, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, int, kotlin.jvm.internal.DefaultConstructorMarker); public java.lang.String getId(); + public com.mapconductor.core.StateMutationSignal getMutations(); public final long getStrokeColor-0d7_KjU(); public final void setStrokeColor-8_81llA(long); public final float getStrokeWidth-D9Ej5fM(); @@ -2249,13 +2820,78 @@ public final class com.mapconductor.core.polyline.PolylineState implements com.m public final void setExtra(java.io.Serializable); public final kotlin.jvm.functions.Function1 getOnClick(); public final void setOnClick(kotlin.jvm.functions.Function1); + public final kotlin.jvm.functions.Function1 getOnAdded(); + public final void setOnAdded(kotlin.jvm.functions.Function1); + public com.mapconductor.core.polyline.PolylineState(java.util.List, java.lang.String, long, float, boolean, boolean, int, java.io.Serializable, kotlin.jvm.functions.Function1, int, kotlin.jvm.internal.DefaultConstructorMarker); public boolean equals(java.lang.Object); public int hashCode(); - public final com.mapconductor.core.polyline.PolylineState copy-uKGX-YA(java.util.List, java.lang.String, long, float, boolean, boolean, int, java.io.Serializable, kotlin.jvm.functions.Function1); + public final com.mapconductor.core.polyline.PolylineState copy-jb-40ds(java.util.List, java.lang.String, long, float, boolean, boolean, int, java.io.Serializable, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1); + public final com.mapconductor.core.polyline.PolylineState copy-uKGX-YA(java.util.List, java.lang.String, long, float, boolean, boolean, int, java.io.Serializable, kotlin.jvm.functions.Function1); public final com.mapconductor.core.polyline.PolylineFingerPrint fingerPrint(); - public final kotlinx.coroutines.flow.Flow asFlow(); + public com.mapconductor.core.polyline.PolylineState(java.util.List, java.lang.String, long, float, boolean, boolean, int, java.io.Serializable, kotlin.jvm.functions.Function1, kotlin.jvm.functions.Function1, kotlin.jvm.internal.DefaultConstructorMarker); public com.mapconductor.core.polyline.PolylineState(java.util.List, java.lang.String, long, float, boolean, boolean, int, java.io.Serializable, kotlin.jvm.functions.Function1, kotlin.jvm.internal.DefaultConstructorMarker); } +public final class com.mapconductor.core.polyline.PolylineTileSet { + public static final com.mapconductor.core.polyline.PolylineTileSet$Companion Companion; + public com.mapconductor.core.polyline.PolylineTileSet(com.mapconductor.core.tileserver.LocalTileServer, kotlinx.coroutines.CoroutineScope); + public com.mapconductor.core.polyline.PolylineTileSet(com.mapconductor.core.tileserver.LocalTileServer, kotlinx.coroutines.CoroutineScope, int, kotlin.jvm.internal.DefaultConstructorMarker); + public final java.lang.String getRouteId(); + public final kotlin.jvm.functions.Function2, java.lang.Object> getOnTemplateChanged(); + public final void setOnTemplateChanged(kotlin.jvm.functions.Function2, ? extends java.lang.Object>); + public final int getTileSize(); + public final java.lang.Object setPolylines(java.util.List, kotlin.coroutines.Continuation); + public final boolean has(java.lang.String); + public final void update(com.mapconductor.core.polyline.PolylineState); + public final void remove(java.lang.String); + public final java.lang.String template(); + public final void dispose(); + public com.mapconductor.core.polyline.PolylineTileSet(); +} +public final class com.mapconductor.core.polyline.PolylineTileSet$Companion { + public final boolean canTile(com.mapconductor.core.polyline.PolylineState); + public final int vertexCount(java.util.List); +} +public final class com.mapconductor.core.polyline.PolylineTiler { + public com.mapconductor.core.polyline.PolylineTiler(com.mapconductor.core.polyline.PolylineTilingOptions); + public com.mapconductor.core.polyline.PolylineTiler(com.mapconductor.core.polyline.PolylineTilingOptions, int, kotlin.jvm.internal.DefaultConstructorMarker); + public final com.mapconductor.core.polyline.PolylineTilingOptions getOptions(); + public final void setOptions(com.mapconductor.core.polyline.PolylineTilingOptions); + public final kotlin.jvm.functions.Function3, java.lang.Object> getOnTemplate(); + public final void setOnTemplate(kotlin.jvm.functions.Function3, ? extends java.lang.Object>); + public final java.lang.Object route(java.util.List, kotlin.coroutines.Continuation>); + public final java.util.List tiledStates(); + public final boolean isTiled(java.lang.String); + public final void update(com.mapconductor.core.polyline.PolylineState); + public final void remove(java.lang.String); + public final void dispose(); + public final java.lang.Object clear(kotlin.coroutines.Continuation); + public com.mapconductor.core.polyline.PolylineTiler(); +} +public final class com.mapconductor.core.polyline.PolylineTilerKt { + public static final java.lang.String POLYLINE_TILE_LAYER_ID; + public static final com.mapconductor.core.raster.RasterLayerState polylineTileRasterLayerState(java.lang.String, int); +} +public final class com.mapconductor.core.polyline.PolylineTilingOptions { + public static final com.mapconductor.core.polyline.PolylineTilingOptions$Companion Companion; + public com.mapconductor.core.polyline.PolylineTilingOptions(boolean, int, int); + public com.mapconductor.core.polyline.PolylineTilingOptions(boolean, int, int, int, kotlin.jvm.internal.DefaultConstructorMarker); + public final boolean getEnabled(); + public final int getMinPolylineCount(); + public final int getMinVertexCount(); + public final boolean shouldUseTiles(int, int); + public final boolean component1(); + public final int component2(); + public final int component3(); + public final com.mapconductor.core.polyline.PolylineTilingOptions copy(boolean, int, int); + public java.lang.String toString(); + public int hashCode(); + public boolean equals(java.lang.Object); + public com.mapconductor.core.polyline.PolylineTilingOptions(); +} +public final class com.mapconductor.core.polyline.PolylineTilingOptions$Companion { + public final com.mapconductor.core.polyline.PolylineTilingOptions getDefault(); + public final com.mapconductor.core.polyline.PolylineTilingOptions getDisabled(); +} public final class com.mapconductor.core.projection.Earth { public static final com.mapconductor.core.projection.Earth INSTANCE; public static final double RADIUS_METERS; @@ -2264,27 +2900,65 @@ public final class com.mapconductor.core.projection.Earth { public static final double SEMI_MINOR_AXIS_METERS; public static final double ECCENTRICITY_SQUARED; } +public final class com.mapconductor.core.projection.MapCoordinateSystem { + public static final com.mapconductor.core.projection.MapCoordinateSystem$Companion Companion; + public com.mapconductor.core.projection.MapCoordinateSystem(java.lang.String, com.mapconductor.core.projection.ProjectedUnit); + public final java.lang.String getCode(); + public final com.mapconductor.core.projection.ProjectedUnit getUnit(); + public final java.lang.String component1(); + public final com.mapconductor.core.projection.ProjectedUnit component2(); + public final com.mapconductor.core.projection.MapCoordinateSystem copy(java.lang.String, com.mapconductor.core.projection.ProjectedUnit); + public java.lang.String toString(); + public int hashCode(); + public boolean equals(java.lang.Object); +} +public final class com.mapconductor.core.projection.MapCoordinateSystem$Companion { + public final com.mapconductor.core.projection.MapCoordinateSystem getWebMercator(); + public final com.mapconductor.core.projection.MapCoordinateSystem getWGS84(); +} +public final class com.mapconductor.core.projection.ProjectedPoint { + public com.mapconductor.core.projection.ProjectedPoint(double, double); + public final double getX(); + public final double getY(); + public final double component1(); + public final double component2(); + public final com.mapconductor.core.projection.ProjectedPoint copy(double, double); + public java.lang.String toString(); + public int hashCode(); + public boolean equals(java.lang.Object); +} +public final class com.mapconductor.core.projection.ProjectedUnit extends java.lang.Enum { + public static final com.mapconductor.core.projection.ProjectedUnit Meters; + public static final com.mapconductor.core.projection.ProjectedUnit Degrees; + public static final com.mapconductor.core.projection.ProjectedUnit Other; + public static com.mapconductor.core.projection.ProjectedUnit[] values(); + public static com.mapconductor.core.projection.ProjectedUnit valueOf(java.lang.String); + public static kotlin.enums.EnumEntries getEntries(); +} public interface com.mapconductor.core.projection.ProjectionInterface { - public abstract long project-tuRUvjQ(com.mapconductor.core.features.GeoPointInterface); - public abstract com.mapconductor.core.features.GeoPointInterface unproject-k-4lQ0M(long); + public abstract com.mapconductor.core.projection.ProjectedPoint project(com.mapconductor.core.features.GeoPointInterface); + public abstract com.mapconductor.core.features.GeoPointInterface unproject(com.mapconductor.core.projection.ProjectedPoint); } public final class com.mapconductor.core.projection.WGS84 implements com.mapconductor.core.projection.ProjectionInterface { public static final com.mapconductor.core.projection.WGS84 INSTANCE; - public long project-tuRUvjQ(com.mapconductor.core.features.GeoPointInterface); - public com.mapconductor.core.features.GeoPointInterface unproject-k-4lQ0M(long); + public com.mapconductor.core.projection.ProjectedPoint project(com.mapconductor.core.features.GeoPointInterface); + public com.mapconductor.core.features.GeoPointInterface unproject(com.mapconductor.core.projection.ProjectedPoint); } public final class com.mapconductor.core.projection.WebMercator implements com.mapconductor.core.projection.ProjectionInterface { public static final com.mapconductor.core.projection.WebMercator INSTANCE; - public long project-tuRUvjQ(com.mapconductor.core.features.GeoPointInterface); - public com.mapconductor.core.features.GeoPointInterface unproject-k-4lQ0M(long); + public com.mapconductor.core.projection.ProjectedPoint project(com.mapconductor.core.features.GeoPointInterface); + public com.mapconductor.core.features.GeoPointInterface unproject(com.mapconductor.core.projection.ProjectedPoint); } public final class com.mapconductor.core.projection.WebMercatorKt { public static final double WEB_MERCATOR_MAX_EXTENT_METERS; + public static final double WEB_MERCATOR_MAX_LATITUDE; } public final class com.mapconductor.core.projection.WebMercatorScreenProjection { public static final com.mapconductor.core.projection.WebMercatorScreenProjection INSTANCE; public final androidx.compose.ui.geometry.Offset toScreenOffset-broig7I(com.mapconductor.core.features.GeoPointInterface, com.mapconductor.core.map.MapCameraPosition, float, float); + public final androidx.compose.ui.geometry.Offset toScreenOffset-17k57fo(com.mapconductor.core.features.GeoPointInterface, com.mapconductor.core.map.MapCameraPosition, float, float, java.lang.Double); public final com.mapconductor.core.features.GeoPoint fromScreenOffset-M_7yMNQ(long, com.mapconductor.core.map.MapCameraPosition, float, float); + public final com.mapconductor.core.features.GeoPoint fromScreenOffset-ULxng0E(long, com.mapconductor.core.map.MapCameraPosition, float, float, java.lang.Double); } final class com.mapconductor.core.projection.WebMercatorScreenProjection$Normalized { public final double getX(); @@ -2346,6 +3020,7 @@ public abstract class com.mapconductor.core.raster.RasterLayerController); public final java.lang.Object removeById(java.lang.String, kotlin.coroutines.Continuation); public java.lang.Object clear(kotlin.coroutines.Continuation); + public java.lang.Object reapplyStyle(kotlin.coroutines.Continuation); public com.mapconductor.core.raster.RasterLayerEntityInterface find(com.mapconductor.core.features.GeoPointInterface); public java.lang.Object onCameraChanged(com.mapconductor.core.map.MapCameraPosition, kotlin.coroutines.Continuation); public void destroy(); @@ -2493,9 +3168,10 @@ public final class com.mapconductor.core.raster.RasterLayerSource$UrlTemplate ex public final class com.mapconductor.core.raster.RasterLayerState implements com.mapconductor.core.ComponentState { public static final com.mapconductor.core.raster.RasterLayerState$Companion Companion; public static final java.lang.String DEFAULT_USER_AGENT; - public com.mapconductor.core.raster.RasterLayerState(com.mapconductor.core.raster.RasterLayerSource, float, boolean, int, java.lang.String, boolean, java.lang.String, java.util.Map); - public com.mapconductor.core.raster.RasterLayerState(com.mapconductor.core.raster.RasterLayerSource, float, boolean, int, java.lang.String, boolean, java.lang.String, java.util.Map, int, kotlin.jvm.internal.DefaultConstructorMarker); + public com.mapconductor.core.raster.RasterLayerState(com.mapconductor.core.raster.RasterLayerSource, float, boolean, int, java.lang.String, boolean, java.lang.String, java.util.Map, kotlin.jvm.functions.Function1); + public com.mapconductor.core.raster.RasterLayerState(com.mapconductor.core.raster.RasterLayerSource, float, boolean, int, java.lang.String, boolean, java.lang.String, java.util.Map, kotlin.jvm.functions.Function1, int, kotlin.jvm.internal.DefaultConstructorMarker); public java.lang.String getId(); + public com.mapconductor.core.StateMutationSignal getMutations(); public final com.mapconductor.core.raster.RasterLayerSource getSource(); public final void setSource(com.mapconductor.core.raster.RasterLayerSource); public final float getOpacity(); @@ -2510,14 +3186,29 @@ public final class com.mapconductor.core.raster.RasterLayerState implements com. public final void setDebug(boolean); public final java.util.Map getExtraHeaders(); public final void setExtraHeaders(java.util.Map); + public final kotlin.jvm.functions.Function1 getOnAdded(); + public final void setOnAdded(kotlin.jvm.functions.Function1); + public com.mapconductor.core.raster.RasterLayerState(com.mapconductor.core.raster.RasterLayerSource, float, boolean, int, java.lang.String, boolean, java.lang.String, java.util.Map); + public com.mapconductor.core.raster.RasterLayerState(com.mapconductor.core.raster.RasterLayerSource, float, boolean, int, java.lang.String, boolean, java.lang.String, java.util.Map, int, kotlin.jvm.internal.DefaultConstructorMarker); public boolean equals(java.lang.Object); public int hashCode(); - public final com.mapconductor.core.raster.RasterLayerState copy(com.mapconductor.core.raster.RasterLayerSource, float, boolean, int, boolean, java.lang.String, java.lang.String, java.util.Map); + public final com.mapconductor.core.raster.RasterLayerState copy(com.mapconductor.core.raster.RasterLayerSource, float, boolean, int, boolean, java.lang.String, java.lang.String, java.util.Map, kotlin.jvm.functions.Function1); + public final com.mapconductor.core.raster.RasterLayerState copy(com.mapconductor.core.raster.RasterLayerSource, float, boolean, int, boolean, java.lang.String, java.lang.String, java.util.Map); public final com.mapconductor.core.raster.RasterLayerFingerPrint fingerPrint(); - public final kotlinx.coroutines.flow.Flow asFlow(); } public final class com.mapconductor.core.raster.RasterLayerState$Companion { } +public interface com.mapconductor.core.raster.RasterTilePreference { + public abstract int getPreferredTileSize(); + public default boolean getLayoutInDevicePixels(); +} +public final class com.mapconductor.core.raster.RasterTilePreference$DefaultImpls { + public static boolean getLayoutInDevicePixels(com.mapconductor.core.raster.RasterTilePreference); +} +public final class com.mapconductor.core.raster.RasterTilePreferenceKey implements com.mapconductor.core.map.MapServiceKey { + public static final com.mapconductor.core.raster.RasterTilePreferenceKey INSTANCE; + public com.mapconductor.core.map.MapCapability getCapability(); +} public final class com.mapconductor.core.raster.TileScheme extends java.lang.Enum { public static final com.mapconductor.core.raster.TileScheme XYZ; public static final com.mapconductor.core.raster.TileScheme TMS; @@ -2525,6 +3216,68 @@ public final class com.mapconductor.core.raster.TileScheme extends java.lang.Enu public static com.mapconductor.core.raster.TileScheme valueOf(java.lang.String); public static kotlin.enums.EnumEntries getEntries(); } +final class com.mapconductor.core.shapetile.GlShapeRasterizer$Context { + public static final com.mapconductor.core.shapetile.GlShapeRasterizer$Context$Companion Companion; + public static final int FILL; + public static final int STROKE; + public static final int FILL_COVERS; + public static final int STROKE_COVERS; + public static final int CIRCLES; + public static final int LINES; + public static final int CORNERS; + public static final int LINE_COLORS; + public final boolean makeCurrent(); + public final void releaseCurrent(); + public final void destroyContext(); + public final java.nio.ByteBuffer draw(com.mapconductor.core.shapetile.GlShapeScene); +} +public final class com.mapconductor.core.shapetile.GlShapeRasterizer$Context$Companion { + public final com.mapconductor.core.shapetile.GlShapeRasterizer$Context create(); +} +final class com.mapconductor.core.shapetile.GlShapeRasterizer$Context$Targets { + public final int getMsaa(); + public final int getResolve(); +} +public final class com.mapconductor.core.shapetile.GlShapeScene$Batch { + public final kotlin.ranges.IntRange getFill(); + public final kotlin.ranges.IntRange getFillCovers(); + public final kotlin.ranges.IntRange getCircles(); + public final kotlin.ranges.IntRange getStroke(); + public final kotlin.ranges.IntRange getStrokeCovers(); +} +public final class com.mapconductor.core.shapetile.GlShapeScene$Floats { + public final float[] getData(); + public final int getSize(); + public final void add(float); + public final void clear(); + public final void add2(float, float); +} +public final class com.mapconductor.core.shapetile.GlShapeScene$NeedsBatches extends java.lang.RuntimeException { +} +public final class com.mapconductor.core.shapetile.GlShapeSceneKt { + public static final float[] toTilePixels(double[], double, double, float); +} +abstract class com.mapconductor.core.shapetile.ShapeTileRenderer$Gpu { +} +public final class com.mapconductor.core.shapetile.ShapeTileRenderer$Gpu$Drawn extends com.mapconductor.core.shapetile.ShapeTileRenderer$Gpu { + public final java.nio.ByteBuffer getPixels(); + public final int getSize(); +} +public final class com.mapconductor.core.shapetile.ShapeTileRenderer$Gpu$Empty extends com.mapconductor.core.shapetile.ShapeTileRenderer$Gpu { + public static final com.mapconductor.core.shapetile.ShapeTileRenderer$Gpu$Empty INSTANCE; +} +public final class com.mapconductor.core.shapetile.ShapeTileRenderer$Gpu$Unavailable extends com.mapconductor.core.shapetile.ShapeTileRenderer$Gpu { + public static final com.mapconductor.core.shapetile.ShapeTileRenderer$Gpu$Unavailable INSTANCE; +} +public final class com.mapconductor.core.shapetile.ShapeTileRenderer$Painter$DefaultImpls { + public static boolean getCacheSimplifiedShapes(com.mapconductor.core.shapetile.ShapeTileRenderer$Painter); + public static boolean getThinSubpixelOverlaps(com.mapconductor.core.shapetile.ShapeTileRenderer$Painter); + public static boolean isVisible(com.mapconductor.core.shapetile.ShapeTileRenderer$Painter, T); + public static int subpixelSlot(com.mapconductor.core.shapetile.ShapeTileRenderer$Painter, T, double, double, double, int); + public static boolean getDrawsOnGpu(com.mapconductor.core.shapetile.ShapeTileRenderer$Painter); + public static boolean record(com.mapconductor.core.shapetile.ShapeTileRenderer$Painter, com.mapconductor.core.shapetile.GlShapeScene, T, java.lang.Object, double, double, float); + public static boolean recordAll(com.mapconductor.core.shapetile.ShapeTileRenderer$Painter, com.mapconductor.core.shapetile.GlShapeScene, com.mapconductor.core.shapetile.ShapeTileStorage, int[], java.util.BitSet, double, double, double, int, float, kotlin.jvm.functions.Function0); +} public final class com.mapconductor.core.spherical.CalculateMetersPerPixelKt { public static final double calculateMetersPerPixel(double, double, double); } @@ -2614,9 +3367,17 @@ public final class com.mapconductor.core.tileserver.LocalTileServer { public final void setForceNoStoreCache(boolean); public final void register(java.lang.String, com.mapconductor.core.tileserver.TileProviderInterface); public final void unregister(java.lang.String); + public final void setLevelGate(java.lang.String, kotlin.jvm.functions.Function1); + public final void registerDocument(java.lang.String, java.lang.String, byte[]); + public final void unregisterDocument(java.lang.String); + public final java.lang.String documentUrl(java.lang.String); + public final void registerFiles(java.lang.String, java.io.File, kotlin.jvm.functions.Function1); + public final void unregisterFiles(java.lang.String); + public final java.lang.String filesUrl(java.lang.String); public final java.lang.String urlTemplate(java.lang.String, int); public final java.lang.String urlTemplate(java.lang.String, int, java.lang.String); public final java.lang.String urlTemplateWithQueryCacheKey(java.lang.String, int, java.lang.String); + public final byte[] renderLocalTile(java.lang.String, kotlin.jvm.functions.Function0); public final boolean isRunning(); public final void start(); public final void stop(); @@ -2625,6 +3386,14 @@ public final class com.mapconductor.core.tileserver.LocalTileServer { public final class com.mapconductor.core.tileserver.LocalTileServer$Companion { public final com.mapconductor.core.tileserver.LocalTileServer startServer(boolean); } +final class com.mapconductor.core.tileserver.LocalTileServer$Document { + public final java.lang.String getContentType(); + public final byte[] getBody(); +} +final class com.mapconductor.core.tileserver.LocalTileServer$FileRoute { + public final java.io.File getDirectory(); + public final kotlin.jvm.functions.Function1 getFallback(); +} final class com.mapconductor.core.tileserver.LocalTileServer$Request { public final java.lang.String getMethod(); public final java.lang.String getPath(); @@ -2659,19 +3428,37 @@ final class com.mapconductor.core.tileserver.LocalTileServer$TileKey { public int hashCode(); public boolean equals(java.lang.Object); } -final class com.mapconductor.core.tileserver.LocalTileServer$TileResponse { +interface com.mapconductor.core.tileserver.LocalTileServer$TileOutcome { +} +public final class com.mapconductor.core.tileserver.LocalTileServer$TileOutcome$Empty implements com.mapconductor.core.tileserver.LocalTileServer$TileOutcome { + public final int getPixelSize(); + public final java.lang.String getCacheControl(); +} +public final class com.mapconductor.core.tileserver.LocalTileServer$TileOutcome$Failed implements com.mapconductor.core.tileserver.LocalTileServer$TileOutcome { + public static final com.mapconductor.core.tileserver.LocalTileServer$TileOutcome$Failed INSTANCE; +} +public final class com.mapconductor.core.tileserver.LocalTileServer$TileOutcome$NotFound implements com.mapconductor.core.tileserver.LocalTileServer$TileOutcome { + public static final com.mapconductor.core.tileserver.LocalTileServer$TileOutcome$NotFound INSTANCE; +} +public final class com.mapconductor.core.tileserver.LocalTileServer$TileOutcome$Tile implements com.mapconductor.core.tileserver.LocalTileServer$TileOutcome { public final byte[] getBody(); public final java.lang.String getCacheControl(); - public final byte[] component1(); - public final java.lang.String component2(); - public final com.mapconductor.core.tileserver.LocalTileServer$TileResponse copy(byte[], java.lang.String); - public java.lang.String toString(); - public int hashCode(); - public boolean equals(java.lang.Object); } public final class com.mapconductor.core.tileserver.LocalTileServerKt { public static final com.mapconductor.core.tileserver.TileCoordinate parseTileCoordinate(java.lang.String); } +public final class com.mapconductor.core.tileserver.ScratchPool { + public static final com.mapconductor.core.tileserver.ScratchPool$Companion Companion; + public com.mapconductor.core.tileserver.ScratchPool(int); + public com.mapconductor.core.tileserver.ScratchPool(int, int, kotlin.jvm.internal.DefaultConstructorMarker); + public final T acquire(kotlin.jvm.functions.Function1); + public final boolean release(T); + public final int getSize(); + public com.mapconductor.core.tileserver.ScratchPool(); +} +public final class com.mapconductor.core.tileserver.ScratchPool$Companion { + public final int getDEFAULT_CAPACITY(); +} public final class com.mapconductor.core.tileserver.TileCoordinate { public com.mapconductor.core.tileserver.TileCoordinate(int, int); public final int getY(); @@ -2683,8 +3470,18 @@ public final class com.mapconductor.core.tileserver.TileCoordinate { public int hashCode(); public boolean equals(java.lang.Object); } +public final class com.mapconductor.core.tileserver.TilePngEncoder { + public static final com.mapconductor.core.tileserver.TilePngEncoder INSTANCE; + public final boolean isAvailable(); + public final byte[] encode(android.graphics.Bitmap); + public final byte[] encode(java.nio.ByteBuffer, int, int, boolean); +} public interface com.mapconductor.core.tileserver.TileProviderInterface { public abstract byte[] renderTile(com.mapconductor.core.tileserver.TileRequest); + public default byte[] renderTile(com.mapconductor.core.tileserver.TileRequest, kotlin.jvm.functions.Function0); +} +public final class com.mapconductor.core.tileserver.TileProviderInterface$DefaultImpls { + public static byte[] renderTile(com.mapconductor.core.tileserver.TileProviderInterface, com.mapconductor.core.tileserver.TileRequest, kotlin.jvm.functions.Function0); } public final class com.mapconductor.core.tileserver.TileRequest { public com.mapconductor.core.tileserver.TileRequest(int, int, int, int); @@ -2708,6 +3505,10 @@ public final class com.mapconductor.core.tileserver.TileServerRegistry { public final void setForceNoStoreCache(boolean); public final void warmup(); } +public final class com.mapconductor.core.tileserver.TransparentTilePng { + public static final com.mapconductor.core.tileserver.TransparentTilePng INSTANCE; + public final byte[] bytes(int); +} public abstract class com.mapconductor.core.zoom.AbstractZoomAltitudeConverter { public static final com.mapconductor.core.zoom.AbstractZoomAltitudeConverter$Companion Companion; public static final double DEFAULT_ZOOM0_ALTITUDE; diff --git a/build.gradle.kts b/build.gradle.kts index 39d6967..791f81c 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -60,7 +60,16 @@ android { } } +// 自分で宣言したドライバー実装点(@InternalMapConductorApi)を、core 自身の +// 状態クラスが使う(各 ComponentState が StateMutationSignal を持つ)。 +kotlin { + compilerOptions { + optIn.add("com.mapconductor.core.InternalMapConductorApi") + } +} + dependencies { + implementation("org.jetbrains.kotlinx:kotlinx-collections-immutable:0.5.2") // Make Compose dependencies implementation instead of compileOnly for proper runtime support implementation(platform(libs.androidx.compose.bom)) implementation(libs.androidx.ui) @@ -75,6 +84,9 @@ dependencies { implementation(libs.androidx.lifecycle.common.java8) testImplementation(libs.junit) + // OverlayCollectorMutationTest drives the collector's debounce on a virtual + // clock; without it the test source set does not compile. + testImplementation(libs.kotlinx.coroutines.test) androidTestImplementation(libs.androidx.junit) androidTestImplementation(libs.androidx.espresso.core) } diff --git a/docs/circle/CircleCompose.kt.md b/docs/circle/CircleCompose.kt.md index 2eacaa2..2ed96dc 100644 --- a/docs/circle/CircleCompose.kt.md +++ b/docs/circle/CircleCompose.kt.md @@ -14,7 +14,7 @@ fun MapViewScope.Circle( radiusMeters: Double, id: String? = null, strokeColor: Color = Color.Red, - strokeWidth: Dp = 2.dp, + strokeWidth: Dp = 1.dp, fillColor: Color = Color.White.copy(alpha = 0.5f), zIndex: Int? = null, extra: Serializable? = null, diff --git a/docs/geocell/HexCellRegistry.kt.md b/docs/geocell/HexCellRegistry.kt.md deleted file mode 100644 index be77239..0000000 --- a/docs/geocell/HexCellRegistry.kt.md +++ /dev/null @@ -1,566 +0,0 @@ -# HexCellRegistry - -## Table of Contents -- [HexCellRegistry](#hexcellregistryactualmarker) - - [Table of Contents](#table-of-contents) - - [Class: HexCellRegistry](#class-hexcellregistryactualmarker) - - [Constructor](#constructor) - - [Methods](#methods) - - [getCell](#getcell) - - [setPoint](#setpoint) - - [contains](#contains) - - [removePoint](#removepoint) - - [clear](#clear) - - [findNearest](#findnearest) - - [findNearestWithDistance](#findnearestwithdistance) - - [findNearestKWithDistance](#findnearestkwithdistance) - - [findWithinRadiusWithDistance](#findwithinradiuswithdistance) - - [all](#all) - - [getEntryIDsByHexCell](#getentryidsbyhexcell) - - [metersPerPixel](#metersperpixel) - - [findWithinPixelRadius](#findwithinpixelradius) - - [findByIdPrefix](#findbyidprefix) - - [getStats](#getstats) - - [Data Class: RegistryStats](#data-class-registrystats) - - [Properties](#properties) - -## Class: HexCellRegistry - -A thread-safe class for managing a collection of hexagonal grid cells. It provides efficient spatial -indexing and querying using an internal KDTree. - -The registry maps entities (like map markers) to the hexagonal cells they occupy at a specific zoom -level. It is designed for performance-critical applications, featuring lazy rebuilding of its -spatial index to optimize write operations. All public methods are thread-safe. - -### Constructor - -Initializes a new instance of the `HexCellRegistry`. - -**Signature** -```kotlin -class HexCellRegistry( - private val geocell: HexGeocellInterface, - private val zoom: Double, -) -``` - -**Parameters** - -- `geocell` - - Type: `HexGeocellInterface` - - Description: The hexagonal geocell system used for coordinate logic. -- `zoom` - - Type: `Double` - - Description: The map zoom level this registry is responsible for. - -
- -## Methods - -### getCell - -Calculates and returns the `HexCell` that would contain a given entity, without adding the entity to -the registry. This is a pure calculation method and does not modify the registry's state. - -**Signature** -```kotlin -fun getCell(entity: MarkerEntityInterface): HexCell -``` - -**Parameters** - -- `entity` - - Type: `MarkerEntityInterface` - - Description: The entity for which to calculate the cell. - -**Returns** - -`HexCell` - The hexagonal cell corresponding to the entity's position. - -**Example** -```kotlin -val entity: MarkerEntityInterface = /* ... get your entity ... */ -val correspondingCell = hexRegistry.getCell(entity) -println("Entity belongs in cell: ${correspondingCell.id}") -``` - ---- - -### setPoint - -Registers a new entity or updates the position of an existing one. If the entity was previously -registered in a different cell, it is automatically moved. This operation marks the internal spatial -index as needing a rebuild, which will occur on the next spatial query. - -**Signature** -```kotlin -fun setPoint(entity: MarkerEntityInterface): HexCell -``` - -**Parameters** - -- `entity` - - Type: `MarkerEntityInterface` - - Description: The entity to add or update in the registry. - -**Returns** - -`HexCell` - The hexagonal cell where the entity has been placed. - -**Example** -```kotlin -val newEntity: MarkerEntityInterface = /* ... create your entity ... */ -val cell = hexRegistry.setPoint(newEntity) -println("Entity ${newEntity.state.id} was added to cell ${cell.id}") -``` - ---- - -### contains - -Checks if a hexagonal cell with the specified ID exists in the registry. - -**Signature** -```kotlin -fun contains(hexId: String): Boolean -``` - -**Parameters** - -- `hexId` - - Type: `String` - - Description: The unique ID of the hexagonal cell. - -**Returns** - -`Boolean` - `true` if a cell with the given ID is registered, `false` otherwise. - -**Example** -```kotlin -if (hexRegistry.contains("8c2a1072b59ffff")) { - println("Cell exists in the registry.") -} -``` - ---- - -### removePoint - -Removes an entity from the registry. If the cell containing the entity becomes empty after its -removal, the cell itself is also removed from the registry. - -**Signature** -```kotlin -fun removePoint(entity: MarkerEntityInterface): Boolean -``` - -**Parameters** - -- `entity` - - Type: `MarkerEntityInterface` - - Description: The entity to remove. - -**Returns** - -`Boolean` - `true` if the entity was found and removed, `false` otherwise. - -**Example** -```kotlin -val entityToRemove: MarkerEntityInterface = /* ... get entity to remove ... */ -val wasRemoved = hexRegistry.removePoint(entityToRemove) -if (wasRemoved) { - println("Entity successfully removed.") -} -``` - ---- - -### clear - -Removes all entities and cells from the registry, effectively resetting it to an empty state. The -internal spatial index is also cleared. - -**Signature** -```kotlin -fun clear() -``` - -**Example** -```kotlin -hexRegistry.clear() -println("Registry has been cleared. Total cells: ${hexRegistry.getStats().totalCells}") -// Output: Registry has been cleared. Total cells: 0 -``` - ---- - -### findNearest - -Finds the single nearest registered `HexCell` to a given geographic point. This method may trigger a -rebuild of the spatial index if the registry has been modified since the last query. - -**Signature** -```kotlin -fun findNearest(point: GeoPointInterface): HexCell? -``` - -**Parameters** - -- `point` - - Type: `GeoPointInterface` - - Description: The geographic point to search from. - -**Returns** - -`HexCell?` - The nearest `HexCell`, or `null` if the registry is empty. - -**Example** -```kotlin -val searchPoint = GeoPoint(40.7128, -74.0060) // New York City -val nearestCell = hexRegistry.findNearest(searchPoint) -nearestCell?.let { - println("Nearest cell is ${it.id} at ${it.center.latitude}, ${it.center.longitude}") -} -``` - ---- - -### findNearestWithDistance - -Finds the single nearest registered `HexCell` to a given point and also returns the distance to it. -The distance is calculated in the projected coordinate system (e.g., meters). - -**Signature** -```kotlin -fun findNearestWithDistance(point: GeoPointInterface): HexCellWithDistance? -``` - -**Parameters** - -- `point` - - Type: `GeoPointInterface` - - Description: The geographic point to search from. - -**Returns** - -`HexCellWithDistance?` - An object containing the nearest cell and the distance, or `null` if the -registry is empty. - -**Example** -```kotlin -val searchPoint = GeoPoint(34.0522, -118.2437) // Los Angeles -val result = hexRegistry.findNearestWithDistance(searchPoint) -result?.let { - println("Nearest cell is ${it.cell.id}, distance: ${it.distance} meters") -} -``` - ---- - -### findNearestKWithDistance - -Finds the `k` nearest registered `HexCell` objects to a given point, ordered by distance. - -**Signature** -```kotlin -fun findNearestKWithDistance( - point: GeoPointInterface, - k: Int, -): List -``` - -**Parameters** - -- `point` - - Type: `GeoPointInterface` - - Description: The geographic point to search from. -- `k` - - Type: `Int` - - Description: The maximum number of nearest cells to find. - -**Returns** - -`List` - A list of up to `k` cells with their distances, sorted from nearest to -farthest. The list will be empty if the registry is empty. - -**Example** -```kotlin -val searchPoint = GeoPoint(48.8566, 2.3522) // Paris -val nearestFive = hexRegistry.findNearestKWithDistance(searchPoint, 5) -println("Found ${nearestFive.size} nearby cells:") -nearestFive.forEach { - println("- Cell ${it.cell.id} at distance ${it.distance}") -} -``` - ---- - -### findWithinRadiusWithDistance - -Finds all registered `HexCell` objects within a specified radius of a given point. The radius is -interpreted in the units of the projected coordinate system (e.g., meters). - -**Signature** -```kotlin -fun findWithinRadiusWithDistance( - point: GeoPointInterface, - radius: Double, -): List -``` - -**Parameters** - -- `point` - - Type: `GeoPointInterface` - - Description: The center point of the search area. -- `radius` - - Type: `Double` - - Description: The search radius, in projected units (typically meters). - -**Returns** - -`List` - A list of all cells found within the radius, along with their -respective distances from the center point. - -**Example** -```kotlin -val searchPoint = GeoPoint(51.5074, -0.1278) // London -val radiusInMeters = 1000.0 -val cellsInRadius = hexRegistry.findWithinRadiusWithDistance(searchPoint, radiusInMeters) -println("Found ${cellsInRadius.size} cells within 1km.") -``` - ---- - -### all - -Returns a complete list of all `HexCell` objects currently in the registry. - -**Signature** -```kotlin -fun all(): List -``` - -**Returns** - -`List` - A list containing all registered hexagonal cells. - -**Example** -```kotlin -val allRegisteredCells = hexRegistry.all() -println("Total registered cells: ${allRegisteredCells.size}") -``` - ---- - -### getEntryIDsByHexCell - -Retrieves the set of all entity IDs associated with a specific `HexCell`. - -**Signature** -```kotlin -fun getEntryIDsByHexCell(hexCell: HexCell): Set? -``` - -**Parameters** - -- `hexCell` - - Type: `HexCell` - - Description: The cell for which to retrieve entity IDs. - -**Returns** - -`Set?` - An immutable set of entity IDs within the given cell, or `null` if the cell is not -registered or contains no entities. - -**Example** -```kotlin -val cell: HexCell = /* ... get a cell from a query ... */ -val entityIds = hexRegistry.getEntryIDsByHexCell(cell) -entityIds?.let { - println("Entities in cell ${cell.id}: $it") -} -``` - ---- - -### metersPerPixel - -A utility function to calculate the approximate real-world distance in meters that corresponds to a -given number of pixels on a map display. - -**Note:** This calculation assumes the `HexGeocellInterface` projection returns coordinates in -meters. - -**Signature** -```kotlin -fun metersPerPixel( - position: GeoPointInterface, - zoom: Double, - pixels: Double, - tileSize: Int = 256, -): Double -``` - -**Parameters** - -- `position` - - Type: `GeoPointInterface` - - Description: The geographic location (latitude/longitude) for the calculation. -- `zoom` - - Type: `Double` - - Description: The current map zoom level. -- `pixels` - - Type: `Double` - - Description: The number of pixels for which to calculate the corresponding distance. -- `tileSize` - - Type: `Int` - - Description: (Optional) The size of the map tiles in pixels. Defaults to `256`. - -**Returns** - -`Double` - The calculated distance in meters. - -**Example** -```kotlin -val centerOfScreen = GeoPoint(35.6895, 139.6917) // Tokyo -val currentZoom = 15.0 -val distanceFor100Pixels = hexRegistry.metersPerPixel(centerOfScreen, currentZoom, 100.0) -println("At zoom $currentZoom, 100 pixels is approx. $distanceFor100Pixels meters.") -``` - ---- - -### findWithinPixelRadius - -A convenience method to find all `HexCell` objects within a given pixel radius of a point on the -screen. It internally converts the pixel radius to meters using `metersPerPixel` and then performs a -spatial search. - -**Signature** -```kotlin -fun findWithinPixelRadius( - position: GeoPointInterface, - zoom: Double, - pixels: Double, - tileSize: Int = 256, -): List -``` - -**Parameters** - -- `position` - - Type: `GeoPointInterface` - - Description: The center point of the search area. -- `zoom` - - Type: `Double` - - Description: The current map zoom level. -- `pixels` - - Type: `Double` - - Description: The search radius in pixels. -- `tileSize` - - Type: `Int` - - Description: (Optional) The size of the map tiles in pixels. Defaults to `256`. - -**Returns** - -`List` - A list of all cells found within the pixel radius, along with their -distances. - -**Example** -```kotlin -val tapPoint = GeoPoint(41.9028, 12.4964) // Rome -val currentZoom = 16.0 -val searchRadiusInPixels = 50.0 -val cellsNearTap = hexRegistry.findWithinPixelRadius(tapPoint, currentZoom, searchRadiusInPixels) -println("Found ${cellsNearTap.size} cells within a 50px radius of the tap.") -``` - ---- - -### findByIdPrefix - -Finds all registered cells whose IDs start with the given prefix. This is useful for querying groups -of cells in hierarchical grid systems (e.g., finding all child cells within a parent region). - -**Signature** -```kotlin -fun findByIdPrefix(prefix: String): List -``` - -**Parameters** - -- `prefix` - - Type: `String` - - Description: The cell ID prefix to search for. Must not be empty. - -**Returns** - -`List` - A list of all `HexCell` objects matching the prefix. - -**Example** -```kotlin -// Assuming a hierarchical cell ID system -val regionPrefix = "8a2a107" -val cellsInRegion = hexRegistry.findByIdPrefix(regionPrefix) -println("Found ${cellsInRegion.size} cells in region $regionPrefix.") -``` - ---- - -### getStats - -Retrieves diagnostic statistics about the current state of the registry. This is useful for -debugging and monitoring performance. - -**Signature** -```kotlin -fun getStats(): RegistryStats -``` - -**Returns** - -`RegistryStats` - A data object containing statistics such as total cell and entity counts. - -**Example** -```kotlin -val stats = hexRegistry.getStats() -println("Registry Stats:") -println("- Total Cells: ${stats.totalCells}") -println("- Total Entries: ${stats.totalEntries}") -println("- KDTree Built: ${stats.kdTreeBuilt}") -println("- Needs Rebuild: ${stats.needsRebuild}") -``` - -
- -## Data Class: RegistryStats - -A data class that holds statistics about the `HexCellRegistry`'s state. - -**Signature** -```kotlin -data class RegistryStats( - val totalCells: Int, - val totalEntries: Int, - val kdTreeBuilt: Boolean, - val needsRebuild: Boolean, -) -``` - -### Properties - -- `totalCells` - - Type: `Int` - - Description: The total number of unique hexagonal cells currently in the registry. -- `totalEntries` - - Type: `Int` - - Description: The total number of entities (e.g., markers) registered across all cells. -- `kdTreeBuilt` - - Type: `Boolean` - - Description: `true` if the KDTree spatial index has been built, `false` otherwise. -- `needsRebuild` - - Type: `Boolean` - - Description: `true` if the registry has been modified and the KDTree needs to be rebuilt on - the next spatial query. diff --git a/docs/geocell/KDTree.kt.md b/docs/geocell/KDTree.kt.md deleted file mode 100644 index 19edde2..0000000 --- a/docs/geocell/KDTree.kt.md +++ /dev/null @@ -1,297 +0,0 @@ -# KDTree - -## `KDTree` Class - -A K-D Tree (K-dimensional tree) implementation optimized for efficient 2D spatial queries on -`HexCell` objects. This class partitions a set of points (the centers of hex cells) in a -2-dimensional space, allowing for fast searches. - -It supports the following query types: -* **Nearest Neighbor:** Find the single closest point to a given location. -* **K-Nearest Neighbors (k-NN):** Find the `k` closest points to a given location. -* **Radius Search:** Find all points within a certain distance of a given location. - -### Signature - -```kotlin -class KDTree(points: List) -``` - -### Description - -Constructs a `KDTree` by recursively partitioning the provided list of `HexCell` points. The tree is -balanced by alternating the splitting axis (X and Y) at each level of depth. If the input list is -empty, an empty tree is created. - -### Parameters - -- `points` - - Type: `List` - - Description: A list of `HexCell` objects to build the tree from. - -### Example - -```kotlin -// Assuming HexCell and Offset are defined as: -// data class HexCell(val id: String, val centerXY: Offset) -// import androidx.compose.ui.geometry.Offset - -val hexCells = listOf( - HexCell("A", Offset(2f, 3f)), - HexCell("B", Offset(5f, 4f)), - HexCell("C", Offset(9f, 6f)), - HexCell("D", Offset(4f, 7f)), - HexCell("E", Offset(8f, 1f)), - HexCell("F", Offset(7f, 2f)) -) - -// Create a new KDTree instance -val kdTree = KDTree(hexCells) -``` - ---- - -## Methods - -### `nearest` - -Finds the single nearest `HexCell` to a given query point. - -#### Signature - -```kotlin -fun nearest(query: Offset): HexCell? -``` - -#### Description - -Performs a nearest neighbor search to find the `HexCell` in the tree whose center is closest to the -specified `query` point. - -#### Parameters - -- `query` - - Type: `Offset` - - Description: The coordinate point to search from. - -#### Returns - -The nearest `HexCell` object, or `null` if the tree is empty. - -#### Example - -```kotlin -val queryPoint = Offset(5f, 5f) -val nearestCell = kdTree.nearest(queryPoint) - -if (nearestCell != null) { - println("Nearest cell is ${nearestCell.id} at ${nearestCell.centerXY}") - // Expected output: Nearest cell is B at Offset(5.0, 4.0) -} -``` - ---- - -### `nearestWithDistance` - -Finds the single nearest `HexCell` to a query point and returns it along with the calculated -distance. - -#### Signature - -```kotlin -fun nearestWithDistance(query: Offset): HexCellWithDistance? -``` - -#### Description - -This method extends the `nearest` search by packaging the resulting `HexCell` and its Euclidean -distance from the `query` point into a `HexCellWithDistance` object. - -#### Parameters - -- `query` - - Type: `Offset` - - Description: The coordinate point to search from. - -#### Returns - -A `HexCellWithDistance` object containing the nearest cell and the distance, or `null` if the tree -is empty. - -#### Example - -```kotlin -// Assuming HexCellWithDistance is defined as: -// data class HexCellWithDistance(val cell: HexCell, val distanceMeters: Double) - -val queryPoint = Offset(5.1f, 4.2f) -val result = kdTree.nearestWithDistance(queryPoint) - -result?.let { - println("Nearest cell is ${it.cell.id} with a distance of ${it.distanceMeters}") - // Expected output: Nearest cell is B with a distance of 0.2236... -} -``` - ---- - -### `nearestKWithDistance` - -Finds the `k` nearest `HexCell`s to a query point, along with their respective distances. - -#### Signature - -```kotlin -fun nearestKWithDistance(query: Offset, k: Int): List -``` - -#### Description - -Performs a k-nearest neighbors (k-NN) search. It returns a list of the `k` closest `HexCell`s to the -`query` point, sorted by distance in ascending order. - -#### Parameters - -- `query` - - Type: `Offset` - - Description: The coordinate point to search from. -- `k` - - Type: `Int` - - Description: The number of nearest neighbors to find. Must be a positive integer. - -#### Returns - -A `List` containing the `k` nearest cells and their distances, sorted from -nearest to farthest. Returns an empty list if the tree is empty. - -#### Example - -```kotlin -val queryPoint = Offset(6f, 3f) -val k = 3 -val nearestThree = kdTree.nearestKWithDistance(queryPoint, k) - -println("Found ${nearestThree.size} neighbors:") -nearestThree.forEach { - println("- Cell ${it.cell.id} at distance ${it.distanceMeters}") -} -// Expected output: -// Found 3 neighbors: -// - Cell F at distance 1.414... -// - Cell B at distance 1.414... -// - Cell A at distance 4.0... -``` - ---- - -### `withinRadiusWithDistance` - -Finds all `HexCell`s within a specified radius of a query point. - -#### Signature - -```kotlin -fun withinRadiusWithDistance(query: Offset, radius: Double): List -``` - -#### Description - -Performs a radius search to find all `HexCell`s whose centers fall within the given `radius` of the -`query` point. The results include the distance to each cell and are sorted by distance. - -#### Parameters - -- `query` - - Type: `Offset` - - Description: The center point of the search circle. -- `radius` - - Type: `Double` - - Description: The radius of the search area. Must be non-negative. - -#### Returns - -A `List` of all cells found within the radius, sorted by distance. Returns an -empty list if no cells are within the radius or if the tree is empty. - -#### Example - -```kotlin -val queryPoint = Offset(7.5f, 2.5f) -val searchRadius = 2.0 -val cellsInRadius = kdTree.withinRadiusWithDistance(queryPoint, searchRadius) - -println("Found ${cellsInRadius.size} cells within a radius of $searchRadius:") -cellsInRadius.forEach { - println("- Cell ${it.cell.id} at distance ${it.distanceMeters}") -} -// Expected output: -// Found 2 cells within a radius of 2.0: -// - Cell F at distance 0.707... -// - Cell E at distance 1.581... -``` - ---- - -### `getStats` - -Retrieves statistics about the internal structure of the `KDTree`. - -#### Signature - -```kotlin -fun getStats(): KDTreeStats -``` - -#### Description - -Provides metrics about the constructed tree, which can be useful for debugging or performance -analysis. It returns the total number of nodes, the maximum depth of the tree, and a flag indicating -if the tree is empty. - -#### Returns - -A `KDTreeStats` object containing the tree's structural metrics. - -#### Example - -```kotlin -val stats = kdTree.getStats() - -println("Tree is empty: ${stats.isEmpty}") -println("Node count: ${stats.nodeCount}") -println("Max depth: ${stats.maxDepth}") - -// Example output for the tree created earlier: -// Tree is empty: false -// Node count: 6 -// Max depth: 4 -``` - ---- - -## `KDTreeStats` Data Class - -A data class that holds statistics about a `KDTree`'s structure. - -### Signature - -```kotlin -data class KDTreeStats( - val nodeCount: Int, - val maxDepth: Int, - val isEmpty: Boolean -) -``` - -### Properties - -- `nodeCount` - - Type: `Int` - - Description: The total number of nodes (cells) in the tree. -- `maxDepth` - - Type: `Int` - - Description: The maximum depth from the root to any leaf node. -- `isEmpty` - - Type: `Boolean` - - Description: `true` if the tree contains no nodes, otherwise `false`. diff --git a/docs/groundimage/GroundImage.kt.md b/docs/groundimage/GroundImage.kt.md index a2a4d86..f462019 100644 --- a/docs/groundimage/GroundImage.kt.md +++ b/docs/groundimage/GroundImage.kt.md @@ -20,6 +20,26 @@ class GroundImageState( ) : ComponentState ``` +The image can also be given as a URL: + +```kotlin +GroundImageState( + bounds: GeoRectBounds, + imageUrl: String, + opacity: Float = 1.0f, + tileSize: Int = GroundImageTileProvider.DEFAULT_TILE_SIZE, + clickable: Boolean = true, + id: String? = null, + extra: Serializable? = null, + onClick: OnGroundImageEventHandler? = null, +) +``` + +The SDK downloads the image (http, https, file or data URLs; http(s) needs the app's +`android.permission.INTERNET`). Until it arrives `image` is a transparent placeholder; once it +arrives `image` becomes the loaded image and the overlay is redrawn. If the image cannot be loaded +the overlay stays transparent and a warning is logged once. + #### Parameters - `bounds` @@ -29,6 +49,9 @@ class GroundImageState( - `image` - Type: `Drawable` - Description: The `Drawable` resource to be displayed as the overlay. +- `imageUrl` + - Type: `String` + - Description: The URL of the image to load, instead of `image`. See above. - `opacity` - Type: `Float` - Description: The opacity of the image, ranging from `0.0f` (fully transparent) to `1.0f` @@ -62,7 +85,11 @@ after initialization to dynamically update the ground image on the map. - Description: The geographical area the image covers. - `image` - Type: `Drawable` - - Description: The image `Drawable` to display. + - Description: The image `Drawable` to display. Setting it clears `imageUrl`. +- `imageUrl` + - Type: `String?` + - Description: The URL the image is loaded from, or `null` if the image was given as a + `Drawable`. Setting it loads that image; a result for an earlier URL is ignored. - `opacity` - Type: `Float` - Description: The opacity of the image. diff --git a/docs/groundimage/GroundImageComponent.kt.md b/docs/groundimage/GroundImageComponent.kt.md index 4b00049..f24a2a6 100644 --- a/docs/groundimage/GroundImageComponent.kt.md +++ b/docs/groundimage/GroundImageComponent.kt.md @@ -21,7 +21,7 @@ its geographical bounds, and other optional properties directly as parameters. fun MapViewScope.GroundImage( bounds: GeoRectBounds, image: Drawable, - opacity: Float = 0.5f, + opacity: Float = 1.0f, tileSize: Int = GroundImageTileProvider.DEFAULT_TILE_SIZE, id: String? = null, extra: Serializable? = null, @@ -46,7 +46,7 @@ be called within the `MapView` composable's content scope. - `opacity` - Type: `Float` - Description: The opacity of the image, ranging from `0.0` (fully transparent) to `1.0` (fully - opaque). Defaults to `0.5f`. + opaque). Defaults to `1.0f`. - `tileSize` - Type: `Int` - Description: The size of the tiles (in pixels) used to render the image on the map. Defaults diff --git a/docs/marker/ImageIcon.kt.md b/docs/marker/ImageIcon.kt.md index 96e1e7c..e87a198 100644 --- a/docs/marker/ImageIcon.kt.md +++ b/docs/marker/ImageIcon.kt.md @@ -23,12 +23,37 @@ class ImageIcon( ) : AndroidDrawableIcon ``` +An `ImageIcon` can also load its image from a URL: + +```kotlin +ImageIcon( + imageUrl: String, + iconSize: Dp = Settings.Default.iconSize, + scale: Float = 1.0f, + anchor: Offset = Offset(0.5f, 0.5f), + infoAnchor: Offset = Offset(0.5f, 0.5f), + debug: Boolean = false, + // label parameters are the same as for the Drawable constructor +) +``` + +The SDK downloads the image (http, https, file or data URLs; http(s) needs the app's +`android.permission.INTERNET`). Until the image arrives the icon is transparent at its final size +and anchor (a label is still drawn), and every marker using it is redrawn once it arrives. Each URL +is fetched once, however many icons or markers use it. If the image cannot be loaded the icon stays +transparent and a warning is logged once. `imageUrl` returns the URL, or `null` for an icon built +from a `Drawable`; `copy()` keeps the URL. + ## Parameters - `image` - Type: `Drawable` - Default: (none) - Description: The Android `Drawable` to be used as the icon. +- `imageUrl` + - Type: `String` + - Default: (none) + - Description: The URL of the image to load instead of `image`. See above. - `iconSize` - Type: `Dp` - Default: `Settings.Default.iconSize` @@ -90,7 +115,13 @@ val customIcon = ImageIcon( anchor = Offset(0.5f, 1.0f) // Anchor at the bottom-center ) -// 3. Use the icons when creating Markers for the map +// 3. Load the image from a URL. The marker shows once the image has arrived. +val remoteIcon = ImageIcon( + imageUrl = "https://example.com/marker.png", + anchor = Offset(0.5f, 1.0f) +) + +// 4. Use the icons when creating Markers for the map val marker1 = Marker( position = LatLng(34.0522, -118.2437), icon = defaultIcon, diff --git a/docs/marker/MarkerManager.kt.md b/docs/marker/MarkerManager.kt.md index 57aff3e..c58b1c6 100644 --- a/docs/marker/MarkerManager.kt.md +++ b/docs/marker/MarkerManager.kt.md @@ -41,8 +41,9 @@ spatial querying capabilities. `MarkerManager` is designed to handle a large number of markers on a map. It employs a performance optimization strategy: for small datasets (fewer than `minMarkerCount`), it uses simple brute-force -searches. For larger datasets, it automatically creates and uses a spatial index (`HexCellRegistry`) -to perform fast spatial queries like finding the nearest marker or markers within a specific area. +searches. For larger datasets, it automatically creates and uses a spatial index (a lat/lng grid, +`MarkerGridIndex`) to perform fast spatial queries like finding the nearest marker or markers within +a specific area. This lazy initialization of the spatial index saves memory for use cases with a small number of markers. All operations that modify or access the internal collections are thread-safe. @@ -63,7 +64,8 @@ open class MarkerManager( - `geocell` - Type: `HexGeocellInterface` - - Description: The hexagonal geocelling system to use for the spatial index. + - Description: The hexagonal geocelling system. Exposed to subclasses; the spatial index itself + is a lat/lng grid and does not use it. - `minMarkerCount` - Type: `Int` - Description: The threshold for creating the spatial index. Spatial queries will use the index @@ -315,23 +317,3 @@ open fun metersPerPixel( #### Returns The calculated distance in meters. - -### `findByIdPrefix` -Searches the spatial index for `HexCell`s that match a given ID prefix. - -> **Note:** This method will only return results if the spatial index has been initialized (i.e., -when the entity count has exceeded `minMarkerCount`). Otherwise, it returns an empty list. - -#### Signature -```kotlin -open fun findByIdPrefix(prefix: String): List -``` - -#### Parameters -- `prefix` - - Type: `String` - - Description: The `HexCell` ID prefix to search for. - -#### Returns -A `List` of matching `HexCell`s, or an empty list if the index is not active or no matches are -found. diff --git a/docs/polygon/Polygon.kt.md b/docs/polygon/Polygon.kt.md index df2628f..06670cc 100644 --- a/docs/polygon/Polygon.kt.md +++ b/docs/polygon/Polygon.kt.md @@ -42,7 +42,7 @@ The `PolygonState` is initialized with the following parameters: - Description: The color of the polygon's outline. - `strokeWidth` - Type: `Dp` - - Default: `2.dp` + - Default: `1.dp` - Description: The width of the polygon's outline. - `fillColor` - Type: `Color` diff --git a/docs/spherical/Spherical.kt.md b/docs/spherical/Spherical.kt.md index 2318e8c..8df2686 100644 --- a/docs/spherical/Spherical.kt.md +++ b/docs/spherical/Spherical.kt.md @@ -313,8 +313,11 @@ fun computeSignedArea(path: List): Double This function computes the signed area of a closed polygon. The sign of the result indicates the orientation of the vertices: -- **Positive value:** The vertices are in a counter-clockwise order. -- **Negative value:** The vertices are in a clockwise order. +- **Positive value:** The vertices are in a clockwise order. +- **Negative value:** The vertices are in a counter-clockwise order. + +Orientation is as seen on a north-up map (longitude increasing to the right, latitude increasing +upward). The magnitude of the result is the area in square meters. The path is assumed to be closed. @@ -327,28 +330,28 @@ The magnitude of the result is the area in square meters. The path is assumed to ### Returns - Type: `Double` -- Description: The signed area in square meters. Positive for CCW, negative for CW. +- Description: The signed area in square meters. Positive for CW, negative for CCW. ### Example ```kotlin -// Counter-clockwise polygon -val ccwPolygon = listOf( +// Clockwise polygon (SW -> NW -> NE -> SE) +val cwPolygon = listOf( GeoPoint(latitude = 40.0, longitude = -75.0), GeoPoint(latitude = 41.0, longitude = -75.0), GeoPoint(latitude = 41.0, longitude = -74.0), GeoPoint(latitude = 40.0, longitude = -74.0) ) -val signedAreaCCW = Spherical.computeSignedArea(ccwPolygon) -// signedAreaCCW will be a positive value -println("Counter-clockwise signed area: $signedAreaCCW") - -// Clockwise polygon -val cwPolygon = ccwPolygon.reversed() val signedAreaCW = Spherical.computeSignedArea(cwPolygon) -// signedAreaCW will be a negative value with the same magnitude +// signedAreaCW will be a positive value println("Clockwise signed area: $signedAreaCW") + +// Counter-clockwise polygon +val ccwPolygon = cwPolygon.reversed() +val signedAreaCCW = Spherical.computeSignedArea(ccwPolygon) +// signedAreaCCW will be a negative value with the same magnitude +println("Counter-clockwise signed area: $signedAreaCCW") ``` --- diff --git a/gradle.properties b/gradle.properties index 26d9949..b1212ba 100644 --- a/gradle.properties +++ b/gradle.properties @@ -8,5 +8,5 @@ minSdk=26 javaVersion=17 jvmTarget=17 -libraryVersion=1.3.1 +libraryVersion=1.4.0 android.generateSyncIssueWhenLibraryConstraintsAreEnabled=false diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 99cd156..eaf935e 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -12,7 +12,14 @@ junit = "4.13.2" junitVersion = "1.3.0" espressoCore = "3.7.0" +coroutines = "1.11.0" + [libraries] +# OverlayCollectorMutationTest drives the collector's debounce on a virtual clock. +# build.gradle.kts has asked for this alias all along; nothing defined it, so the +# standalone build died in script compilation before it could reach a single task. +kotlinx-coroutines-test = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-test", version.ref = "coroutines" } + # Jetpack Compose (with BOM) androidx-compose-bom = { group = "androidx.compose", name = "compose-bom", version.ref = "composeBom" } androidx-ui = { group = "androidx.compose.ui", name = "ui", version.ref = "composeLibs" } diff --git a/src/androidTest/AndroidManifest.xml b/src/androidTest/AndroidManifest.xml new file mode 100644 index 0000000..4ead9cf --- /dev/null +++ b/src/androidTest/AndroidManifest.xml @@ -0,0 +1,13 @@ + + + + + + + + + diff --git a/src/androidTest/assets/antennas/README.md b/src/androidTest/assets/antennas/README.md new file mode 100644 index 0000000..0fe98cb --- /dev/null +++ b/src/androidTest/assets/antennas/README.md @@ -0,0 +1,12 @@ +# US antenna horizons + +Source: FCC ASR weekly complete registration export, downloaded 2026-11-10. +https://data.fcc.gov/download/pub/uls/complete/r_tower.zip + +This is a snapshot of registered antenna structures, not a cellular base station database. FCC registration does not establish that a transmitter is operating. Only current, constructed registrations with coordinates and a positive overall height above ground are retained. Owner names, addresses and contacts are discarded. Data provenance, filtering, SHA-256 and binary layout are in public/antennas/us-antennas.json. + +The radius is a **geometric horizon model**, not measured or predicted radio coverage. It assumes a spherical Earth with R=6378137 m and a receiver 1.5 m above the ground. Radius in metres is R*(acos(R/(R+h))+acos(R/(R+1.5))). It ignores terrain, antenna elevation within the structure, radiation pattern, obstructions, frequency and atmospheric refraction. geodesic=true traces that surface distance on the sphere. The false toggle is a local-plane comparison. + +Low (<60 m), medium (60–150 m) and tall (>=150 m) structures are colored blue, green and orange. Alaska and US overview camera presets demonstrate latitude-dependent projection. Each platform bundles the same ~2.27 MB file; no network or token is needed to load the sample data. Source is factual FCC public-access data, with source credit shown on the sample. + +Rebuild: download r_tower.zip, then `python3 pack.py r_tower.zip us-antennas.bin`. Copy the .bin and .json to each example's antennas asset directory. MCCA header and count are little-endian; each 16-byte record stores float32 latitude, float32 longitude, float32 height_m and uint32 registration. diff --git a/src/androidTest/assets/antennas/us-antennas.bin b/src/androidTest/assets/antennas/us-antennas.bin new file mode 100644 index 0000000..26804c3 Binary files /dev/null and b/src/androidTest/assets/antennas/us-antennas.bin differ diff --git a/src/androidTest/assets/antennas/us-antennas.json b/src/androidTest/assets/antennas/us-antennas.json new file mode 100644 index 0000000..c629681 --- /dev/null +++ b/src/androidTest/assets/antennas/us-antennas.json @@ -0,0 +1,16 @@ +{ + "source": "https://data.fcc.gov/download/pub/uls/complete/r_tower.zip", + "source_sha256": "fe21a1ac2ac9b168172a17dd8bf21560727c1b833305092aec8bfc7598cc4ab5", + "file_sha256": "73790a6249002a52083e7cfb359092f71d05b4e91ea1667ee840bcd83f636185", + "count": 141979, + "bytes": 2271672, + "receiver_height_m": 1.5, + "earth_radius_m": 6378137, + "min_radius_m": 11693.874125711327, + "max_radius_m": 93860.22110994058, + "excluded": { + "registration": 4 + }, + "filter": "RA archive_flag_code=C, status_code=C, empty date_dismantled; CO coordinate_type=T; unique registration number; 0 < overall_height_above_ground <= 1000 m", + "format": "MCCA + u32 count + count*(f32 latitude, f32 longitude, f32 height_m, u32 registration); little endian" +} diff --git a/src/androidTest/java/com/mapconductor/core/ExampleInstrumentedTest.kt b/src/androidTest/java/com/mapconductor/core/ExampleInstrumentedTest.kt index 2f0554e..7aee77f 100644 --- a/src/androidTest/java/com/mapconductor/core/ExampleInstrumentedTest.kt +++ b/src/androidTest/java/com/mapconductor/core/ExampleInstrumentedTest.kt @@ -16,7 +16,10 @@ class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. + // A library module has no app of its own, so the instrumentation runs + // in a test app whose package carries the `.test` suffix. The + // template's assertion has never been true here. val appContext = InstrumentationRegistry.getInstrumentation().targetContext - assertEquals("com.mapconductor.core", appContext.packageName) + assertEquals("com.mapconductor.core.test", appContext.packageName) } } diff --git a/src/androidTest/java/com/mapconductor/core/OverlayOnAddedDeviceTest.kt b/src/androidTest/java/com/mapconductor/core/OverlayOnAddedDeviceTest.kt new file mode 100644 index 0000000..e3bff41 --- /dev/null +++ b/src/androidTest/java/com/mapconductor/core/OverlayOnAddedDeviceTest.kt @@ -0,0 +1,200 @@ +package com.mapconductor.core + +import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.mapconductor.core.controller.MapViewControllerInterface +import com.mapconductor.core.controller.OverlayControllerInterface +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.features.GeoPointInterface +import com.mapconductor.core.features.GeoRectBounds +import com.mapconductor.core.map.MapCameraPosition +import com.mapconductor.core.map.MapViewHolderInterface +import com.mapconductor.core.polygon.OnPolygonEventHandler +import com.mapconductor.core.polygon.PolygonCapableInterface +import com.mapconductor.core.polygon.PolygonController +import com.mapconductor.core.polygon.PolygonEntityInterface +import com.mapconductor.core.polygon.PolygonManager +import com.mapconductor.core.polygon.PolygonOverlay +import com.mapconductor.core.polygon.PolygonOverlayRendererInterface +import com.mapconductor.core.polygon.PolygonOverlayRendererInterface.AddParamsInterface +import com.mapconductor.core.polygon.PolygonOverlayRendererInterface.ChangeParamsInterface +import com.mapconductor.core.polygon.PolygonState +import com.mapconductor.core.polygon.PolygonTiler +import com.mapconductor.core.polygon.PolygonTilingOptions +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.runBlocking +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith + +/** + * `onAdded` on the tile path: the real core PolygonController with a real + * PolygonTiler (its renderer needs android.util.LruCache, hence a device + * test). The native path and the rest are in the JVM OverlayOnAddedTest. + */ +@RunWith(AndroidJUnit4::class) +class OverlayOnAddedDeviceTest { + private val events = mutableListOf() + + private inner class FakeRenderer : PolygonOverlayRendererInterface { + override suspend fun onAdd(data: List): List = + data.map { + events += "native:${it.state.id}" + "native-${it.state.id}" + } + + override suspend fun onChange(data: List>): List = data.map { it.prev.polygon } + + override suspend fun onRemove(data: List>) { + data.forEach { events += "remove:${it.state.id}" } + } + + override suspend fun onPostProcess() = Unit + } + + private inner class FakeMap( + tiling: PolygonTilingOptions, + ) : MapViewControllerInterface, + PolygonCapableInterface { + val polygons = object : PolygonController(PolygonManager(), FakeRenderer()) {} + + init { + polygons.tiler = + PolygonTiler(tiling).also { tiler -> + // What a provider does: upsert the raster layer, or remove it. + tiler.onTemplate = { template, _ -> events += if (template != null) "upsert" else "removeLayer" } + } + } + + override suspend fun compositionPolygons(data: List) = polygons.add(data) + + override suspend fun updatePolygon(state: PolygonState) = polygons.update(state) + + @Deprecated("Use PolygonState.onClick instead.") + override fun setOnPolygonClickListener(listener: OnPolygonEventHandler?) = Unit + + override fun hasPolygon(state: PolygonState): Boolean = polygons.has(state.id) + + override val holder: MapViewHolderInterface<*, *> get() = error("not used") + + override suspend fun clearOverlays() = polygons.clear() + + override fun moveCamera(position: MapCameraPosition) = Unit + + override fun animateCamera( + position: MapCameraPosition, + duration: Long, + ) = Unit + + override fun fitBounds( + bounds: GeoRectBounds, + padding: Int, + ) = Unit + + override fun registerOverlayController(controller: OverlayControllerInterface<*, *>) = Unit + + override fun destroy() = polygons.destroy() + } + + private val maps = mutableListOf() + + @After + fun tearDown() = maps.forEach { it.destroy() } + + private fun tiling(minPolygonCount: Int) = PolygonTilingOptions(minPolygonCount = minPolygonCount) + + private fun map(minPolygonCount: Int) = FakeMap(tiling(minPolygonCount)).also { maps += it } + + private val recorder: (PolygonState) -> Unit = { events += "onAdded:${it.id}" } + + private fun square(i: Int): PolygonState { + val lat = (i / 100) * 0.01 + val lng = (i % 100) * 0.01 + val points: List = + listOf( + GeoPoint.fromLatLong(lat, lng), + GeoPoint.fromLatLong(lat, lng + 0.005), + GeoPoint.fromLatLong(lat + 0.005, lng + 0.005), + GeoPoint.fromLatLong(lat + 0.005, lng), + ) + return PolygonState(points = points, id = "p$i", onAdded = recorder) + } + + private fun PolygonOverlay.show( + map: FakeMap, + states: List, + ) = runBlocking { render(states.associateBy { it.id }.toMutableMap(), map) } + + private fun overlay() = PolygonOverlay(MutableStateFlow(mutableMapOf())) + + @Test + fun calledAfterTheTileTemplateWasHandedToTheMap() { + val map = map(minPolygonCount = 5) + val states = List(5) { square(it) } + + overlay().show(map, states) + + assertEquals("upsert", events.first()) + assertEquals(states.map { "onAdded:${it.id}" }, events.drop(1)) + assertTrue("nothing drawn natively", events.none { it.startsWith("native:") }) + } + + @Test + fun anInPlaceChangeOfATiledPolygonCallsNothing() { + val map = map(minPolygonCount = 2) + val overlay = overlay() + val states = List(2) { square(it) } + overlay.show(map, states) + events.clear() + + states[0].fillColor = androidx.compose.ui.graphics.Color.Red + runBlocking { map.updatePolygon(states[0]) } + overlay.show(map, states) + + assertTrue(events.toString(), events.none { it.startsWith("onAdded") }) + } + + @Test + fun aTiledPolygonMadeGeodesicInPlaceMovesToNativeAndCallsNothing() { + val map = map(minPolygonCount = 2) + val overlay = overlay() + val states = List(3) { square(it) } + overlay.show(map, states) + assertEquals(3, events.count { it.startsWith("onAdded") }) + events.clear() + + // No longer tileable: drawn natively from now on, still on the map. + states[0].geodesic = true + runBlocking { map.updatePolygon(states[0]) } + assertTrue(events.toString(), "native:p0" in events) + overlay.show(map, states) + + assertTrue(events.toString(), events.none { it.startsWith("onAdded") }) + } + + @Test + fun movingBetweenNativeAndTilesWhileOnTheMapCallsNothing() { + val map = map(minPolygonCount = 4) + val overlay = overlay() + val first = List(3) { square(it) } + overlay.show(map, first) + assertEquals(listOf("onAdded:p0", "onAdded:p1", "onAdded:p2"), events.filter { it.startsWith("onAdded") }) + events.clear() + + // A fourth polygon tips the set into tiles: only the new one is added. + overlay.show(map, first + square(3)) + assertEquals(listOf("upsert", "remove:p0", "remove:p1", "remove:p2", "onAdded:p3"), events) + events.clear() + + // Back to native drawing: p0..p2 were on the map all along. + overlay.show(map, first) + assertEquals(listOf("removeLayer", "native:p0", "native:p1", "native:p2"), events) + events.clear() + + // p3 left; adding it again (into tiles) calls it again. + overlay.show(map, first + square(3)) + assertEquals("onAdded:p3", events.last()) + assertEquals(1, events.count { it.startsWith("onAdded") }) + } +} diff --git a/src/androidTest/java/com/mapconductor/core/RemoteImageDeviceTest.kt b/src/androidTest/java/com/mapconductor/core/RemoteImageDeviceTest.kt new file mode 100644 index 0000000..aa25189 --- /dev/null +++ b/src/androidTest/java/com/mapconductor/core/RemoteImageDeviceTest.kt @@ -0,0 +1,199 @@ +package com.mapconductor.core + +import androidx.compose.ui.unit.Dp +import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.features.GeoRectBounds +import com.mapconductor.core.groundimage.GroundImageState +import com.mapconductor.core.marker.ImageIcon +import com.mapconductor.core.marker.MarkerState +import com.mapconductor.core.marker.iconRevision +import java.io.ByteArrayOutputStream +import java.util.concurrent.CountDownLatch +import java.util.concurrent.Executors +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicInteger +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertSame +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import android.graphics.Bitmap +import android.graphics.Color +import android.graphics.drawable.ColorDrawable +import kotlinx.coroutines.asCoroutineDispatcher + +/** + * URL で渡す画像(`ImageIcon(imageUrl)` / `GroundImageState(imageUrl)`)。 + * + * 取得は差し替えた [RemoteImageLoader.fetch] がラッチで止めるので、「読み込み中」と + * 「届いた後」を順に確かめられる。復号は端末の BitmapFactory を使う。 + */ +@RunWith(AndroidJUnit4::class) +class RemoteImageDeviceTest { + private val executor = Executors.newSingleThreadExecutor() + private val release = CountDownLatch(1) + private val fetches = AtomicInteger() + private var failing = false + + private val png: ByteArray by lazy { + val bitmap = Bitmap.createBitmap(8, 8, Bitmap.Config.ARGB_8888).apply { eraseColor(Color.RED) } + ByteArrayOutputStream().also { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) }.toByteArray() + } + + @Before + fun setUp() { + RemoteImageLoader.resetForTest() + RemoteImageLoader.dispatcher = executor.asCoroutineDispatcher() + RemoteImageLoader.fetch = { url -> + fetches.incrementAndGet() + release.await(5, TimeUnit.SECONDS) + if (failing) throw IllegalStateException("offline: $url") + png + } + } + + @After + fun tearDown() { + RemoteImageLoader.resetForTest() + executor.shutdownNow() + } + + /** 取得のスレッドで、それまでに積まれた仕事が終わるのを待つ。 */ + private fun drain() { + executor.submit {}.get(5, TimeUnit.SECONDS) + } + + private fun loadAll() { + release.countDown() + drain() + } + + @Test + fun oneFetchPerUrlAndEveryoneGetsTheSameImage() { + val results = mutableListOf() + RemoteImageLoader.load("https://example.test/a.png") { synchronized(results) { results.add(it) } } + RemoteImageLoader.load("https://example.test/a.png") { synchronized(results) { results.add(it) } } + loadAll() + + assertEquals(1, fetches.get()) + assertEquals(2, results.size) + assertSame(results[0], results[1]) + assertEquals(8, results[0]!!.width) + // 読み終えた後は、その場で返る。 + var immediate: Bitmap? = null + RemoteImageLoader.load("https://example.test/a.png") { immediate = it } + assertSame(results[0], immediate) + assertEquals(1, fetches.get()) + } + + @Test + fun aFailedUrlStaysFailed() { + failing = true + var first: Bitmap? = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888) + RemoteImageLoader.load("https://example.test/missing.png") { first = it } + loadAll() + assertNull(first) + + var second: Bitmap? = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888) + RemoteImageLoader.load("https://example.test/missing.png") { second = it } + assertNull(second) + assertEquals(1, fetches.get()) + } + + @Test + fun dataUrlsAreDecodedWithoutTheNetwork() { + RemoteImageLoader.resetForTest() + val url = "data:image/png;base64," + android.util.Base64.encodeToString(png, android.util.Base64.NO_WRAP) + val done = CountDownLatch(1) + var bitmap: Bitmap? = null + RemoteImageLoader.load(url) { + bitmap = it + done.countDown() + } + assertTrue(done.await(5, TimeUnit.SECONDS)) + assertEquals(8, bitmap!!.width) + } + + @Test + fun iconLooksTheSameSizeAndChangesOnceWhenTheImageArrives() { + val icon = ImageIcon(imageUrl = "https://example.test/icon.png", iconSize = Dp(16f)) + val same = ImageIcon(imageUrl = "https://example.test/icon.png", iconSize = Dp(16f)) + assertEquals("https://example.test/icon.png", icon.imageUrl) + assertEquals(icon, same) + val pendingHash = icon.hashCode() + val pending = icon.toBitmapIcon() + val center = pending.bitmap.width / 2 + assertEquals(0, Color.alpha(pending.bitmap.getPixel(center, center))) + + loadAll() + + assertNotEquals(pendingHash, icon.hashCode()) + assertEquals(icon, same) + val ready = icon.toBitmapIcon() + assertEquals(pending.size, ready.size) + assertEquals(pending.anchor, ready.anchor) + assertEquals(Color.RED, ready.bitmap.getPixel(center, center)) + // copy は URL を引き継ぐ。 + assertEquals("https://example.test/icon.png", icon.copy(scale = 2f).imageUrl) + assertNull(ImageIcon(image = ColorDrawable(Color.RED)).imageUrl) + } + + @Test + fun markerRedrawsWhenItsIconArrivesButNotAfterTheIconWasReplaced() { + val icon = ImageIcon(imageUrl = "https://example.test/marker.png") + val kept = MarkerState(position = GeoPoint.fromLatLong(35.0, 139.0), icon = icon) + val replaced = MarkerState(position = GeoPoint.fromLatLong(35.0, 139.0), icon = icon) + val keptWrites = AtomicInteger() + val replacedWrites = AtomicInteger() + kept.mutations.listen { keptWrites.incrementAndGet() } + replaced.icon = ImageIcon(image = ColorDrawable(Color.BLUE)) + replaced.mutations.listen { replacedWrites.incrementAndGet() } + val before = kept.fingerPrint() + + loadAll() + + assertEquals(1, keptWrites.get()) + assertEquals(0, replacedWrites.get()) + assertEquals(1, kept.iconRevision) + assertEquals(0, replaced.iconRevision) + assertNotEquals(before, kept.fingerPrint()) + } + + @Test + fun groundImageShowsTheImageOnceLoadedAndKeepsOnlyTheLatestUrl() { + val bounds = + GeoRectBounds( + southWest = GeoPoint.fromLatLong(35.0, 139.0), + northEast = GeoPoint.fromLatLong(35.1, 139.1), + ) + val state = GroundImageState(bounds = bounds, imageUrl = "https://example.test/ground.png") + val placeholder = state.image + assertEquals(1, placeholder.intrinsicWidth) + + // 読み終える前に別の URL へ替えたら、前の結果は使わない。 + val other = GroundImageState(bounds = bounds, imageUrl = "https://example.test/old.png") + other.imageUrl = "https://example.test/new.png" + + loadAll() + + assertEquals(8, state.image.intrinsicWidth) + assertNotEquals(placeholder.hashCode(), state.image.hashCode()) + assertEquals("https://example.test/new.png", other.imageUrl) + assertEquals( + GroundImageState(bounds = bounds, imageUrl = "https://example.test/new.png").image, + other.image, + ) + + // 画像を直接書き換えたら URL は消える。copy は URL を引き継ぐ。 + assertEquals("https://example.test/ground.png", state.copy(opacity = 0.5f).imageUrl) + state.image = ColorDrawable(Color.GREEN) + assertNull(state.imageUrl) + assertFalse(state.image is UrlImageDrawable) + } +} diff --git a/src/androidTest/java/com/mapconductor/core/circle/CircleNationwidePerformanceTest.kt b/src/androidTest/java/com/mapconductor/core/circle/CircleNationwidePerformanceTest.kt new file mode 100644 index 0000000..2f4767d --- /dev/null +++ b/src/androidTest/java/com/mapconductor/core/circle/CircleNationwidePerformanceTest.kt @@ -0,0 +1,68 @@ +package com.mapconductor.core.circle + +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.dp +import androidx.test.platform.app.InstrumentationRegistry +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.shapetile.ShapeGridIndex +import com.mapconductor.core.shapetile.ShapeTileRenderer +import org.junit.Assert.assertTrue +import org.junit.Test +import java.nio.ByteBuffer +import java.nio.ByteOrder +import kotlin.math.acos +import kotlin.math.ln +import kotlin.math.sin +import android.util.Log + +class CircleNationwidePerformanceTest { + @Test fun nationwideZoomTiles() { + val bytes = + InstrumentationRegistry + .getInstrumentation() + .context.assets + .open("antennas/us-antennas.bin") + .use { it.readBytes() } + val b = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN) + b.position(4) + val count = b.int + val circles = + List(count) { + val lat = b.float.toDouble() + val lon = b.float.toDouble() + val height = b.float.toDouble() + val id = b.int + val radius = 6378137.0 * (acos(6378137.0 / (6378137.0 + height)) + acos(6378137.0 / 6378138.5)) + TileCircle.from( + CircleState( + center = GeoPoint(lat, lon), radiusMeters = radius, id = "$id", geodesic = true, + fillColor = Color.Blue.copy(alpha = 0.035f), strokeColor = Color.Blue.copy(alpha = 0.35f), + strokeWidth = 0.5.dp, + ), + )!! + } + val start = System.nanoTime() + val index = ShapeGridIndex.build(count) { circles[it].bbox } + Log.i("CirclePerf", "indexMs=${(System.nanoTime() - start) / 1e6} large=${index.large.size}") + val renderer = ShapeTileRenderer(pixelScale = { 2f }, painter = CircleTilePainter) + renderer.setItems(circles) + for (z in listOf(4, 6, 8, 10, 12, 14)) { + val n = 1 shl z + val x = ((-98.0 + 180) / 360 * n).toInt() + val latitude = 39.0 * Math.PI / 180 + val y = ((0.5 - ln((1 + sin(latitude)) / (1 - sin(latitude))) / (4 * Math.PI)) * n).toInt() + val q = System.nanoTime() + val candidates = + index + .query({ circles[it].bbox }, x.toDouble() / n, y.toDouble() / n, (x + 1.0) / n, (y + 1.0) / n) + val queryMs = (System.nanoTime() - q) / 1e6 + val t = System.nanoTime() + val bitmap = renderer.renderBitmap(x, y, z) + val renderMs = (System.nanoTime() - t) / 1e6 + assertTrue(candidates.isNotEmpty()) + assertTrue(bitmap != null) + bitmap?.recycle() + Log.i("CirclePerf", "z=$z candidates=${candidates.size} queryMs=$queryMs renderMs=$renderMs") + } + } +} diff --git a/src/androidTest/java/com/mapconductor/core/circle/CircleTileFileDeviceTest.kt b/src/androidTest/java/com/mapconductor/core/circle/CircleTileFileDeviceTest.kt new file mode 100644 index 0000000..3590c36 --- /dev/null +++ b/src/androidTest/java/com/mapconductor/core/circle/CircleTileFileDeviceTest.kt @@ -0,0 +1,167 @@ +package com.mapconductor.core.circle + +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.dp +import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.mapconductor.core.ResourceProvider +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.shapetile.ShapeTileRenderer +import com.mapconductor.core.tileserver.TileRequest +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Assert.fail +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import org.junit.runner.RunWith +import java.io.File +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicReference +import kotlin.concurrent.thread +import kotlinx.coroutines.runBlocking + +@RunWith(AndroidJUnit4::class) +class CircleTileFileDeviceTest { + @get:Rule val temporary = TemporaryFolder() + + private fun renderer() = ShapeTileRenderer(pixelScale = { 1f }, painter = CircleTilePainter) + + private fun state( + lat: Double, + lng: Double, + geodesic: Boolean, + id: String? = null, + ) = CircleState( + id = id, center = GeoPoint(lat, lng), radiusMeters = 250000.0, geodesic = geodesic, + fillColor = Color(0x802563EB), strokeColor = Color.Red, strokeWidth = 1.dp, + ) + + @Test fun fileAndMemoryProduceIdenticalPixelsAndUpdates() { + for (geodesic in listOf(false, true)) { + val data = + listOf(state(0.0, 0.0, geodesic), state(69.0, -150.0, geodesic), state(42.0, -71.0, geodesic)) + .map { TileCircle.from(it)!! } + val memory = renderer().apply { setItems(data) } + val disk = + renderer().apply { + setStorage( + CircleTileFileStorage + .create(temporary.root, data.size, { data[it] }), + ) + } + try { + for ((z, x, y) in listOf(Triple(0, 0, 0), Triple(4, 1, 3), Triple(4, 4, 5))) { + fun compare() { + val a = memory.renderBitmap(x, y, z) + val b = disk.renderBitmap(x, y, z) + if (a == null) { + assertNull(b) + } else { + assertNotNull(b) + assertTrue("Pixel mismatch at $z/$x/$y geodesic=$geodesic", a.sameAs(b)) + a.recycle() + b!!.recycle() + } + } + compare() + val changed = TileCircle.from(state(60.0, -130.0, !geodesic).apply { fillColor = Color.Green })!! + memory.update(listOf(1 to changed, 2 to null)) + disk.update(listOf(1 to changed, 2 to null)) + compare() + } + } finally { + memory.clear() + disk.clear() + } + } + assertTrue(temporary.root.listFiles()!!.isEmpty()) + } + + @Test fun retiringModelWaitsForItsInFlightTileReader() { + val item = TileCircle.from(state(0.0, 0.0, true))!! + val storage = CircleTileFileStorage.create(temporary.root, 2001, { item }) + val file = storage.cacheFile + val renderer = renderer().apply { setStorage(storage) } + val entered = CountDownLatch(1) + val resume = CountDownLatch(1) + val failure = AtomicReference() + val result = AtomicReference() + val reader = + thread { + try { + result.set( + renderer.renderTile(TileRequest(0, 0, 0)) { + entered.countDown() + check(resume.await(10, TimeUnit.SECONDS)) + false + }, + ) + } catch (error: Throwable) { + failure.set(error) + } + } + try { + assertTrue(entered.await(10, TimeUnit.SECONDS)) + renderer.clear() + assertTrue("Old file must remain readable", file.exists()) + } finally { + resume.countDown() + reader.join(10000) + renderer.clear() + } + assertFalse(reader.isAlive) + assertNull(failure.get()) + assertNotNull(result.get()) + assertFalse("Last reader releases the retired file", file.exists()) + } + + @Test fun cancelledRequestReleasesItsFileLease() { + val storage = CircleTileFileStorage.create(temporary.root, 3, { TileCircle.from(state(0.0, 0.0, true)) }) + val file = storage.cacheFile + val renderer = renderer().apply { setStorage(storage) } + try { + try { + renderer.renderTile(TileRequest(0, 0, 0)) { true } + fail("Expected cancellation") + } catch ( + _: ShapeTileRenderer.TileRenderCancelled, + ) { + } + assertTrue(file.exists()) + } finally { + renderer.clear() + } + assertFalse(file.exists()) + } + + @Test fun automaticallyUsesFilesAbove2000AndDeletesThemOnDispose() = + runBlocking { + ResourceProvider.init( + androidx.test.platform.app.InstrumentationRegistry + .getInstrumentation() + .targetContext, + ) + val directory = File(ResourceProvider.getAppContext().cacheDir, "mapconductor-circle-geometry") + val before = directory.listFiles()?.toSet() ?: emptySet() + val set = CircleTileSet() + var created = emptySet() + try { + val states = List(2001) { state(42.0, -71.0, true, "file-$it").apply { zIndex = it } } + set.setCircles(states.take(2000)) + assertEquals(before, directory.listFiles()?.toSet() ?: emptySet()) + set.setCircles(states) + created = directory.listFiles()!!.toSet() - before + assertEquals(1, created.size) + set.setCircles(states.filterIndexed { index, _ -> index % 2 == 0 }) + assertFalse(set.has(states[1].id)) + assertTrue(set.has(states[0].id)) + } finally { + set.dispose() + } + assertTrue(created.none { it.exists() }) + } +} diff --git a/src/androidTest/java/com/mapconductor/core/circle/CircleTileRendererDeviceTest.kt b/src/androidTest/java/com/mapconductor/core/circle/CircleTileRendererDeviceTest.kt new file mode 100644 index 0000000..6ec4fe8 --- /dev/null +++ b/src/androidTest/java/com/mapconductor/core/circle/CircleTileRendererDeviceTest.kt @@ -0,0 +1,414 @@ +package com.mapconductor.core.circle + +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.dp +import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.features.GeoPointInterface +import com.mapconductor.core.geometry.circleToRing +import com.mapconductor.core.polygon.toMercatorRing +import com.mapconductor.core.shapetile.ShapeTileRenderer +import com.mapconductor.core.tileserver.TileRequest +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNotSame +import org.junit.Assert.assertNull +import org.junit.Assert.assertSame +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import kotlin.math.PI +import kotlin.math.floor +import kotlin.math.ln +import kotlin.math.sin +import android.graphics.Bitmap +import android.graphics.BitmapFactory +import kotlinx.coroutines.runBlocking + +/** + * 円のタイルの画素。tile-sw.js の「Shape tiles」節の円と同じ描き方であることを固定する。 + * PolylineTileRendererDeviceTest と同じく、1 単位 = 1 画素(pixelScale = 1)で描かせる。 + * + * z0 のタイルは世界全体が 256 画素。js-sdk-core の `CircleTileRendering.test.mjs`、 + * ios-sdk の `CircleTileRendererTests` と 1 対 1。 + */ +@RunWith(AndroidJUnit4::class) +class CircleTileRendererDeviceTest { + @Test + fun filteringSharesGeometryButHidesSourcesAndPixels() = runBlocking { + val left = CircleState(id = "left", center = p(0.0, -60.0), radiusMeters = 500000.0, zIndex = 0) + val right = CircleState(id = "right", center = p(0.0, 60.0), radiusMeters = 500000.0, zIndex = 1) + val set = CircleTileSet() + try { + set.setCircles(listOf(left, right)) + val leftGeometry = set.renderer.itemAt(0) + val rightGeometry = set.renderer.itemAt(1) + val initialIds = set.shapes.ids() + repeat(3) { + set.setCircles(listOf(left)) + assertSame(leftGeometry, set.renderer.itemAt(0)) + assertSame(rightGeometry, set.renderer.itemAt(1)) + assertEquals(setOf("left"), set.shapes.ids()) + assertNull(set.shapes.source("right")) + val sources = mutableListOf() + set.shapes.visitSources { sources.add(it) } + assertEquals(listOf(left), sources) + val bitmap = set.renderer.renderBitmap(0, 0, 0)!! + assertTrue(alpha(bitmap.getPixel(bitmap.width / 3, bitmap.height / 2)) > 0) + assertEquals(0, alpha(bitmap.getPixel(bitmap.width * 2 / 3, bitmap.height / 2))) + bitmap.recycle() + set.setCircles(listOf(left, right)) + assertSame(rightGeometry, set.renderer.itemAt(1)) + assertSame(right, set.shapes.source("right")) + assertEquals(setOf("left", "right"), initialIds) + } + // Same state identity with a changed value must rebuild geometry. + left.radiusMeters = 700000.0 + set.setCircles(listOf(left, right)) + assertNotSame(leftGeometry, set.renderer.itemAt(0)) + } finally { + set.dispose() + } + } + + @Test + fun filteringDoesNotReuseChangedStackingOrder() = runBlocking { + val a = CircleState(id = "a", center = p(0.0, 0.0), radiusMeters = 1000.0, zIndex = 0) + val b = CircleState(id = "b", center = p(0.0, 0.0), radiusMeters = 1000.0, zIndex = 0) + val set = CircleTileSet() + try { + set.setCircles(listOf(a, b)) + val first = set.renderer.itemAt(0) + set.setCircles(listOf(b, a)) + assertNotSame(first, set.renderer.itemAt(0)) + b.zIndex = 2 + set.setCircles(listOf(b, a)) + assertEquals(1000.0, set.renderer.itemAt(0)!!.radiusMeters, 0.0) + assertEquals(listOf("a", "b"), set.shapes.ids().sorted()) + } finally { + set.dispose() + } + } + + private val red = Color(0xFFFF0000) + private val blue = Color(0xFF0000FF) + private val green = Color(0xFF00FF00) + + private fun p( + latitude: Double, + longitude: Double, + ): GeoPointInterface = GeoPoint.fromLatLong(latitude, longitude) + + private fun renderer(vararg states: CircleState) = + ShapeTileRenderer(tileSize = 256, pixelScale = { 1f }, painter = CircleTilePainter).apply { + setItems(states.sortedBy(::effectiveZIndex).map(TileCircle::from)) + } + + private fun alpha(pixel: Int) = pixel ushr 24 + + private fun rgb(pixel: Int) = pixel and 0xFFFFFF + + private fun worldX( + lng: Double, + z: Int, + ): Double = (lng + 180) / 360 * 256.0 * (1 shl z) + + private fun worldY( + lat: Double, + z: Int, + ): Double { + val s = sin(lat * PI / 180) + return (0.5 - ln((1 + s) / (1 - s)) / (4 * PI)) * 256.0 * (1 shl z) + } + + /** The columns of row [y] that are painted (alpha over half). */ + private fun paintedColumns( + bitmap: Bitmap, + y: Int, + ): List = (0 until bitmap.width).filter { alpha(bitmap.getPixel(it, y)) > 0x80 } + + /** A circle at the equator, [radiusPx] pixels across at [z] (radius of a z-world pixel = 40075 km / 256 / 2^z). */ + private fun equatorCircle( + lng: Double, + radiusPx: Double, + z: Int, + fill: Color = Color(0x800000FF), + stroke: Color = red, + strokeWidth: Float = 2f, + id: String? = null, + zIndex: Int? = 0, + lat: Double = 0.0, + ): CircleState { + val metersPerPx = 2 * PI * 6378137.0 / (256.0 * (1 shl z)) + return CircleState( + center = p(lat, lng), + radiusMeters = radiusPx * metersPerPx, + fillColor = fill, + strokeColor = stroke, + strokeWidth = strokeWidth.dp, + id = id, + zIndex = zIndex, + ) + } + + /** 中心は塗りの色、半径の所に縁の色 */ + @Test + fun tiledManagerSharesSourceStatesWithoutPersistentEntities() = kotlinx.coroutines.runBlocking { + val states = List(2001) { i -> CircleState(center = GeoPoint(0.001 * i, 0.0), radiusMeters = 5.0, id = "shared-$i") } + val tiler = CircleTiler() + val manager = CircleManager() + try { + tiler.route(states) + assertTrue(manager.setTiledSource(tiler)) + assertTrue(manager.nativeEntities().isEmpty()) + assertTrue(manager.hasEntity("shared-123")) + org.junit.Assert.assertSame(states[123], manager.getEntity("shared-123")!!.state) + org.junit.Assert.assertSame(states[123], manager.find(states[123].center)!!.state) + assertTrue(manager.nativeEntities().isEmpty()) + val replacement = states[25].copy(radiusMeters = 8.0) + tiler.update(replacement) + org.junit.Assert.assertSame(replacement, manager.getEntity(replacement.id)!!.state) + tiler.remove("shared-123") + org.junit.Assert.assertFalse(manager.hasEntity("shared-123")) + assertNull(manager.getEntity("shared-123")) + manager.clear() + org.junit.Assert.assertFalse(manager.hasEntity("shared-25")) + } finally { tiler.dispose() } + } + + @Test + fun subpixelOverlapKeepsOnlyTopCircle_andZoomRestoresBoth() { + val lower = equatorCircle(0.0, 0.2, 0, fill = Color(0x800000FF), id = "lower") + val upper = equatorCircle(0.0, 0.2, 0, fill = Color(0x80FF0000), id = "upper") + val r = renderer(lower, upper) + val small = r.renderBitmap(0, 0, 0)!! + assertEquals(0, rgb(small.getPixel(128, 128)) and 0xFF) + assertEquals(128, alpha(small.getPixel(128, 128))) + val large = r.renderBitmap(8, 8, 4)!! + assertTrue("both translucent circles return", (large.getPixel(0, 0) and 0xFF) > 0) + assertTrue(alpha(large.getPixel(0, 0)) > 128) + } + + @Test + fun centreIsFilled_andTheEdgeIsStroked() { + // z4: 世界 4096 px。経度 -168.75 度 = x 128(タイル 0 の真ん中)、北緯 10 度 = y 1933.6(タイル 7) + val lat = 10.0 + val z = 4 + val state = equatorCircle(lng = -168.75, radiusPx = 40.0, z = z, fill = Color(0xFF0000FF), lat = lat) + val bitmap = renderer(state).renderBitmap(0, 7, z)!! + val cx = worldX(-168.75, z) - 0 + val cy = worldY(lat, z) - 7 * 256 + assertEquals("中心は塗り", 0x0000FF, rgb(bitmap.getPixel(cx.toInt(), cy.toInt()))) + // 赤道の 40 px は緯度 10 度で 40 / cos(10°) ≒ 40.6 px(メルカトルで地上の大きさ) + val radius = 40.0 / kotlin.math.cos(lat * PI / 180) + val row = cy.toInt() + val painted = paintedColumns(bitmap, row) + assertEquals("左端", cx - radius - 1, painted.first().toDouble(), 1.5) + assertEquals("右端", cx + radius + 1, painted.last().toDouble() + 1, 1.5) + assertEquals("縁は赤", 0xFF0000, rgb(bitmap.getPixel((cx + radius).toInt(), row))) + assertEquals("外は透明", 0, alpha(bitmap.getPixel((cx + radius + 4).toInt(), row))) + } + + /** タイルの境目にかかる円は、両側のタイルに同じ位置・大きさで欠けずに出る */ + @Test + fun circleOnATileEdgeIsDrawnOnBothSides() { + // z1: 経度 0 度は x 方向のタイルの境目。中心をそこに置く + val z = 1 + val state = equatorCircle(lng = 0.0, radiusPx = 30.0, z = z, fill = Color(0xFF00FF00), stroke = green, lat = 30.0) + val r = renderer(state) + val west = r.renderBitmap(0, 0, z)!! + val east = r.renderBitmap(1, 0, z)!! + val row = worldY(30.0, z).toInt() + val westCols = paintedColumns(west, row) + val eastCols = paintedColumns(east, row) + // 西のタイルは右端まで、東のタイルは左端から塗る。幅は左右で同じ + assertEquals(255, westCols.last()) + assertEquals(0, eastCols.first()) + assertEquals((256 - westCols.first()).toDouble(), (eastCols.last() + 1).toDouble(), 1.0) + // 中心の行で切れ目が無い(境目の両側の画素が塗られている) + assertTrue(alpha(west.getPixel(255, row)) > 0x80 && alpha(east.getPixel(0, row)) > 0x80) + } + + /** ズームを 1 段上げると半径の画素数は 2 倍(地上の大きさが保たれる)、縁幅は同じ */ + @Test + fun radiusDoublesPerZoom_strokeStaysTheSame() { + // ボストンの、z17 でタイルの 1/3 の所: z18 で 2/3、z19 で 1/3。どのズームでも円がタイルに収まる + val scale17 = 256.0 * (1 shl 17) + val wx17 = (floor(worldX(-71.0605, 17) / 256) + 1.0 / 3) * 256 + val wy17 = (floor(worldY(42.3555, 17) / 256) + 1.0 / 3) * 256 + val lng = wx17 / scale17 * 360 - 180 + val lat = kotlin.math.atan(kotlin.math.sinh(PI * (1 - 2 * wy17 / scale17))) * 180 / PI + val state = + CircleState( + center = p(lat, lng), + radiusMeters = 15.0, + fillColor = Color.Transparent, + strokeColor = blue, + strokeWidth = 2.dp, + ) + val r = renderer(state) + val widths = mutableListOf() + val strokes = mutableListOf() + for (z in 17..19) { + val wx = worldX(lng, z) + val wy = worldY(lat, z) + val tx = (wx / 256).toInt() + val ty = (wy / 256).toInt() + val bitmap = r.renderBitmap(tx, ty, z) + assertNotNull("z$z", bitmap) + val row = (wy - ty * 256).toInt() + val cols = paintedColumns(bitmap!!, row) + widths += cols.last() - cols.first() + // 縁幅: 左の縁の塗られた列の数 + var n = 0 + var c = cols.first() + while (c < 256 && alpha(bitmap.getPixel(c, row)) > 0x80) { + n++ + c++ + } + strokes += n + } + assertEquals("$widths", widths[0] * 2.0, widths[1].toDouble(), 2.5) + assertEquals("$widths", widths[1] * 2.0, widths[2].toDouble(), 2.5) + assertTrue("$strokes", strokes.all { it in 1..3 }) + } + + /** 直径 1 px 未満は 1 px の点(アンチエイリアスなし、塗りの色) */ + @Test + fun subPixelCircleIsOnePixel() { + val state = CircleState(center = p(0.0, 0.0), radiusMeters = 100.0, fillColor = Color(0xFF00FF00), strokeColor = red) + val bitmap = renderer(state).renderBitmap(0, 0, 0)!! + var painted = 0 + for (py in 120..136) { + for (px in 120..136) { + val pixel = bitmap.getPixel(px, py) + if (alpha(pixel) > 0) { + painted++ + assertEquals(0x00FF00, rgb(pixel)) + assertEquals(0xFF, alpha(pixel)) + } + } + } + assertEquals(1, painted) + assertTrue(alpha(bitmap.getPixel(128, 128)) == 0xFF) + } + + /** 直径 4 px 未満は縁を描かない(塗りだけ) */ + @Test + fun underFourPixelsAcrossHasNoOutline() { + val state = equatorCircle(lng = 0.0, radiusPx = 1.5, z = 0, fill = Color(0xFF00FF00), stroke = red, strokeWidth = 2f) + val bitmap = renderer(state).renderBitmap(0, 0, 0)!! + for (py in 120..136) { + for (px in 120..136) { + val pixel = bitmap.getPixel(px, py) + if (alpha(pixel) > 0) assertTrue("($px, $py) ${Integer.toHexString(pixel)}", (pixel and 0xFF0000) ushr 16 < 0x40) + } + } + } + + /** 高緯度(70 度、200 km)は 128 角形で、circleToRing の点が通る画素に縁がある */ + @Test + fun highLatitudeCircleIsTheNativeRing() { + val state = + CircleState( + center = p(70.0, 20.0), + radiusMeters = 200_000.0, + fillColor = Color.Transparent, + strokeColor = red, + strokeWidth = 3.dp, + ) + val z = 5 + val r = renderer(state) + val ring = toMercatorRing(circleToRing(state.center, 200_000.0, true, 128)) + val scale = 256.0 * (1 shl z) + var checked = 0 + for (i in ring.indices step 2 * 8) { + val wx = ring[i] * scale + val wy = ring[i + 1] * scale + val tx = (wx / 256).toInt() + val ty = (wy / 256).toInt() + val bitmap = r.renderBitmap(tx, ty, z) ?: continue + val px = (wx - tx * 256).toInt().coerceIn(0, 255) + val py = (wy - ty * 256).toInt().coerceIn(0, 255) + // 点のまわり 1 画素に縁 + val near = + (-1..1).any { dy -> + (-1..1).any { dx -> + val x = (px + dx).coerceIn(0, 255) + val y = (py + dy).coerceIn(0, 255) + alpha(bitmap.getPixel(x, y)) > 0x80 && rgb(bitmap.getPixel(x, y)) == 0xFF0000 + } + } + assertTrue("点 $i ($wx, $wy)", near) + checked++ + } + assertEquals(16, checked) + } + + /** zIndex の大きい円が上、未指定は中心からの自動値(南が上) */ + @Test + fun higherZIndexIsOnTop_andUnsetIsTheAutomaticOne() = + runBlocking { + val set = CircleTileSet() + try { + val over = equatorCircle(lng = 0.0, radiusPx = 20.0, z = 0, fill = red, stroke = red, zIndex = 1) + val under = equatorCircle(lng = 0.0, radiusPx = 20.0, z = 0, fill = blue, stroke = blue, zIndex = 0) + set.setCircles(listOf(over, under)) + val bitmap = set.renderer.renderBitmap(0, 0, 0)!! + assertEquals("zIndex 1 が上", 0xFF0000, rgb(bitmap.getPixel(bitmap.width / 2, bitmap.height / 2))) + + // 未指定: 南の円(自動値が大きい)が北の円の上 + val south = equatorCircle(lng = 0.0, radiusPx = 20.0, z = 0, fill = green, stroke = green, zIndex = null, lat = -1.0) + val north = equatorCircle(lng = 0.0, radiusPx = 20.0, z = 0, fill = red, stroke = red, zIndex = null, lat = 1.0) + set.setCircles(listOf(south, north)) + val auto = set.renderer.renderBitmap(0, 0, 0)!! + assertEquals("南が上", 0x00FF00, rgb(auto.getPixel(auto.width / 2, auto.height / 2))) + } finally { + set.dispose() + } + } + + /** 透明な円は描かない。何も無いタイルは null(空) */ + @Test + fun invisibleCirclesDrawNothing_andEmptyTilesAreNull() { + val r = + renderer( + CircleState(center = p(40.0, 90.0), radiusMeters = 500_000.0, fillColor = Color.Transparent, strokeColor = Color.Transparent), + CircleState(center = p(40.0, 90.0), radiusMeters = 500_000.0, fillColor = Color.Transparent, strokeWidth = 0.dp), + ) + assertNull(r.renderTile(TileRequest(x = 1, y = 0, z = 1))) + assertNull(r.renderTile(TileRequest(x = 0, y = 0, z = 1))) + } + + /** 色を変えたら、その円のタイルだけ描き直す(他はキャッシュ) */ + @Test + fun inPlaceChangeRedrawsOnlyTheTilesItTouches() { + val west = CircleState(center = p(30.0, -90.0), radiusMeters = 300_000.0, fillColor = blue, strokeColor = blue, id = "west") + val east = CircleState(center = p(30.0, 90.0), radiusMeters = 300_000.0, fillColor = blue, strokeColor = blue, id = "east") + val r = renderer(west, east) + val westTile = TileRequest(x = 0, y = 0, z = 1) + val eastTile = TileRequest(x = 1, y = 0, z = 1) + val westBefore = r.renderTile(westTile)!! + val eastBefore = r.renderTile(eastTile)!! + + // renderer() は実効 zIndex で並べる: 自動値は同じ緯度なら西が上(大きい)→ west は後ろ + val westIndex = listOf(west, east).sortedBy(::effectiveZIndex).indexOf(west) + west.fillColor = green + west.strokeColor = green + r.update(listOf(westIndex to TileCircle.from(west))) + + val westAfter = r.renderTile(westTile)!! + assertNotSame("変えた円のタイルは描き直す", westBefore, westAfter) + assertSame("触れていないタイルはキャッシュから返す", eastBefore, r.renderTile(eastTile)) + val decoded = BitmapFactory.decodeByteArray(westAfter, 0, westAfter.size) + assertEquals(0x00FF00, rgb(decoded.getPixel(worldX(-90.0, 1).toInt(), worldY(30.0, 1).toInt()))) + } + + /** 取りやめられたタイルは空ではなく失敗にする */ + @Test + fun cancelledTileFailsInsteadOfComingBackEmpty() { + val r = renderer(CircleState(center = p(0.0, 0.0), radiusMeters = 1_000_000.0, fillColor = blue)) + val thrown = runCatching { r.renderTile(TileRequest(x = 0, y = 0, z = 0)) { true } }.exceptionOrNull() + assertTrue(thrown is ShapeTileRenderer.TileRenderCancelled) + } +} diff --git a/src/androidTest/java/com/mapconductor/core/circle/CircleTilerDeviceTest.kt b/src/androidTest/java/com/mapconductor/core/circle/CircleTilerDeviceTest.kt new file mode 100644 index 0000000..63fa9f4 --- /dev/null +++ b/src/androidTest/java/com/mapconductor/core/circle/CircleTilerDeviceTest.kt @@ -0,0 +1,409 @@ +package com.mapconductor.core.circle + +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.dp +import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.mapconductor.core.controller.BaseMapViewController +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.features.GeoPointInterface +import com.mapconductor.core.features.GeoRectBounds +import com.mapconductor.core.map.MapCameraPosition +import com.mapconductor.core.tileserver.TileServerRegistry +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import java.net.HttpURLConnection +import java.net.URL +import kotlin.math.ln +import kotlin.math.sin +import android.graphics.BitmapFactory +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout + +/** + * CircleController と CircleTiler の振り分け。PolylineTilerDeviceTest と同じ規則: + * タイルにした円は CircleManager に残し(タップ用、元の円のまま)、レンダラには渡さない。 + * js-sdk-core の CircleController(tiler)、ios-sdk-core の CircleTilerTests と同じ内容。 + * + * CircleTileSet が本物のタイルサーバーに経路を作るので、端末で動かす。 + */ +@RunWith(AndroidJUnit4::class) +class CircleTilerDeviceTest { + private fun p( + latitude: Double, + longitude: Double, + ): GeoPointInterface = GeoPoint.fromLatLong(latitude, longitude) + + private val events = mutableListOf() + + /** 半径 20 m の木を n 本、ボストンに 0.0012 度(東西 ≒ 99 m、南北 ≒ 133 m)おきに並べる。 */ + private fun trees( + n: Int, + color: Color = Color(0xFF12B886), + ): List = + List(n) { i -> + val lat = 42.30 + (i / 100) * 0.0012 + val lng = -71.10 + (i % 100) * 0.0012 + CircleState( + center = p(lat, lng), + radiusMeters = 20.0, + id = "tree-$i", + fillColor = color, + strokeColor = color, + strokeWidth = 2.dp, + zIndex = 0, + onAdded = { events += "onAdded:${it.id}" }, + ) + } + + private inner class Renderer : CircleOverlayRendererInterface { + val onMap = mutableSetOf() + val added = mutableListOf() + val removed = mutableListOf() + + override suspend fun onAdd(data: List): List = + data.map { params -> + events += "native:${params.state.id}" + params.state.id.also { + onMap.add(it) + added.add(it) + } + } + + override suspend fun onChange(data: List>): List = + data.map { it.current.state.id } + + override suspend fun onRemove(data: List>) { + data.forEach { + onMap.remove(it.state.id) + removed.add(it.state.id) + } + } + + override suspend fun onPostProcess() {} + } + + private class Controller( + renderer: CircleOverlayRendererInterface, + ) : CircleController(CircleManager(), renderer) + + private class Templates { + val seen = mutableListOf() + + fun last() = synchronized(this) { seen.lastOrNull() } + } + + private fun controller(options: CircleTilingOptions = CircleTilingOptions.Default): Triple { + val renderer = Renderer() + val controller = Controller(renderer) + val templates = Templates() + controller.tiler = + CircleTiler(options).apply { + onTemplate = { template, _ -> synchronized(templates) { templates.seen.add(template) } } + } + return Triple(controller, renderer, templates) + } + + /** しきい値を超えたらネイティブには何も渡さず、タップ用にマネージャへ残す */ + @Test + fun pastThresholdNothingGoesNative_andTapsStillHit() = + runBlocking { + val (controller, renderer, templates) = controller() + controller.onCameraChanged(MapCameraPosition(position = p(42.30, -71.10), zoom = 16.0)) + controller.add(trees(2001)) + assertTrue(renderer.onMap.isEmpty()) + assertEquals(2001, controller.circleManager.allEntities().size) + assertNotNull(templates.last()) + // tree-101: 北緯 42.3012、経度 -71.0988。中心から 15 m 東は当たる + assertEquals("tree-101", controller.find(p(42.3012, -71.09862))?.state?.id) + // 木と木の間は外れ + assertNull(controller.find(p(42.3018, -71.0982))) + } + + /** しきい値を下回ったらネイティブに戻し、上回ったらネイティブから外す */ + @Test + fun crossingThresholdMovesCirclesBetweenNativeAndTiles() = + runBlocking { + val (controller, renderer, templates) = controller() + controller.add(trees(2000)) + assertEquals(2000, renderer.onMap.size) + assertNull(templates.last()) + + controller.add(trees(2001)) + assertTrue("タイルへ移ったらネイティブから消す", renderer.onMap.isEmpty()) + assertEquals(2001, controller.circleManager.allEntities().size) + assertNotNull(templates.last()) + + controller.add(trees(10)) + assertEquals(10, renderer.onMap.size) + assertEquals("リストから消えたものは忘れる", 10, controller.circleManager.allEntities().size) + assertNull(templates.last()) + } + + /** タイルの円のその場の変更は、版を上げたテンプレートで知らせる */ + @Test + fun inPlaceChangeOfTiledCircleAnnouncesNewTemplate() = + runBlocking { + val (controller, renderer, templates) = controller() + val states = trees(2001) + controller.add(states) + val before = templates.last()!! + states[5].fillColor = Color(0xFFE64980) + controller.update(states[5]) + assertTrue(renderer.onMap.isEmpty()) + withTimeout(2000) { + while (templates.last() == before) delay(5) + } + assertTrue(templates.last()!! != before) + assertEquals(Color(0xFFE64980), controller.circleManager.getEntity("tree-5")?.state?.fillColor) + } + + /** タイルはタイルサーバーから PNG で届き、何も無い場所は透明の 200。URL に版が入る */ + @Test + fun tilesAreServedAsPng_andEmptyPlacesAsTransparent200() = + runBlocking { + val (controller, _, templates) = controller() + controller.add(trees(2001)) + val template = templates.last()!! + assertTrue("版が入る: $template", Regex("""/circles-\w+/256/\d+/\{z\}""").containsMatchIn(template)) + assertTrue(alphaAt(template, 42.3012, -71.0988, 17) > 0) + assertEquals("木と木の間", 0, alphaAt(template, 42.3018, -71.0982, 17)) + assertEquals(200, get(template, 14, 100, 12000).first) + } + + /** clear でテンプレートを外し、タイル側の円も忘れる */ + @Test + fun clearRemovesTemplateAndForgetsTiledCircles() = + runBlocking { + val (controller, _, templates) = controller() + controller.add(trees(2001)) + controller.clear() + assertNull(templates.last()) + assertTrue(controller.circleManager.allEntities().isEmpty()) + assertTrue(TileServerRegistry.get().isRunning()) + } + + /** 混在リストでは日付変更線の円だけネイティブ、タイルには描かれない */ + @Test + fun inAMixedListOnlyTheAntimeridianOneGoesNative() = + runBlocking { + val (controller, renderer, templates) = controller() + val dateline = CircleState(center = p(0.0, 179.999), radiusMeters = 5_000.0, id = "dateline") + controller.add(trees(2001) + dateline) + assertEquals(setOf("dateline"), renderer.onMap) + assertTrue(alphaAt(templates.last()!!, 42.3012, -71.0988, 17) > 0) + } + + /** その場で日付変更線へ動かしたらネイティブへ移り(add ではない、onAdded は呼ばない)、タイルから消える */ + @Test + fun movingOntoTheAntimeridianInPlaceMovesItToNative() = + runBlocking { + val (controller, renderer, templates) = controller() + // One becomes native; the remaining 2,001 must still exceed 2,000. + val states = trees(2002) + controller.add(states) + val before = templates.last()!! + assertTrue(alphaAt(before, 42.3012, -71.0988, 17) > 0) + events.clear() + + states[101].center = p(0.0, 179.999) + states[101].radiusMeters = 5_000.0 + controller.update(states[101]) + withTimeout(2000) { + while (templates.last() == before) delay(5) + } + assertEquals(listOf("tree-101"), renderer.added) + assertEquals("tree-101", controller.circleManager.getEntity("tree-101")?.circle) + assertEquals(listOf("native:tree-101"), events) + val after = templates.last()!! + assertEquals("タイルから消える", 0, alphaAt(after, 42.3012, -71.0988, 17)) + assertTrue("隣はタイルに残る", alphaAt(after, 42.3012, -71.0976, 17) > 0) + + // 同じリストを渡し直しても、ネイティブのまま(足しも消しもしない) + controller.add(states) + assertEquals(listOf("tree-101"), renderer.added) + assertTrue(renderer.removed.isEmpty()) + } + + // ── onAdded と地図ごとの指定(CircleOverlay 経由、本物の BaseMapViewController) ────── + + private class Driver( + val circles: Controller, + ) : BaseMapViewController() { + override val holder get() = throw UnsupportedOperationException() + override val defaultCoroutine = CoroutineScope(Dispatchers.Unconfined) + override val mainCoroutine = defaultCoroutine + + init { + registerOverlayController(circles) + } + + override fun moveCamera(position: MapCameraPosition) = Unit + + override fun animateCamera( + position: MapCameraPosition, + duration: Long, + ) = Unit + + override fun fitBounds( + bounds: GeoRectBounds, + padding: Int, + ) = Unit + + override suspend fun clearOverlays() = circles.clear() + } + + private fun CircleOverlay.show( + map: Driver, + states: List, + ) = runBlocking { render(states.associateBy { it.id }.toMutableMap(), map) } + + /** タイルで地図に載った円にも onAdded。その場の変更とネイティブへの移動では呼ばない */ + @Test + fun onAddedOnTheTilePath() { + val (controller, renderer, _) = controller(CircleTilingOptions(minCircleCount = 3)) + val map = Driver(controller) + val overlay = CircleOverlay(MutableStateFlow(mutableMapOf())) + val states = trees(4) + overlay.show(map, states) + assertEquals(listOf("onAdded:tree-0", "onAdded:tree-1", "onAdded:tree-2", "onAdded:tree-3"), events) + assertTrue(renderer.onMap.isEmpty()) + events.clear() + + states[0].fillColor = Color.Red + runBlocking { map.updateCircle(states[0]) } + states[1].radiusMeters = 0.0 + runBlocking { map.updateCircle(states[1]) } + overlay.show(map, states) + assertEquals(listOf("native:tree-1"), events) + controller.destroy() + } + + /** 地図ごとの指定(CircleOverlay の tilingOptions)は、次に円を渡すときに効く */ + @Test + fun perMapOptionsApplyOnTheNextHandOver() { + val (controller, renderer, templates) = controller() + val map = Driver(controller) + val options = MutableStateFlow(CircleTilingOptions.Disabled) + val overlay = CircleOverlay(MutableStateFlow(mutableMapOf()), options) + val states = trees(2001) + + overlay.show(map, states) + assertEquals("Disabled: 全部ネイティブ", 2001, renderer.onMap.size) + assertNull(templates.last()) + + options.value = CircleTilingOptions.Default + overlay.show(map, states) + assertTrue("Default: 全部タイル", renderer.onMap.isEmpty()) + assertNotNull(templates.last()) + assertEquals(CircleTilingOptions.Default, controller.tiler?.options) + controller.destroy() + } + + private fun alphaAt( + template: String, + lat: Double, + lng: Double, + z: Int, + ): Int { + val n = 1 shl z + val s = sin(Math.toRadians(lat)) + val my = 0.5 - ln((1 + s) / (1 - s)) / (4 * Math.PI) + val x = ((lng + 180) / 360 * n).toInt() + val y = (my * n).toInt() + val (code, bytes) = get(template, z, x, y) + assertEquals(200, code) + val bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size) ?: return 0 + val scale = 256.0 * n + val px = (lng + 180) / 360 * scale - x * 256 + val py = my * scale - y * 256 + val k = bitmap.width / 256.0 + return bitmap.getPixel((px * k).toInt(), (py * k).toInt()) ushr 24 + } + + /** タップは今の state で決める。位置を変えた直後、タイルの描き直し(まとめて 16 ms 後)より前でも */ + @Test + fun aTapFindsAMovedCircleBeforeItsTilesAreRedrawn() = + runBlocking { + val (controller, _, _) = controller() + val list = trees(2001) + controller.add(list) + val before = list[101].center + val moved = p(42.25, -71.10) + list[101].center = moved + controller.update(list[101]) + assertEquals("tree-101", controller.find(moved)?.state?.id) + assertNull(controller.find(before)) + delay(100) + assertEquals("tree-101", controller.find(moved)?.state?.id) + assertNull(controller.find(before)) + } + + /** 縁の半分は半径の外まで当たる(カメラのズームで)。半径より太い縁、描かない(透明な)縁でも */ + @Test + fun aTapOnATiledCirclesStrokeHitsIt() = + runBlocking { + val (controller, _, _) = controller() + val list = trees(2001) + for (state in list) { + state.radiusMeters = 5.0 + state.strokeWidth = 40.dp + } + list[101].strokeColor = Color.Transparent + controller.add(list) + controller.onCameraChanged(MapCameraPosition(position = p(42.3012, -71.0988), zoom = 18.0)) + val half = com.mapconductor.core.spherical.calculateMetersPerPixel(42.3012, 18.0) * 40.0 / 2.0 + val center = p(42.3012, -71.0988) + val onStroke = com.mapconductor.core.spherical.Spherical.computeOffset(center, 5.0 + half - 0.5, 270.0) + val beyond = com.mapconductor.core.spherical.Spherical.computeOffset(center, 5.0 + half + 0.5, 270.0) + assertEquals("tree-101", controller.find(onStroke)?.state?.id) + assertNull(controller.find(beyond)) + } + + /** タップは近くのタイルの円だけを読む。全国の例の規模で全部を読むと 1 回 0.6 秒かかった */ + @Test + fun aTapAmongManyTiledCirclesIsQuick() = + runBlocking { + val (controller, _, _) = controller() + val random = kotlin.random.Random(7) + val list = + List(100_000) { i -> + CircleState( + center = p(random.nextDouble(30.0, 45.0), random.nextDouble(130.0, 145.0)), + radiusMeters = 500.0, + id = "c$i", + strokeWidth = 1.dp, + onClick = {}, + ) + } + controller.add(list) + controller.onCameraChanged(MapCameraPosition(position = list[0].center, zoom = 12.0)) + val start = System.nanoTime() + for (state in list.take(10)) assertNotNull(controller.find(state.center)) + val perTapMs = (System.nanoTime() - start) / 1e6 / 10 + assertTrue("a tap took $perTapMs ms", perTapMs < 20.0) + } + + private fun get( + template: String, + z: Int, + x: Int, + y: Int, + ): Pair { + val url = template.replace("{z}", "$z").replace("{x}", "$x").replace("{y}", "$y") + val connection = URL(url).openConnection() as HttpURLConnection + connection.useCaches = false + return try { + connection.responseCode to connection.inputStream.use { it.readBytes() } + } finally { + connection.disconnect() + } + } +} diff --git a/src/androidTest/java/com/mapconductor/core/map/MapViewSaverRoundTripTest.kt b/src/androidTest/java/com/mapconductor/core/map/MapViewSaverRoundTripTest.kt new file mode 100644 index 0000000..f90d0c1 --- /dev/null +++ b/src/androidTest/java/com/mapconductor/core/map/MapViewSaverRoundTripTest.kt @@ -0,0 +1,216 @@ +package com.mapconductor.core.map + +import androidx.compose.runtime.saveable.Saver +import androidx.compose.runtime.saveable.SaverScope +import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.features.GeoRectBounds +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test +import org.junit.runner.RunWith +import android.os.Bundle +import android.os.Parcel + +/** + * 回転などの構成変更で state が Saver を通って作り直されるときに、値が落ちないこと。 + * + * [Bundle] は JVM の単体テストでは中身の無いスタブなので、実機で確かめる。保存した + * Bundle は一度 [Parcel] に書いて読み戻す(プロセスが落ちたあとの復元と同じ経路で、 + * Bundle に入れてはいけない型が混じっていればここで落ちる)。 + */ +@RunWith(AndroidJUnit4::class) +class MapViewSaverRoundTripTest { + private val rules = + listOf( + AttributionRule("© plain"), + AttributionRule( + attribution = "© ranged", + minZoom = 3, + maxZoom = 12, + bounds = GeoRectBounds(GeoPoint(35.0, 139.0), GeoPoint(36.0, 140.5)), + ), + AttributionRule(attribution = "© empty bounds", bounds = GeoRectBounds()), + ) + + @Test + fun attributionRulesSurviveParcel() { + val bundle = Bundle() + MapViewStateBundle.putAttributionRules(bundle, rules) + + val restored = MapViewStateBundle.getAttributionRules(throughParcel(bundle)) + + assertEquals(rules.size, restored.size) + rules.zip(restored).forEach { (expected, actual) -> + assertEquals(expected.attribution, actual.attribution) + assertEquals(expected.minZoom, actual.minZoom) + assertEquals(expected.maxZoom, actual.maxZoom) + assertEquals(expected.bounds?.southWest, actual.bounds?.southWest) + assertEquals(expected.bounds?.northEast, actual.bounds?.northEast) + assertEquals(expected.bounds?.isEmpty, actual.bounds?.isEmpty) + } + } + + @Test + fun missingAttributionRulesReadAsEmpty() { + assertEquals(emptyList(), MapViewStateBundle.getAttributionRules(Bundle())) + assertEquals(emptyList(), MapViewStateBundle.getAttributionRules(null)) + } + + @Test + fun saverKeepsUiSettingsCameraAndDesign() { + val state = + FakeState( + id = "state-1", + design = FakeDesign("custom-design", rules), + camera = + MapCameraPosition( + position = GeoPoint(35.68, 139.76, 12.0), + zoom = 14.5, + bearing = 30.0, + tilt = 45.0, + paddings = MapPaddings(top = 10.0, left = 20.0, bottom = 30.0, right = 40.0), + ), + ) + state.uiSettings = + MapUISettings( + scrollGesture = false, + zoomGesture = true, + rotateGesture = false, + tiltGesture = false, + paddings = MapPaddings(top = 1.0, left = 2.0, bottom = 3.0, right = 4.0), + ) + + val restored = roundTrip(FakeSaver().createSaver(), state) + + assertEquals("state-1", restored.id) + assertEquals("custom-design", restored.mapDesignType.id) + assertEquals(rules.map { it.attribution }, restored.mapDesignType.attributionRules.map { it.attribution }) + + val ui = restored.uiSettings + assertEquals(false, ui.scrollGesture) + assertEquals(true, ui.zoomGesture) + assertEquals(false, ui.rotateGesture) + assertEquals(false, ui.tiltGesture) + assertPaddings(MapPaddings(1.0, 2.0, 3.0, 4.0), ui.paddings) + + val camera = restored.cameraPosition + assertEquals(35.68, camera.position.latitude, 1e-9) + assertEquals(139.76, camera.position.longitude, 1e-9) + assertEquals(12.0, camera.position.altitude, 1e-9) + assertEquals(14.5, camera.zoom, 1e-9) + assertEquals(30.0, camera.bearing, 1e-9) + assertEquals(45.0, camera.tilt, 1e-9) + assertPaddings(MapPaddings(10.0, 20.0, 30.0, 40.0), camera.paddings!!) + } + + @Test + fun defaultUiSettingsStayDefault() { + val restored = roundTrip(FakeSaver().createSaver(), FakeState("s", FakeDesign("d", emptyList()))) + assertEquals(MapUISettings.Default.scrollGesture, restored.uiSettings.scrollGesture) + assertEquals(MapUISettings.Default.rotateGesture, restored.uiSettings.rotateGesture) + assertEquals(emptyList(), restored.mapDesignType.attributionRules) + } + + /** 以前の形式(uiSettings も camera の paddings も無い)の Bundle も読めること。 */ + @Test + fun readsBundleWrittenBeforeTheFix() { + val legacy = + Bundle().apply { + putString("stateId", "old") + putBundle("mapDesign", Bundle().apply { putString("id", "old-design") }) + putBundle( + "camera", + Bundle().apply { + putDouble("zoom", 5.0) + putDouble("tilt", 0.0) + putDouble("bearing", 0.0) + putDouble("latitude", 1.0) + putDouble("longitude", 2.0) + }, + ) + } + + val restored = FakeSaver().createSaver().restore(throughParcel(legacy))!! + + assertEquals("old", restored.id) + assertEquals("old-design", restored.mapDesignType.id) + assertEquals(MapUISettings.Default, restored.uiSettings) + assertEquals(5.0, restored.cameraPosition.zoom, 1e-9) + assertNull(restored.cameraPosition.paddings) + } + + private fun assertPaddings( + expected: MapPaddingsInterface, + actual: MapPaddingsInterface, + ) { + assertEquals(expected.top, actual.top, 1e-9) + assertEquals(expected.left, actual.left, 1e-9) + assertEquals(expected.bottom, actual.bottom, 1e-9) + assertEquals(expected.right, actual.right, 1e-9) + } + + private class FakeDesign( + override val id: String, + override val attributionRules: List, + ) : MapDesignTypeInterface { + override fun getValue(): String = id + } + + private class FakeState( + override val id: String, + design: FakeDesign, + camera: MapCameraPosition = MapCameraPosition.Default, + ) : MapViewState(camera) { + override var mapDesignType: FakeDesign = design + } + + private class FakeSaver : BaseMapViewSaver() { + override fun saveMapDesign( + state: FakeState, + bundle: Bundle, + ) { + bundle.putString("id", state.mapDesignType.id) + MapViewStateBundle.putAttributionRules(bundle, state.mapDesignType.attributionRules) + } + + override fun createState( + stateId: String, + mapDesignBundle: Bundle?, + cameraPosition: MapCameraPosition, + ): FakeState = + FakeState( + id = stateId, + design = + FakeDesign( + id = mapDesignBundle?.getString("id") ?: "", + attributionRules = MapViewStateBundle.getAttributionRules(mapDesignBundle), + ), + camera = cameraPosition, + ) + + override fun getStateId(state: FakeState): String = state.id + } + + private companion object { + fun throughParcel(bundle: Bundle): Bundle { + val parcel = Parcel.obtain() + try { + parcel.writeBundle(bundle) + parcel.setDataPosition(0) + return parcel.readBundle(MapViewSaverRoundTripTest::class.java.classLoader)!! + } finally { + parcel.recycle() + } + } + + fun roundTrip( + saver: Saver, + value: T, + ): T { + val scope = SaverScope { true } + val saved = with(saver) { scope.save(value) }!! + return saver.restore(throughParcel(saved))!! + } + } +} diff --git a/src/androidTest/java/com/mapconductor/core/map/StyleMutationParseTest.kt b/src/androidTest/java/com/mapconductor/core/map/StyleMutationParseTest.kt new file mode 100644 index 0000000..0603676 --- /dev/null +++ b/src/androidTest/java/com/mapconductor/core/map/StyleMutationParseTest.kt @@ -0,0 +1,82 @@ +package com.mapconductor.core.map + +import androidx.test.ext.junit.runners.AndroidJUnit4 +import org.junit.Assert.assertEquals +import org.junit.Test +import org.junit.runner.RunWith + +/** + * The parts of [StyleMutation] that need a real `org.json`, which the JVM + * unit tests do not have: the stub in the Android jar throws on every call, + * so reading what the style compiler wrote has to be checked on a device. + */ +@RunWith(AndroidJUnit4::class) +class StyleMutationParseTest { + @Test + fun readsWhatTheCompilerWrites() { + val parsed = + StyleMutation.parseList( + """ + [ + {"op":"setPaint","layerId":"roads","key":"line-color","value":"#fff","previous":null}, + {"op":"setLayout","layerId":"labels","key":"visibility","value":"none","previous":"visible"}, + {"op":"setFilter","layerId":"roads","value":["==","class","motorway"],"previous":null}, + {"op":"setZoomRange","layerId":"roads","minZoom":5,"maxZoom":null, + "previousMinZoom":null,"previousMaxZoom":null}, + {"op":"addLayer","layerId":"bg","layer":{"id":"bg","type":"background"},"beforeId":"water"}, + {"op":"somethingFromTheFuture","layerId":"roads"} + ] + """.trimIndent(), + ) + + assertEquals("the unknown op is dropped, the rest survive", 5, parsed.size) + // A string value keeps its quotes, or no renderer could read it back. + assertEquals("\"#fff\"", (parsed[0] as StyleMutation.SetPaint).value) + assertEquals("null", (parsed[0] as StyleMutation.SetPaint).previous) + assertEquals("\"none\"", (parsed[1] as StyleMutation.SetLayout).value) + assertEquals("[\"==\",\"class\",\"motorway\"]", (parsed[2] as StyleMutation.SetFilter).value) + assertEquals(5.0, (parsed[3] as StyleMutation.SetZoomRange).minZoom) + assertEquals(null, (parsed[3] as StyleMutation.SetZoomRange).maxZoom) + assertEquals("bg", parsed[4].layerId) + assertEquals("water", (parsed[4] as StyleMutation.AddLayer).beforeId) + } + + /** Rubbish in must not take the map down; it means no adjustment. */ + @Test + fun answersWithNothingRatherThanThrowing() { + assertEquals(emptyList(), StyleMutation.parseList("not json")) + assertEquals(emptyList(), StyleMutation.parseList("{}")) + assertEquals(emptyList(), StyleMutation.parseList("[{\"op\":\"setPaint\"}]")) + } + + @Test + fun addingALayerIsUndoneByRemovingIt() { + val add = StyleMutation.AddLayer("bg", """{"id":"bg","type":"background"}""", beforeId = null) + assertEquals(StyleMutation.RemoveLayer("bg"), add.reversed()) + } + + /** + * Applying a set and then its reverse has to leave the map where it + * started, whatever the values were. + */ + @Test + fun everyMutationUndoesItself() { + val mutations = + StyleMutation.parseList( + """ + [ + {"op":"setPaint","layerId":"a","key":"line-color","value":"#fff","previous":"#888"}, + {"op":"setLayout","layerId":"b","key":"visibility","value":"none","previous":null}, + {"op":"setFilter","layerId":"c","value":["all"],"previous":null}, + {"op":"setZoomRange","layerId":"d","minZoom":5,"maxZoom":12, + "previousMinZoom":null,"previousMaxZoom":22} + ] + """.trimIndent(), + ) + for (mutation in mutations) { + val there = mutation.reversed()!! + val andBack = there.reversed()!! + assertEquals("${mutation.target} did not survive a round trip", mutation, andBack) + } + } +} diff --git a/src/androidTest/java/com/mapconductor/core/marker/DefaultIconAnchorDeviceTest.kt b/src/androidTest/java/com/mapconductor/core/marker/DefaultIconAnchorDeviceTest.kt new file mode 100644 index 0000000..5945ed4 --- /dev/null +++ b/src/androidTest/java/com/mapconductor/core/marker/DefaultIconAnchorDeviceTest.kt @@ -0,0 +1,55 @@ +package com.mapconductor.core.marker + +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.dp +import androidx.test.ext.junit.runners.AndroidJUnit4 +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import android.util.Log + +/** + * アンカーがピンの先端に乗っているか。`scale` で縮めても `iconSize` で縮めても同じ。 + * + * 先端は、アンカー列で一番下にある不透明な画素。アンカーの y との差を px で測る。 + */ +@RunWith(AndroidJUnit4::class) +class DefaultIconAnchorDeviceTest { + private fun tipGapPx(icon: ColorDefaultIcon): Float { + val bitmapIcon = icon.toBitmapIcon() + val bitmap = bitmapIcon.bitmap + val anchorX = (bitmapIcon.anchor.x * bitmap.width).toInt().coerceIn(0, bitmap.width - 1) + val anchorY = bitmapIcon.anchor.y * bitmap.height + var lowest = -1 + for (y in 0 until bitmap.height) { + for (dx in -1..1) { + val x = (anchorX + dx).coerceIn(0, bitmap.width - 1) + if ((bitmap.getPixel(x, y) ushr 24) > 128) lowest = y + } + } + val gap = anchorY - (lowest + 1) + Log.i( + "IconAnchor", + "${bitmap.width}x${bitmap.height} anchor=${bitmapIcon.anchor} tipBottom=${lowest + 1} gap=$gap", + ) + return gap + } + + @Test + fun anchorSitsOnTheTipWhateverTheSize() { + val icons = + listOf( + ColorDefaultIcon(fillColor = Color.Red), + ColorDefaultIcon(fillColor = Color.Red, label = "T"), + ColorDefaultIcon(fillColor = Color.Blue, label = "P", scale = 0.6f), + ColorDefaultIcon(fillColor = Color.Blue, label = "P", iconSize = 28.dp), + ColorDefaultIcon(fillColor = Color.Blue, scale = 0.6f), + ColorDefaultIcon(fillColor = Color.Blue, scale = 2f), + ) + val gaps = icons.map { tipGapPx(it) / it.toBitmapIcon().bitmap.height } + // 素のピン(1 番目)の先端とアンカーの差を基準に、どの大きさでも同じ割合であること。 + for (gap in gaps) { + assertTrue("gaps $gaps", kotlin.math.abs(gap - gaps[0]) <= 0.02f) + } + } +} diff --git a/src/androidTest/java/com/mapconductor/core/marker/MarkerTileRenderBenchmark.kt b/src/androidTest/java/com/mapconductor/core/marker/MarkerTileRenderBenchmark.kt new file mode 100644 index 0000000..4292277 --- /dev/null +++ b/src/androidTest/java/com/mapconductor/core/marker/MarkerTileRenderBenchmark.kt @@ -0,0 +1,95 @@ +package com.mapconductor.core.marker + +import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.tileserver.TileRequest +import org.junit.Assert.assertNotNull +import org.junit.Test +import org.junit.runner.RunWith +import android.util.Log + +/** + * What one marker tile costs on this device, with and without decluttering. + * + * 144k markers in the street-tree shape, the tiles central Tokyo actually + * requests. Not a pass/fail gate — the point is the logged ms/tile, so a slow + * device can be measured instead of guessed about. The declutter run is the + * configuration the samples ask for; the run without it is what they were + * silently getting while the controllers dropped `declutterPx` on the floor. + */ +@RunWith(AndroidJUnit4::class) +class MarkerTileRenderBenchmark { + private fun manager(): MarkerManager { + val manager = MarkerManager.defaultManager(minMarkerCount = 1) + var seed = 12345uL + + fun next(): Double { + seed = seed * 6364136223846793005uL + 1442695040888963407uL + return (seed shr 11).toDouble() / (1uL shl 53).toDouble() + } + repeat(144_000) { at -> + manager.registerEntity( + MarkerEntity( + marker = null, + state = + MarkerState( + position = GeoPoint.fromLatLong(35.5 + next() * 0.4, 139.5 + next() * 0.5), + id = "$at", + ), + visible = true, + isRendered = true, + tiling = true, + ), + ) + } + return manager + } + + private fun renderViewport( + renderer: MarkerTileRenderer, + z: Int, + label: String, + ) { + // The tile column/row central Tokyo lands on at this zoom. + val n = 1 shl z + val centerX = ((139.75 + 180.0) / 360.0 * n).toInt() + val centerY = + run { + val latRad = Math.toRadians(35.69) + ((1.0 - Math.log(Math.tan(latRad) + 1.0 / Math.cos(latRad)) / Math.PI) / 2.0 * n).toInt() + } + var totalMs = 0L + var tiles = 0 + for (dx in -1..1) { + for (dy in -1..1) { + val start = System.nanoTime() + val bytes = renderer.renderTile(TileRequest(x = centerX + dx, y = centerY + dy, z = z)) + totalMs += (System.nanoTime() - start) / 1_000_000 + tiles += 1 + assertNotNull(bytes) + } + } + Log.i(TAG, "RENDERBENCH $label z=$z tiles=$tiles total=${totalMs}ms perTile=${totalMs / tiles}ms") + } + + @Test + fun viewportCostWithAndWithoutDeclutter() { + val manager = manager() + for (declutter in intArrayOf(0, 14)) { + val renderer = + MarkerTileRenderer( + markerManager = manager, + tileSize = 256, + cacheSizeBytes = 1, // effectively no tile cache: measure the render + declutterPx = declutter, + ) + for (z in intArrayOf(10, 11, 12, 13, 14)) { + renderViewport(renderer, z, label = "declutter=$declutter") + } + } + } + + private companion object { + private const val TAG = "MarkerTileRenderBenchmark" + } +} diff --git a/src/androidTest/java/com/mapconductor/core/marker/MarkerTileSeamDeviceTest.kt b/src/androidTest/java/com/mapconductor/core/marker/MarkerTileSeamDeviceTest.kt new file mode 100644 index 0000000..431f1f0 --- /dev/null +++ b/src/androidTest/java/com/mapconductor/core/marker/MarkerTileSeamDeviceTest.kt @@ -0,0 +1,178 @@ +package com.mapconductor.core.marker + +import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.tileserver.TileRequest +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Test +import org.junit.runner.RunWith +import android.graphics.BitmapFactory +import android.util.Log + +/** + * Adjacent rendered tiles must agree at the seam, declutter included. + * + * `MarkerTileSeamTest` (JVM) checks that the index hands both tiles the same + * candidates. This renders the actual pixels, because the seam can also be + * broken after the query: if the declutter winner inside a boundary cell + * depends on enumeration order, the two tiles keep different markers and a + * circle appears cut in half against the tile edge — found on device with the + * base layer hidden. + * + * The comparison looks at the two pixel columns facing each other across the + * seam. A marker straddling it paints both; a broken seam leaves one side + * opaque and the other transparent for roughly the icon's whole height. An + * icon merely tangent to the seam can differ for a short run, so only long + * runs count. + */ +@RunWith(AndroidJUnit4::class) +class MarkerTileSeamDeviceTest { + private fun manager(): MarkerManager { + val manager = MarkerManager.defaultManager(minMarkerCount = 1) + var seed = 12345uL + + fun next(): Double { + seed = seed * 6364136223846793005uL + 1442695040888963407uL + return (seed shr 11).toDouble() / (1uL shl 53).toDouble() + } + repeat(144_000) { at -> + manager.registerEntity( + MarkerEntity( + marker = null, + state = + MarkerState( + position = GeoPoint.fromLatLong(35.5 + next() * 0.4, 139.5 + next() * 0.5), + id = "$at", + ), + visible = true, + isRendered = true, + tiling = true, + ), + ) + } + return manager + } + + @Test + fun distinctRectanglesWithMatchingLowBitsAreAllRendered() { + val manager = MarkerManager.defaultManager(minMarkerCount = 1) + val icon = + ImageIcon( + image = android.graphics.drawable.ColorDrawable(android.graphics.Color.RED), + iconSize = + androidx.compose.ui.unit + .Dp(16f), + ) + val tilePixels = + com.mapconductor.core.ResourceProvider + .dpToPx(512.0) + .toInt() + val positions = listOf(100 to 100, 200 to 100, 100 to 356) + for ((index, point) in positions.withIndex()) { + val worldX = 8.0 + point.first.toDouble() / tilePixels + val worldY = 6.0 + point.second.toDouble() / tilePixels + val latitude = Math.toDegrees(Math.atan(Math.sinh(Math.PI * (1.0 - 2.0 * worldY / 16.0)))) + manager.registerEntity( + MarkerEntity( + marker = null, + state = + MarkerState( + position = GeoPoint.fromLatLong(latitude, worldX * 360.0 / 16.0 - 180.0), + id = "rectangle-$index", + icon = icon, + ), + visible = true, + isRendered = true, + tiling = true, + ), + ) + } + val renderer = MarkerTileRenderer(manager, tileSize = 512, cacheSizeBytes = 1) + val bytes = renderer.renderTile(TileRequest(x = 8, y = 6, z = 4))!! + val bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size) + for ((x, y) in positions) { + assertEquals("marker at $x,$y", android.graphics.Color.RED, bitmap.getPixel(x, y)) + } + bitmap.recycle() + } + + @Test + fun adjacentTilesAgreeAtEveryVerticalSeam() { + val renderer = + MarkerTileRenderer( + markerManager = manager(), + tileSize = 256, + cacheSizeBytes = 1, + declutterPx = 14, + ) + var seams = 0 + var bad = 0 + // z15+ is a different path: the declutter separation drops below the + // grid's bottom level there, the index declines the thinned query and + // the renderer falls back to the full one. + for (z in intArrayOf(12, 13, 14, 15, 16, 17)) { + val n = 1 shl z + val centerX = ((139.75 + 180.0) / 360.0 * n).toInt() + val centerY = + run { + val latRad = Math.toRadians(35.69) + ((1.0 - Math.log(Math.tan(latRad) + 1.0 / Math.cos(latRad)) / Math.PI) / 2.0 * n).toInt() + } + for (dx in -3..2) { + for (dy in -2..2) { + val at = renderer.renderTile(TileRequest(x = centerX + dx, y = centerY + dy, z = z)) + val east = renderer.renderTile(TileRequest(x = centerX + dx + 1, y = centerY + dy, z = z)) + val south = renderer.renderTile(TileRequest(x = centerX + dx, y = centerY + dy + 1, z = z)) + assertNotNull(at) + assertNotNull(east) + assertNotNull(south) + val tile = BitmapFactory.decodeByteArray(at!!, 0, at.size) + val eastTile = BitmapFactory.decodeByteArray(east!!, 0, east.size) + val southTile = BitmapFactory.decodeByteArray(south!!, 0, south.size) + seams += 2 + var worst = 0 + var run = 0 + for (y in 0 until tile.height) { + val a = (tile.getPixel(tile.width - 1, y) ushr 24) > 0x20 + val b = (eastTile.getPixel(0, y) ushr 24) > 0x20 + if (a != b) { + run += 1 + if (run > worst) worst = run + } else { + run = 0 + } + } + if (worst > 16) { + bad += 1 + Log + .i(TAG, "SEAM broken(vertical) z=$z x=${centerX + dx}/${centerX + dx + 1} y=${centerY + dy} worstRun=$worst") + } + worst = 0 + run = 0 + for (x in 0 until tile.width) { + val a = (tile.getPixel(x, tile.height - 1) ushr 24) > 0x20 + val b = (southTile.getPixel(x, 0) ushr 24) > 0x20 + if (a != b) { + run += 1 + if (run > worst) worst = run + } else { + run = 0 + } + } + if (worst > 16) { + bad += 1 + Log + .i(TAG, "SEAM broken(horizontal) z=$z x=${centerX + dx} y=${centerY + dy}/${centerY + dy + 1} worstRun=$worst") + } + } + } + } + Log.i(TAG, "SEAM seams=$seams bad=$bad") + assertEquals("seams with a half-drawn marker", 0, bad) + } + + private companion object { + private const val TAG = "MarkerTileSeamDeviceTest" + } +} diff --git a/src/androidTest/java/com/mapconductor/core/polygon/PolygonAuditDeviceTest.kt b/src/androidTest/java/com/mapconductor/core/polygon/PolygonAuditDeviceTest.kt new file mode 100644 index 0000000..bfccc43 --- /dev/null +++ b/src/androidTest/java/com/mapconductor/core/polygon/PolygonAuditDeviceTest.kt @@ -0,0 +1,67 @@ +package com.mapconductor.core.polygon + +import android.graphics.BitmapFactory +import androidx.compose.ui.graphics.Color +import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.mapconductor.core.features.GeoPoint +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.runBlocking +import org.junit.Assert.* +import org.junit.Test +import org.junit.runner.RunWith +import java.net.URL + +@RunWith(AndroidJUnit4::class) +/** Regression coverage for draw order and interrupted native-to-tile transitions. */ +class PolygonAuditDeviceTest { + private fun state(id: String, color: Color = Color.Red, z: Int = 0) = PolygonState( + id = id, points = listOf(GeoPoint(-20.0,-20.0), GeoPoint(-20.0,20.0), GeoPoint(20.0,20.0), GeoPoint(20.0,-20.0)), + fillColor = color, zIndex = z, + ) + private fun pixel(template: String): Int { + val bytes = URL(template.replace("{z}","0").replace("{x}","0").replace("{y}","0")).readBytes() + val b = BitmapFactory.decodeByteArray(bytes,0,bytes.size) + return b.getPixel(b.width/2,b.height/2).also { b.recycle() } + } + @Test fun changingZIndexMustReorderTiles() = runBlocking { + val controller = object : PolygonController(PolygonManager(),Renderer()) {} + var template = "" + controller.tiler = PolygonTiler(PolygonTilingOptions(minPolygonCount=2)).apply { + onTemplate = { value, _ -> template = value.orEmpty() } + } + try { + val red = state("red",Color.Red,0) + val blue = state("blue",Color.Blue,1) + controller.add(listOf(red,blue)) + assertEquals(android.graphics.Color.BLUE,pixel(template)) + red.zIndex = 2 + controller.update(red) + assertEquals("red should now cover blue",android.graphics.Color.RED,pixel(template)) + } finally { controller.destroy() } + } + private class Renderer : PolygonOverlayRendererInterface { + val onMap = mutableSetOf() + var cancelRemoval = false + override suspend fun onAdd(data: List) = data.map { it.state.id.also(onMap::add) } + override suspend fun onChange(data: List>) = data.map { it.current.state.id } + override suspend fun onRemove(data: List>) { + if (cancelRemoval) { cancelRemoval = false; throw CancellationException("simulated resync cancellation") } + data.forEach { onMap.remove(it.state.id) } + } + override suspend fun onPostProcess() {} + } + @Test fun cancelledTransitionMustRetryNativeRemoval() = runBlocking { + val renderer = Renderer() + val controller = object : PolygonController(PolygonManager(),renderer) {} + controller.tiler = PolygonTiler(PolygonTilingOptions(minPolygonCount=2)) + try { + val first = state("first") + controller.add(listOf(first)) + renderer.cancelRemoval = true + val many = listOf(first,state("second")) + try { controller.add(many); fail("expected cancellation") } catch (_: CancellationException) {} + controller.add(many) + assertTrue("native polygon must be removed after retry: ${renderer.onMap}",renderer.onMap.isEmpty()) + } finally { controller.destroy() } + } +} diff --git a/src/androidTest/java/com/mapconductor/core/polygon/PolygonTileRendererDeviceTest.kt b/src/androidTest/java/com/mapconductor/core/polygon/PolygonTileRendererDeviceTest.kt new file mode 100644 index 0000000..8493c5e --- /dev/null +++ b/src/androidTest/java/com/mapconductor/core/polygon/PolygonTileRendererDeviceTest.kt @@ -0,0 +1,182 @@ +package com.mapconductor.core.polygon + +import android.graphics.Bitmap +import android.graphics.BitmapFactory +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.dp +import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.features.GeoPointInterface +import com.mapconductor.core.tileserver.TileRequest +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNotSame +import org.junit.Assert.assertNull +import org.junit.Assert.assertSame +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith + +/** + * ポリゴンタイルの画素。tile-sw.js の「Polygon tiles」節と同じ描き方であることを固定する。 + * + * 1 単位 = 1 画素(pixelScale = 1)で描かせ、z0 のタイル(世界全体が 256 画素)を見る。 + * 経度 λ は x = (λ + 180) / 360 * 256、赤道は y = 128。 + */ +@RunWith(AndroidJUnit4::class) +class PolygonTileRendererDeviceTest { + private val red = Color(0xFFFF0000) + private val blue = Color(0xFF0000FF) + private val green = Color(0xFF00FF00) + + private fun p( + latitude: Double, + longitude: Double, + ): GeoPointInterface = GeoPoint.fromLatLong(latitude, longitude) + + private fun box( + south: Double, + west: Double, + north: Double, + east: Double, + ): List = listOf(p(south, west), p(south, east), p(north, east), p(north, west)) + + private fun renderer(vararg states: PolygonState) = + PolygonTileRenderer(tileSize = 256, pixelScale = { 1f }).apply { + setPolygons(states.map(TilePolygon::from)) + } + + private fun x(lng: Double) = ((lng + 180) / 360 * 256).toInt() + + private fun alpha(pixel: Int) = pixel ushr 24 + + private fun rgb(pixel: Int) = pixel and 0xFFFFFF + + /** 外周と同じ向きの穴も抜け、枠線は外周にだけ引く */ + @Test + fun holeWoundLikeOutlineIsCutOut_andOnlyOutlineIsStroked() { + val outer = box(-60.0, -90.0, 60.0, 90.0) + val hole = box(-20.0, -30.0, 20.0, 30.0) + // 穴を外周と同じ向きで渡す。nonzero で抜けるのは、描く前に巻きを逆にそろえるから + val bitmap = + renderer( + PolygonState(points = outer, holes = listOf(hole), fillColor = blue, strokeColor = red, strokeWidth = 2.dp), + ).renderBitmap(0, 0, 0)!! + assertEquals("穴の中は透明", 0, alpha(bitmap.getPixel(128, 128))) + assertEquals("塗り", 0x0000FF, rgb(bitmap.getPixel(x(-60.0), 128))) + assertEquals("外周の枠線", 0xFF0000, rgb(bitmap.getPixel(x(-90.0), 128))) + // 穴の縁(経度 -30 度)は塗りの縁で、枠線の色は無い + for (dx in -1..1) { + val pixel = bitmap.getPixel(x(-30.0) + dx, 128) + assertTrue("穴の縁 dx=$dx に枠線の赤: ${Integer.toHexString(pixel)}", (pixel shr 16 and 0xFF) < 0x40) + } + } + + /** 画面上 4 画素未満のポリゴンは枠線を省く */ + @Test + fun polygonUnderFourPixelsHasNoOutline() { + // 経度 2 度 = 1.4 画素、緯度 2 度 ≒ 1.4 画素 + val bitmap = + renderer( + PolygonState(points = box(0.0, 0.0, 4.0, 4.0), fillColor = blue, strokeColor = red, strokeWidth = 1.dp), + ).renderBitmap(0, 0, 0)!! + var reddest = 0 + for (py in 120..130) for (px in 125..135) reddest = maxOf(reddest, bitmap.getPixel(px, py) shr 16 and 0xFF) + assertEquals("枠線の赤が無い", 0, reddest) + } + + /** 1 画素に満たないポリゴンは塗りの色の 1 画素になる */ + @Test + fun subPixelPolygonIsOnePixelOfFill() { + val bitmap = + renderer( + PolygonState(points = box(0.0, 0.0, 0.01, 0.01), fillColor = blue, strokeColor = red), + ).renderBitmap(0, 0, 0)!! + var painted = 0 + for (py in 0 until 256) { + for (px in 0 until 256) { + val pixel = bitmap.getPixel(px, py) + if (alpha(pixel) != 0) { + painted++ + assertEquals(0x0000FF, rgb(pixel)) + } + } + } + assertEquals(1, painted) + } + + /** 何も無いタイルと、見えない色だけのタイルは null(空) */ + @Test + fun tileWithNothingVisibleIsEmpty() { + val r = + renderer( + PolygonState(points = box(0.0, 10.0, 10.0, 20.0), fillColor = Color.Transparent, strokeColor = Color.Transparent), + ) + // z1 の北西のタイル(経度 -180..0、北半球)には何も無い + assertNull(r.renderTile(TileRequest(x = 0, y = 0, z = 1))) + // 北東のタイルにはあるが、見えない色だけ + assertNull(r.renderTile(TileRequest(x = 1, y = 0, z = 1))) + } + + /** その場の変更は、重なるタイルだけ描き直す */ + @Test + fun inPlaceChangeRedrawsOnlyOverlappingTiles() { + val west = PolygonState(points = box(10.0, -100.0, 20.0, -90.0), fillColor = blue, id = "west") + val east = PolygonState(points = box(10.0, 90.0, 20.0, 100.0), fillColor = blue, id = "east") + val r = renderer(west, east) + val westTile = TileRequest(x = 0, y = 0, z = 1) + val eastTile = TileRequest(x = 1, y = 0, z = 1) + val westBefore = r.renderTile(westTile)!! + val eastBefore = r.renderTile(eastTile)!! + + west.fillColor = green + r.update(listOf(0 to TilePolygon.from(west))) + + val westAfter = r.renderTile(westTile)!! + assertNotSame("変えたポリゴンのタイルは描き直す", westBefore, westAfter) + assertSame("触れていないタイルはキャッシュから返す", eastBefore, r.renderTile(eastTile)) + val decoded = decode(westAfter) + // z1: 世界が 512 画素。経度 -95 度は x = 120、北緯 15 度は y = 234 + assertEquals(0x00FF00, rgb(decoded.getPixel(120, 234))) + } + + /** タイルから外したポリゴン(null)は、重なっていたタイルだけ描き直して消える */ + @Test + fun removedPolygonRedrawsOnlyItsTiles() { + val west = PolygonState(points = box(10.0, -100.0, 20.0, -90.0), fillColor = blue, id = "west") + val east = PolygonState(points = box(10.0, 90.0, 20.0, 100.0), fillColor = blue, id = "east") + val r = renderer(west, east) + val westTile = TileRequest(x = 0, y = 0, z = 1) + val eastTile = TileRequest(x = 1, y = 0, z = 1) + assertNotNull(r.renderTile(westTile)) + val eastBefore = r.renderTile(eastTile)!! + + r.update(listOf(0 to null)) + + assertNull("外したポリゴンしか無いタイルは空", r.renderTile(westTile)) + assertSame("触れていないタイルはキャッシュから返す", eastBefore, r.renderTile(eastTile)) + } + + /** 形が変わったら索引も作り直す */ + @Test + fun movedShapeIsReindexed() { + val moving = PolygonState(points = box(10.0, -100.0, 20.0, -90.0), fillColor = blue, id = "m") + val r = renderer(moving) + assertNull(r.renderTile(TileRequest(x = 1, y = 0, z = 1))) + moving.points = box(10.0, 90.0, 20.0, 100.0) + r.update(listOf(0 to TilePolygon.from(moving))) + assertNotNull("移った先のタイルに出る", r.renderTile(TileRequest(x = 1, y = 0, z = 1))) + assertNull("元のタイルからは消える", r.renderTile(TileRequest(x = 0, y = 0, z = 1))) + } + + /** 取りやめられたタイルは空ではなく失敗にする */ + @Test + fun cancelledTileFailsInsteadOfComingBackEmpty() { + val r = renderer(PolygonState(points = box(0.0, 0.0, 10.0, 10.0), fillColor = blue)) + val thrown = + runCatching { r.renderTile(TileRequest(x = 0, y = 0, z = 0)) { true } }.exceptionOrNull() + assertTrue(thrown is PolygonTileRenderer.TileRenderCancelled) + } + + private fun decode(png: ByteArray): Bitmap = BitmapFactory.decodeByteArray(png, 0, png.size) +} diff --git a/src/androidTest/java/com/mapconductor/core/polygon/PolygonTilerDeviceTest.kt b/src/androidTest/java/com/mapconductor/core/polygon/PolygonTilerDeviceTest.kt new file mode 100644 index 0000000..3d5b30d --- /dev/null +++ b/src/androidTest/java/com/mapconductor/core/polygon/PolygonTilerDeviceTest.kt @@ -0,0 +1,337 @@ +package com.mapconductor.core.polygon + +import android.graphics.BitmapFactory +import androidx.compose.ui.graphics.Color +import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.features.GeoPointInterface +import com.mapconductor.core.tileserver.TileServerRegistry +import kotlinx.coroutines.delay +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import java.net.HttpURLConnection +import java.net.URL + +/** + * PolygonController と PolygonTiler の振り分け。js-sdk-core の PolygonController(tiler プロパティ)と同じ規則: + * タイルにしたポリゴンは PolygonManager に残し(タップ用、元の形)、レンダラには渡さない。 + * + * PolygonTileSet が本物のタイルサーバーに経路を作るので、端末で動かす。 + */ +@RunWith(AndroidJUnit4::class) +class PolygonTilerDeviceTest { + private fun p( + latitude: Double, + longitude: Double, + ): GeoPointInterface = GeoPoint.fromLatLong(latitude, longitude) + + /** 0.001 度角の区画を n 個、ボストンに並べる。 */ + private fun parcels( + n: Int, + fill: Color = Color(0xFF2563EB), + ): List = + List(n) { i -> + val lat = 42.30 + (i / 100) * 0.0012 + val lng = -71.10 + (i % 100) * 0.0012 + PolygonState( + points = listOf(p(lat, lng), p(lat, lng + 0.001), p(lat + 0.001, lng + 0.001), p(lat + 0.001, lng)), + id = "parcel-$i", + fillColor = fill, + ) + } + + private class Renderer : PolygonOverlayRendererInterface { + val onMap = mutableSetOf() + val added = mutableListOf() + val changed = mutableListOf() + val removed = mutableListOf() + + override suspend fun onAdd(data: List): List = + data.map { params -> + params.state.id.also { + onMap.add(it) + added.add(it) + } + } + + override suspend fun onChange(data: List>): List = + data.map { params -> params.current.state.id.also { changed.add(it) } } + + override suspend fun onRemove(data: List>) { + data.forEach { + onMap.remove(it.state.id) + removed.add(it.state.id) + } + } + + override suspend fun onPostProcess() {} + } + + private class Controller( + renderer: Renderer, + ) : PolygonController(PolygonManager(), renderer) + + private class Templates { + val seen = mutableListOf() + + fun last() = seen.lastOrNull() + } + + private fun controller(): Triple { + val renderer = Renderer() + val controller = Controller(renderer) + val templates = Templates() + controller.tiler = + PolygonTiler().apply { + onTemplate = { template, _ -> synchronized(templates) { templates.seen.add(template) } } + } + return Triple(controller, renderer, templates) + } + + /** しきい値を超えたらネイティブには何も渡さず、タップ用にマネージャへ残す */ + @Test + fun pastThresholdNothingGoesNative_andTapsStillHit() = + runBlocking { + val (controller, renderer, templates) = controller() + val states = parcels(2000) + controller.add(states) + assertTrue(renderer.onMap.isEmpty()) + assertEquals(2000, controller.polygonManager.allEntities().size) + assertNotNull(templates.last()) + // タップ判定は元の形で + assertEquals("parcel-101", controller.find(p(42.3017, -71.0983))?.state?.id) + assertNull(controller.find(p(42.3011, -71.0995))) + } + + /** しきい値を下回ったらネイティブに戻し、上回ったらネイティブから外す */ + @Test + fun crossingThresholdMovesPolygonsBetweenNativeAndTiles() = + runBlocking { + val (controller, renderer, templates) = controller() + controller.add(parcels(1999)) + assertEquals(1999, renderer.onMap.size) + assertNull(templates.last()) + + controller.add(parcels(2000)) + assertTrue("タイルへ移ったらネイティブから消す", renderer.onMap.isEmpty()) + assertEquals(2000, controller.polygonManager.allEntities().size) + assertNotNull(templates.last()) + + controller.add(parcels(10)) + assertEquals(10, renderer.onMap.size) + assertEquals("リストから消えたものは忘れる", 10, controller.polygonManager.allEntities().size) + assertNull(templates.last()) + } + + /** タイルのポリゴンのその場の変更は、版を上げたテンプレートで知らせる */ + @Test + fun inPlaceChangeOfTiledPolygonAnnouncesNewTemplate() = + runBlocking { + val (controller, renderer, templates) = controller() + val states = parcels(2000) + controller.add(states) + val before = templates.last()!! + states[5].fillColor = Color(0xFF16A34A) + controller.update(states[5]) + assertTrue(renderer.onMap.isEmpty()) + withTimeout(2000) { + while (synchronized(templates) { templates.last() } == before) delay(5) + } + assertTrue(templates.last()!! != before) + assertEquals( + Color(0xFF16A34A), + controller.polygonManager + .getEntity("parcel-5") + ?.state + ?.fillColor, + ) + } + + /** タイルはタイルサーバーから PNG で届き、何も無い場所は透明の 200 */ + @Test + fun tilesAreServedAsPng_andEmptyPlacesAsTransparent200() = + runBlocking { + val (controller, _, templates) = controller() + controller.add(parcels(2000)) + val template = templates.last()!! + // z14 で区画の並ぶ場所と、何も無い南半球 + val (x, y) = tileOf(42.31, -71.07, 14) + val drawn = get(template, 14, x, y) + assertEquals(200, drawn.first) + val bitmap = BitmapFactory.decodeByteArray(drawn.second, 0, drawn.second.size) + assertNotNull(bitmap) + var painted = 0 + for (py in 0 until bitmap.height step 4) { + for (px in 0 until bitmap.width step 4) { + if (bitmap.getPixel(px, py) ushr 24 != + 0 + ) { + painted++ + } + } + } + assertTrue("区画が描かれている: $painted", painted > 0) + val empty = get(template, 14, 100, 12000) + assertEquals(200, empty.first) + } + + /** clear でテンプレートを外し、タイル側のポリゴンも忘れる */ + @Test + fun clearRemovesTemplateAndForgetsTiledPolygons() = + runBlocking { + val (controller, _, templates) = controller() + controller.add(parcels(2000)) + controller.clear() + assertNull(templates.last()) + assertTrue(controller.polygonManager.allEntities().isEmpty()) + assertTrue(TileServerRegistry.get().isRunning()) + } + + // ── タイルにできなくなったポリゴン(geodesic・経度の幅 180° 以上・頂点 3 未満) ────── + // + // タイルにするかは add でだけ決めていた。タイルで描いているポリゴンをその場で + // geodesic=true にしたり、点を書き換えてタイルにできない形にしたりすると、update は + // タイルの経路に入ったまま canTile を見直さず、直線のままタイルに描き続けた。 + // js-sdk-core の PolygonTilingInPlace.test.mjs、ios-sdk-core の PolygonTilingInPlaceTests と同じ内容。 + + /** parcel-101 の中と、隣の parcel-102 の中 */ + private val inside101 = 42.3017 to -71.0983 + private val inside102 = 42.3017 to -71.0971 + + /** 混在リストでは geodesic だけネイティブ、タイルには描かれない */ + @Test + fun inAMixedListOnlyTheGeodesicOneGoesNative() = + runBlocking { + val (controller, renderer, templates) = controller() + val g = + PolygonState( + points = listOf(p(42.29, -71.10), p(42.29, -71.099), p(42.291, -71.099), p(42.291, -71.10)), + id = "g", + fillColor = Color(0xFFDC2626), + geodesic = true, + ) + controller.add(parcels(2000) + g) + assertEquals(setOf("g"), renderer.onMap) + val template = templates.last()!! + assertEquals("タイルには描かない", 0, alphaAt(template, 42.2905, -71.0995, 17)) + assertTrue("区画はタイルに描く", alphaAt(template, inside101.first, inside101.second, 17) > 0) + } + + private suspend fun movesToNative(change: (PolygonState) -> Unit): Triple> { + val (controller, renderer, templates) = controller() + // しきい値(2,000)より 1 つ多い。移った 1 つを除いても、渡し直したときに残りはタイルのまま。 + val states = parcels(2001) + controller.add(states) + assertTrue(renderer.onMap.isEmpty()) + val before = templates.last()!! + assertTrue(alphaAt(before, inside101.first, inside101.second, 17) > 0) + + change(states[101]) + controller.update(states[101]) + withTimeout(2000) { + while (synchronized(templates) { templates.last() } == before) delay(5) + } + + assertEquals("ネイティブで描く", listOf("parcel-101"), renderer.added) + assertEquals("parcel-101", controller.polygonManager.getEntity("parcel-101")?.polygon) + val after = templates.last()!! + assertEquals("タイルから消える", 0, alphaAt(after, inside101.first, inside101.second, 17)) + assertTrue("隣はタイルに残る", alphaAt(after, inside102.first, inside102.second, 17) > 0) + return Triple(controller, renderer, states) + } + + /** その場で geodesic=true にしたらネイティブへ移り、タイルから消える。タップは引き続き当たる */ + @Test + fun settingGeodesicInPlaceMovesItToNative() = + runBlocking { + val (controller, renderer, states) = movesToNative { it.geodesic = true } + + val hit = controller.find(p(inside101.first, inside101.second)) + assertEquals("parcel-101", hit?.state?.id) + assertEquals("parcel-101", hit?.polygon) + assertEquals("parcel-102", controller.find(p(inside102.first, inside102.second))?.state?.id) + + // その後のその場の変更はネイティブへ + states[101].fillColor = Color(0xFF16A34A) + controller.update(states[101]) + assertEquals(listOf("parcel-101"), renderer.changed) + + // 同じリストを渡し直しても、ネイティブのまま(足しも消しもしない) + controller.add(states) + assertEquals(listOf("parcel-101"), renderer.added) + assertTrue(renderer.removed.isEmpty()) + assertEquals(setOf("parcel-101"), renderer.onMap) + } + + /** その場で点を書き換えて経度の幅 180° 以上にしても同じ */ + @Test + fun pointsSpanningHalfTheWorldInPlaceMoveItToNative() = + runBlocking { + movesToNative { + it.points = listOf(p(42.3012, -71.0988), p(42.3012, -71.0978), p(42.3022, -71.0978), p(42.3022, 120.0)) + } + Unit + } + + /** その場で点を 3 未満にしても同じ */ + @Test + fun fewerThanThreePointsInPlaceMoveItToNative() = + runBlocking { + movesToNative { it.points = listOf(p(42.3012, -71.0988), p(42.3012, -71.0978)) } + Unit + } + + /** The alpha of the tile pixel at a coordinate. */ + private fun alphaAt( + template: String, + lat: Double, + lng: Double, + z: Int, + ): Int { + val (x, y) = tileOf(lat, lng, z) + val (code, bytes) = get(template, z, x, y) + assertEquals(200, code) + val bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size) ?: return 0 + val scale = 256.0 * (1 shl z) + val s = kotlin.math.sin(Math.toRadians(lat)) + val px = (lng + 180) / 360 * scale - x * 256 + val py = (0.5 - kotlin.math.ln((1 + s) / (1 - s)) / (4 * Math.PI)) * scale - y * 256 + val k = bitmap.width / 256.0 + return bitmap.getPixel((px * k).toInt(), (py * k).toInt()) ushr 24 + } + + private fun tileOf( + lat: Double, + lng: Double, + z: Int, + ): Pair { + val n = 1 shl z + val x = ((lng + 180) / 360 * n).toInt() + val s = kotlin.math.sin(Math.toRadians(lat)) + val y = ((0.5 - kotlin.math.ln((1 + s) / (1 - s)) / (4 * Math.PI)) * n).toInt() + return x to y + } + + private fun get( + template: String, + z: Int, + x: Int, + y: Int, + ): Pair { + val url = template.replace("{z}", "$z").replace("{x}", "$x").replace("{y}", "$y") + val connection = URL(url).openConnection() as HttpURLConnection + connection.useCaches = false + return try { + val code = connection.responseCode + code to connection.inputStream.use { it.readBytes() } + } finally { + connection.disconnect() + } + } +} diff --git a/src/androidTest/java/com/mapconductor/core/polyline/PolylineTileRendererDeviceTest.kt b/src/androidTest/java/com/mapconductor/core/polyline/PolylineTileRendererDeviceTest.kt new file mode 100644 index 0000000..029ca43 --- /dev/null +++ b/src/androidTest/java/com/mapconductor/core/polyline/PolylineTileRendererDeviceTest.kt @@ -0,0 +1,281 @@ +package com.mapconductor.core.polyline + +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.dp +import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.features.GeoPointInterface +import com.mapconductor.core.shapetile.ShapeTileRenderer +import com.mapconductor.core.tileserver.TileRequest +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNotSame +import org.junit.Assert.assertNull +import org.junit.Assert.assertSame +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import kotlin.math.PI +import kotlin.math.ln +import kotlin.math.sin +import android.graphics.Bitmap +import android.graphics.BitmapFactory +import kotlinx.coroutines.runBlocking + +/** + * ポリラインタイルの画素。tile-sw.js の「Shape tiles」節のポリラインと同じ描き方であることを固定する。 + * PolygonTileRendererDeviceTest と同じく、1 単位 = 1 画素(pixelScale = 1)で描かせる。 + * + * z0 のタイルは世界全体が 256 画素。経度 λ は x = (λ + 180) / 360 * 256、赤道は y = 128。 + * js-sdk-core の `PolylineTileRendering.test.mjs`、ios-sdk の `PolylineTileRendererTests` と 1 対 1。 + */ +@RunWith(AndroidJUnit4::class) +class PolylineTileRendererDeviceTest { + private val red = Color(0xFFFF0000) + private val blue = Color(0xFF0000FF) + private val green = Color(0xFF00FF00) + + private fun p( + latitude: Double, + longitude: Double, + ): GeoPointInterface = GeoPoint.fromLatLong(latitude, longitude) + + private fun renderer(vararg states: PolylineState) = + ShapeTileRenderer(tileSize = 256, pixelScale = { 1f }, painter = PolylineTilePainter).apply { + setItems(states.map(TilePolyline::from)) + } + + private fun alpha(pixel: Int) = pixel ushr 24 + + private fun rgb(pixel: Int) = pixel and 0xFFFFFF + + private fun centre(bitmap: Bitmap) = bitmap.getPixel(bitmap.width / 2, bitmap.height / 2) + + /** The rows of column [x] that are painted (alpha over half), top to bottom. */ + private fun paintedRows( + bitmap: Bitmap, + x: Int, + ): List = (0 until bitmap.height).filter { alpha(bitmap.getPixel(x, it)) > 0x80 } + + /** World y (in pixels of a 256 * 2^z world) of [lat]. */ + private fun worldY( + lat: Double, + z: Int, + ): Double { + val s = sin(lat * PI / 180) + return (0.5 - ln((1 + s) / (1 - s)) / (4 * PI)) * 256.0 * (1 shl z) + } + + /** 水平線は期待した行に、線幅ぶんの太さで出る */ + @Test + fun horizontalLineIsOnItsRowAsWideAsItsStroke() { + val bitmap = + renderer( + PolylineState(points = listOf(p(0.0, -90.0), p(0.0, 90.0)), strokeColor = red, strokeWidth = 4.dp), + ).renderBitmap(0, 0, 0)!! + // 赤道は y = 128。幅 4 なら 126..129 + assertEquals(listOf(126, 127, 128, 129), paintedRows(bitmap, 128)) + assertEquals(0xFF0000, rgb(bitmap.getPixel(128, 127))) + // 端は丸く、線幅の半分だけ先まで: 経度 -90 度は x = 64、その 2 画素手前まで + assertTrue(alpha(bitmap.getPixel(63, 128)) > 0x80) + assertEquals(0, alpha(bitmap.getPixel(60, 128))) + // 塗らない(線の外は透明) + assertEquals(0, alpha(bitmap.getPixel(128, 100))) + } + + /** タイルの境目にある線は、両側のタイルに同じ行・太さで切れ目なく出る */ + @Test + fun lineOnATileEdgeIsDrawnOnBothSidesWithoutAGap() { + // z1: 赤道は y 方向のタイルの境目(世界 512 画素の y = 256) + val r = + renderer( + PolylineState(points = listOf(p(0.0, -90.0), p(0.0, 90.0)), strokeColor = red, strokeWidth = 4.dp), + ) + val north = r.renderBitmap(0, 0, 1)!! + val south = r.renderBitmap(0, 1, 1)!! + // 経度 -45 度は z1 の x = 192 + assertEquals("北のタイルの下 2 行", listOf(254, 255), paintedRows(north, 192)) + assertEquals("南のタイルの上 2 行", listOf(0, 1), paintedRows(south, 192)) + // 東西のタイルの境目(経度 0 度)を横切っても、両側の端の列で同じ行 + val east = r.renderBitmap(1, 0, 1)!! + assertEquals(paintedRows(north, 255), paintedRows(east, 0)) + assertEquals(listOf(254, 255), paintedRows(east, 0)) + } + + /** 斜めの線もタイルの境目で切れない: 境目の両側の端の列で、塗った行がつながる */ + @Test + fun slantedLineContinuesAcrossTheTileEdge() { + val r = + renderer( + PolylineState(points = listOf(p(30.0, -20.0), p(10.0, 20.0)), strokeColor = blue, strokeWidth = 3.dp), + ) + // z2: 経度 0 度は x 方向のタイル 1 と 2 の境目 + val y = (worldY(20.0, 2) / 256).toInt() + val west = r.renderBitmap(1, y, 2)!! + val east = r.renderBitmap(2, y, 2)!! + val westRows = paintedRows(west, 255) + val eastRows = paintedRows(east, 0) + assertTrue(westRows.isNotEmpty() && eastRows.isNotEmpty()) + // 1 列ぶん右へ下がる線なので、重なるか 1 行ずれるだけ + assertTrue( + "$westRows / $eastRows", + westRows.first() <= eastRows.last() && eastRows.first() <= westRows.last() + 1, + ) + } + + /** ズームを変えても線幅(画素)は同じ */ + @Test + fun strokeKeepsItsWidthAcrossZooms() { + val r = + renderer( + PolylineState(points = listOf(p(20.0, -170.0), p(20.0, 170.0)), strokeColor = blue, strokeWidth = 4.dp), + ) + val widths = + (2..5).map { z -> + val y = (worldY(20.0, z) / 256).toInt() + val bitmap = r.renderBitmap(1, y, z)!! + paintedRows(bitmap, 128).size + } + assertEquals(listOf(4, 4, 4, 4), widths) + } + + /** 1 画素に満たない線は線幅の丸(点)になる */ + @Test + fun subPixelLineIsADotAsWideAsTheLine() { + val bitmap = + renderer( + PolylineState(points = listOf(p(0.0, 0.0), p(0.0, 0.001)), strokeColor = green, strokeWidth = 4.dp), + ).renderBitmap(0, 0, 0)!! + var painted = 0 + for (py in 120..136) { + for (px in 120..136) { + val pixel = bitmap.getPixel(px, py) + if (alpha(pixel) > 0x80) { + painted++ + assertEquals(0x00FF00, rgb(pixel)) + } + } + } + // 直径 4 の丸: 12 画素前後 + assertTrue("painted=$painted", painted in 8..16) + } + + /** zIndex の大きい線が上、同じなら後に渡した線が上 */ + @Test + fun higherZIndexIsOnTop_thenLaterInTheList() = + runBlocking { + val set = PolylineTileSet() + try { + val over = + PolylineState(points = listOf(p(-10.0, 0.0), p(10.0, 0.0)), strokeColor = red, strokeWidth = 6.dp, zIndex = 1) + val under = + PolylineState(points = listOf(p(0.0, -10.0), p(0.0, 10.0)), strokeColor = blue, strokeWidth = 6.dp, zIndex = 0) + set.setPolylines(listOf(over, under)) + // The set draws at the device's density: the crossing is the bitmap's centre. + assertEquals("zIndex 1 が上", 0xFF0000, rgb(centre(set.renderer.renderBitmap(0, 0, 0)!!))) + + val first = + PolylineState(points = listOf(p(-10.0, 0.0), p(10.0, 0.0)), strokeColor = red, strokeWidth = 6.dp) + val second = + PolylineState(points = listOf(p(0.0, -10.0), p(0.0, 10.0)), strokeColor = green, strokeWidth = 6.dp) + set.setPolylines(listOf(first, second)) + assertEquals("後に渡した線が上", 0x00FF00, rgb(centre(set.renderer.renderBitmap(0, 0, 0)!!))) + } finally { + set.dispose() + } + } + + /** 透明な線・幅 0 の線は描かない。何も無いタイルは null(空) */ + @Test + fun invisibleLinesDrawNothing_andEmptyTilesAreNull() { + val r = + renderer( + PolylineState( + points = listOf(p(10.0, 10.0), p(20.0, 20.0)), strokeColor = Color.Transparent, + strokeWidth = + 4 + .dp, + ), + PolylineState(points = listOf(p(10.0, 10.0), p(20.0, 30.0)), strokeColor = red, strokeWidth = 0.dp), + ) + // 北東のタイルにはあるが、見えないものだけ + assertNull(r.renderTile(TileRequest(x = 1, y = 0, z = 1))) + // 北西のタイルには何も無い + assertNull(r.renderTile(TileRequest(x = 0, y = 0, z = 1))) + } + + /** 色を変えたら、その線のタイルだけ描き直す(他はキャッシュ) */ + @Test + fun inPlaceChangeRedrawsOnlyTheTilesItTouches() { + val west = + PolylineState( + points = listOf(p(10.0, -100.0), p(20.0, -90.0)), strokeColor = blue, id = "west", + strokeWidth = + 3 + .dp, + ) + val east = + PolylineState( + points = listOf(p(10.0, 90.0), p(20.0, 100.0)), strokeColor = blue, id = "east", + strokeWidth = + 3 + .dp, + ) + val r = renderer(west, east) + val westTile = TileRequest(x = 0, y = 0, z = 1) + val eastTile = TileRequest(x = 1, y = 0, z = 1) + val westBefore = r.renderTile(westTile)!! + val eastBefore = r.renderTile(eastTile)!! + + west.strokeColor = green + r.update(listOf(0 to TilePolyline.from(west))) + + val westAfter = r.renderTile(westTile)!! + assertNotSame("変えた線のタイルは描き直す", westBefore, westAfter) + assertSame("触れていないタイルはキャッシュから返す", eastBefore, r.renderTile(eastTile)) + val decoded = BitmapFactory.decodeByteArray(westAfter, 0, westAfter.size) + // 線の中点(経度 -95 度、北緯 ~15 度)は z1 で x = 120 + val y = worldY(15.0, 1).toInt() + val mid = (y - 3..y + 3).map { decoded.getPixel(120, it) }.firstOrNull { alpha(it) > 0x80 } + assertNotNull(mid) + assertEquals(0x00FF00, rgb(mid!!)) + } + + /** 外した線(null)は、重なっていたタイルだけ描き直して消える */ + @Test + fun removedLineRedrawsOnlyItsTiles() { + val west = PolylineState(points = listOf(p(10.0, -100.0), p(20.0, -90.0)), strokeColor = blue, id = "west") + val east = PolylineState(points = listOf(p(10.0, 90.0), p(20.0, 100.0)), strokeColor = blue, id = "east") + val r = renderer(west, east) + assertNotNull(r.renderTile(TileRequest(x = 0, y = 0, z = 1))) + val eastBefore = r.renderTile(TileRequest(x = 1, y = 0, z = 1))!! + r.update(listOf(0 to null)) + assertNull(r.renderTile(TileRequest(x = 0, y = 0, z = 1))) + assertSame(eastBefore, r.renderTile(TileRequest(x = 1, y = 0, z = 1))) + } + + /** 太い線の色を変えたら、線幅ぶん隣のタイルにはみ出した所も描き直す */ + @Test + fun aChangeRedrawsTheNeighbourTheStrokeReachesInto() { + // z1 の北のタイルの下端に沿う太い線: 南のタイルの上端にもはみ出す + val line = + PolylineState(points = listOf(p(0.5, -90.0), p(0.5, -10.0)), strokeColor = blue, strokeWidth = 10.dp, id = "l") + val r = renderer(line) + val south = TileRequest(x = 0, y = 1, z = 1) + val before = r.renderTile(south)!! + line.strokeColor = red + r.update(listOf(0 to TilePolyline.from(line))) + val after = r.renderTile(south)!! + assertNotSame(before, after) + val decoded = BitmapFactory.decodeByteArray(after, 0, after.size) + assertEquals(0xFF0000, rgb(decoded.getPixel(192, 0))) + } + + /** 取りやめられたタイルは空ではなく失敗にする */ + @Test + fun cancelledTileFailsInsteadOfComingBackEmpty() { + val r = renderer(PolylineState(points = listOf(p(0.0, 0.0), p(10.0, 10.0)), strokeColor = blue)) + val thrown = runCatching { r.renderTile(TileRequest(x = 0, y = 0, z = 0)) { true } }.exceptionOrNull() + assertTrue(thrown is ShapeTileRenderer.TileRenderCancelled) + } +} diff --git a/src/androidTest/java/com/mapconductor/core/polyline/PolylineTilerDeviceTest.kt b/src/androidTest/java/com/mapconductor/core/polyline/PolylineTilerDeviceTest.kt new file mode 100644 index 0000000..894180b --- /dev/null +++ b/src/androidTest/java/com/mapconductor/core/polyline/PolylineTilerDeviceTest.kt @@ -0,0 +1,381 @@ +package com.mapconductor.core.polyline + +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.dp +import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.mapconductor.core.controller.BaseMapViewController +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.features.GeoPointInterface +import com.mapconductor.core.features.GeoRectBounds +import com.mapconductor.core.map.MapCameraPosition +import com.mapconductor.core.tileserver.TileServerRegistry +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import java.net.HttpURLConnection +import java.net.URL +import kotlin.math.ln +import kotlin.math.sin +import android.graphics.BitmapFactory +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout + +/** + * PolylineController と PolylineTiler の振り分け。PolygonTilerDeviceTest と同じ規則: + * タイルにした線は PolylineManager に残し(タップ用、元の点のまま)、レンダラには渡さない。 + * js-sdk-core の PolylineController(tiler)、ios-sdk-core の PolylineTilerTests と同じ内容。 + * + * PolylineTileSet が本物のタイルサーバーに経路を作るので、端末で動かす。 + */ +@RunWith(AndroidJUnit4::class) +class PolylineTilerDeviceTest { + private fun p( + latitude: Double, + longitude: Double, + ): GeoPointInterface = GeoPoint.fromLatLong(latitude, longitude) + + private val events = mutableListOf() + + /** 東西に 0.001 度の道を n 本、ボストンに並べる。 */ + private fun roads( + n: Int, + color: Color = Color(0xFF2563EB), + ): List = + List(n) { i -> + val lat = 42.30 + (i / 100) * 0.0012 + val lng = -71.10 + (i % 100) * 0.0012 + PolylineState( + points = listOf(p(lat, lng), p(lat, lng + 0.0005), p(lat, lng + 0.001)), + id = "road-$i", + strokeColor = color, + strokeWidth = 4.dp, + onAdded = { events += "onAdded:${it.id}" }, + ) + } + + private inner class Renderer : PolylineOverlayRendererInterface { + val onMap = mutableSetOf() + val added = mutableListOf() + val changed = mutableListOf() + val removed = mutableListOf() + + override suspend fun onAdd(data: List): List = + data.map { params -> + events += "native:${params.state.id}" + params.state.id.also { + onMap.add(it) + added.add(it) + } + } + + override suspend fun onChange( + data: List>, + ): List = + data.map { params -> + params.current.state.id + .also { changed.add(it) } + } + + override suspend fun onRemove(data: List>) { + data.forEach { + onMap.remove(it.state.id) + removed.add(it.state.id) + } + } + + override suspend fun onPostProcess() {} + } + + private class Controller( + renderer: PolylineOverlayRendererInterface, + ) : PolylineController(PolylineManager(), renderer) + + private class Templates { + val seen = mutableListOf() + + fun last() = synchronized(this) { seen.lastOrNull() } + } + + private fun controller( + options: PolylineTilingOptions = PolylineTilingOptions.Default, + ): Triple { + val renderer = Renderer() + val controller = Controller(renderer) + val templates = Templates() + controller.tiler = + PolylineTiler(options).apply { + onTemplate = { template, _ -> synchronized(templates) { templates.seen.add(template) } } + } + return Triple(controller, renderer, templates) + } + + /** z16 のボストン(タップの許容距離を画面の大きさで測るため)。 */ + private suspend fun Controller.atZoom16() = + onCameraChanged(MapCameraPosition(position = p(42.30, -71.10), zoom = 16.0)) + + /** しきい値を超えたらネイティブには何も渡さず、タップ用にマネージャへ残す */ + @Test + fun pastThresholdNothingGoesNative_andTapsStillHit() = + runBlocking { + val (controller, renderer, templates) = controller() + controller.atZoom16() + controller.add(roads(2000)) + assertTrue(renderer.onMap.isEmpty()) + assertEquals(2000, controller.polylineManager.allEntities().size) + assertNotNull(templates.last()) + // タップ判定は元の線で: road-101 は北緯 42.3012、経度 -71.0988..-71.0978 + val hit = controller.findWithClosestPoint(p(42.30125, -71.0983)) + assertEquals("road-101", hit?.entity?.state?.id) + assertEquals(42.3012, hit!!.closestPoint.latitude, 1e-7) + // 道と道の間(南北に 0.0012 度 ≒ 133 m 離れている)の真ん中は外れ + assertNull(controller.find(p(42.3018, -71.0983))) + } + + /** しきい値を下回ったらネイティブに戻し、上回ったらネイティブから外す */ + @Test + fun crossingThresholdMovesPolylinesBetweenNativeAndTiles() = + runBlocking { + val (controller, renderer, templates) = controller() + controller.add(roads(1999)) + assertEquals(1999, renderer.onMap.size) + assertNull(templates.last()) + + controller.add(roads(2000)) + assertTrue("タイルへ移ったらネイティブから消す", renderer.onMap.isEmpty()) + assertEquals(2000, controller.polylineManager.allEntities().size) + assertNotNull(templates.last()) + + controller.add(roads(10)) + assertEquals(10, renderer.onMap.size) + assertEquals("リストから消えたものは忘れる", 10, controller.polylineManager.allEntities().size) + assertNull(templates.last()) + } + + /** タイルの線のその場の変更は、版を上げたテンプレートで知らせる */ + @Test + fun inPlaceChangeOfTiledPolylineAnnouncesNewTemplate() = + runBlocking { + val (controller, renderer, templates) = controller() + val states = roads(2000) + controller.add(states) + val before = templates.last()!! + states[5].strokeColor = Color(0xFF16A34A) + controller.update(states[5]) + assertTrue(renderer.onMap.isEmpty()) + withTimeout(2000) { + while (templates.last() == before) delay(5) + } + assertTrue(templates.last()!! != before) + assertEquals( + Color(0xFF16A34A), + controller.polylineManager + .getEntity("road-5") + ?.state + ?.strokeColor, + ) + } + + /** タイルはタイルサーバーから PNG で届き、何も無い場所は透明の 200 */ + @Test + fun tilesAreServedAsPng_andEmptyPlacesAsTransparent200() = + runBlocking { + val (controller, _, templates) = controller() + controller.add(roads(2000)) + val template = templates.last()!! + assertTrue("版が入る: $template", Regex("""/polylines-\w+/256/\d+/\{z\}""").containsMatchIn(template)) + assertTrue(alphaAt(template, 42.3012, -71.0983, 17) > 0) + assertEquals("道と道の間", 0, alphaAt(template, 42.3018, -71.0983, 17)) + val empty = get(template, 14, 100, 12000) + assertEquals(200, empty.first) + } + + /** clear でテンプレートを外し、タイル側の線も忘れる */ + @Test + fun clearRemovesTemplateAndForgetsTiledPolylines() = + runBlocking { + val (controller, _, templates) = controller() + controller.add(roads(2000)) + controller.clear() + assertNull(templates.last()) + assertTrue(controller.polylineManager.allEntities().isEmpty()) + assertTrue(TileServerRegistry.get().isRunning()) + } + + /** 混在リストでは geodesic だけネイティブ、タイルには描かれない */ + @Test + fun inAMixedListOnlyTheGeodesicOneGoesNative() = + runBlocking { + val (controller, renderer, templates) = controller() + val g = + PolylineState( + points = listOf(p(42.2905, -71.10), p(42.2905, -71.099)), + id = "g", + strokeColor = Color(0xFFDC2626), + strokeWidth = 4.dp, + geodesic = true, + ) + controller.add(roads(2000) + g) + assertEquals(setOf("g"), renderer.onMap) + val template = templates.last()!! + assertEquals("タイルには描かない", 0, alphaAt(template, 42.2905, -71.0995, 17)) + assertTrue("道はタイルに描く", alphaAt(template, 42.3012, -71.0983, 17) > 0) + } + + /** その場で geodesic にしたらネイティブへ移り(add ではない)、タイルから消える。隣はタイルに残る */ + @Test + fun settingGeodesicInPlaceMovesItToNative() = + runBlocking { + val (controller, renderer, templates) = controller() + val states = roads(2001) + controller.add(states) + val before = templates.last()!! + assertTrue(alphaAt(before, 42.3012, -71.0983, 17) > 0) + + states[101].geodesic = true + controller.update(states[101]) + withTimeout(2000) { + while (templates.last() == before) delay(5) + } + assertEquals(listOf("road-101"), renderer.added) + assertEquals("road-101", controller.polylineManager.getEntity("road-101")?.polyline) + val after = templates.last()!! + assertEquals("タイルから消える", 0, alphaAt(after, 42.3012, -71.0983, 17)) + assertTrue("隣はタイルに残る", alphaAt(after, 42.3012, -71.0971, 17) > 0) + + // 同じリストを渡し直しても、ネイティブのまま(足しも消しもしない) + controller.add(states) + assertEquals(listOf("road-101"), renderer.added) + assertTrue(renderer.removed.isEmpty()) + } + + // ── onAdded と地図ごとの指定(PolylineOverlay 経由、本物の BaseMapViewController) ────── + + private class Driver( + val polylines: Controller, + ) : BaseMapViewController() { + override val holder get() = throw UnsupportedOperationException() + override val defaultCoroutine = CoroutineScope(Dispatchers.Unconfined) + override val mainCoroutine = defaultCoroutine + + init { + registerOverlayController(polylines) + } + + override fun moveCamera(position: MapCameraPosition) = Unit + + override fun animateCamera( + position: MapCameraPosition, + duration: Long, + ) = Unit + + override fun fitBounds( + bounds: GeoRectBounds, + padding: Int, + ) = Unit + + override suspend fun clearOverlays() = polylines.clear() + } + + private fun PolylineOverlay.show( + map: Driver, + states: List, + ) = runBlocking { render(states.associateBy { it.id }.toMutableMap(), map) } + + /** タイルで地図に載った線にも onAdded。その場の変更とネイティブへの移動では呼ばない */ + @Test + fun onAddedOnTheTilePath() { + // 4 本で 3 本以上ならタイル: 1 本がネイティブへ移っても、残りはタイルのまま + val (controller, renderer, _) = controller(PolylineTilingOptions(minPolylineCount = 3)) + val map = Driver(controller) + val overlay = PolylineOverlay(MutableStateFlow(mutableMapOf())) + val states = roads(4) + overlay.show(map, states) + assertEquals(listOf("onAdded:road-0", "onAdded:road-1", "onAdded:road-2", "onAdded:road-3"), events) + assertTrue(renderer.onMap.isEmpty()) + events.clear() + + states[0].strokeColor = Color.Red + runBlocking { map.updatePolyline(states[0]) } + states[1].geodesic = true + runBlocking { map.updatePolyline(states[1]) } + overlay.show(map, states) + assertEquals(listOf("native:road-1"), events) + controller.destroy() + } + + /** 地図ごとの指定(PolylineOverlay の tilingOptions)は、次に線を渡すときに効く */ + @Test + fun perMapOptionsApplyOnTheNextHandOver() { + val (controller, renderer, templates) = controller() + val map = Driver(controller) + val options = MutableStateFlow(PolylineTilingOptions.Disabled) + val overlay = PolylineOverlay(MutableStateFlow(mutableMapOf()), options) + val states = roads(2000) + + overlay.show(map, states) + assertEquals("Disabled: 全部ネイティブ", 2000, renderer.onMap.size) + assertNull(templates.last()) + + options.value = PolylineTilingOptions.Default + overlay.show(map, states) + assertTrue("Default: 全部タイル", renderer.onMap.isEmpty()) + assertNotNull(templates.last()) + assertEquals(PolylineTilingOptions.Default, controller.tiler?.options) + controller.destroy() + } + + /** The alpha of the tile pixel at a coordinate. */ + private fun alphaAt( + template: String, + lat: Double, + lng: Double, + z: Int, + ): Int { + val (x, y) = tileOf(lat, lng, z) + val (code, bytes) = get(template, z, x, y) + assertEquals(200, code) + val bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size) ?: return 0 + val scale = 256.0 * (1 shl z) + val s = sin(Math.toRadians(lat)) + val px = (lng + 180) / 360 * scale - x * 256 + val py = (0.5 - ln((1 + s) / (1 - s)) / (4 * Math.PI)) * scale - y * 256 + val k = bitmap.width / 256.0 + return bitmap.getPixel((px * k).toInt(), (py * k).toInt()) ushr 24 + } + + private fun tileOf( + lat: Double, + lng: Double, + z: Int, + ): Pair { + val n = 1 shl z + val x = ((lng + 180) / 360 * n).toInt() + val s = sin(Math.toRadians(lat)) + val y = ((0.5 - ln((1 + s) / (1 - s)) / (4 * Math.PI)) * n).toInt() + return x to y + } + + private fun get( + template: String, + z: Int, + x: Int, + y: Int, + ): Pair { + val url = template.replace("{z}", "$z").replace("{x}", "$x").replace("{y}", "$y") + val connection = URL(url).openConnection() as HttpURLConnection + connection.useCaches = false + return try { + val code = connection.responseCode + code to connection.inputStream.use { it.readBytes() } + } finally { + connection.disconnect() + } + } +} diff --git a/src/androidTest/java/com/mapconductor/core/shapetile/ShapeTileGpuDeviceTest.kt b/src/androidTest/java/com/mapconductor/core/shapetile/ShapeTileGpuDeviceTest.kt new file mode 100644 index 0000000..98793fa --- /dev/null +++ b/src/androidTest/java/com/mapconductor/core/shapetile/ShapeTileGpuDeviceTest.kt @@ -0,0 +1,274 @@ +package com.mapconductor.core.shapetile + +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.dp +import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.mapconductor.core.circle.CircleState +import com.mapconductor.core.circle.CircleTileFileStorage +import com.mapconductor.core.circle.CircleTilePainter +import com.mapconductor.core.circle.TileCircle +import com.mapconductor.core.circle.effectiveZIndex +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.features.GeoPointInterface +import com.mapconductor.core.polygon.PolygonState +import com.mapconductor.core.polygon.PolygonTilePainter +import com.mapconductor.core.polygon.TilePolygon +import com.mapconductor.core.polyline.PolylineState +import com.mapconductor.core.polyline.PolylineTilePainter +import com.mapconductor.core.polyline.TilePolyline +import org.junit.After +import org.junit.Before +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import org.junit.runner.RunWith +import kotlin.math.abs +import kotlin.math.max +import android.graphics.Bitmap + +/** + * 図形タイルを GPU([GlShapeRasterizer])と Canvas で描き、同じ絵になることを確かめる。 + * + * GPU は MSAA、Canvas は Skia のアンチエイリアスなので、縁の画素は 1 段ずれる。見るのは、縁を + * 除いた所が一致すること。とくに食い違いやすい所: nonzero の塗り(穴)、半透明の線の継ぎ目と + * 自己交差(2 度塗りしない)、丸い角と端、1 点に縮む図形、渡した順の重なり、128 角形で描く円。 + * ios-sdk-core の `MetalShapeRasterizerTests` と `MetalPathRasterizerTests` に対応する。 + */ +@RunWith(AndroidJUnit4::class) +class ShapeTileGpuDeviceTest { + @get:Rule + val temporary = TemporaryFolder() + + @Before + fun drawEveryKindOnTheGpu() { + // Polygons and polylines are drawn on the canvas by default; turn them on + // here so that their GPU path is compared too. + ShapeTileRenderer.gpuPolygonsAndLines = true + } + + @After + fun restore() { + ShapeTileRenderer.useGpu = true + ShapeTileRenderer.gpuPolygonsAndLines = false + } + + private fun p( + latitude: Double, + longitude: Double, + ): GeoPointInterface = GeoPoint.fromLatLong(latitude, longitude) + + /** 同じタイルを GPU と Canvas で描く。 */ + private fun both( + renderer: () -> ShapeTileRenderer, + x: Int, + y: Int, + z: Int, + ratio: Int = 1, + ): Pair { + assertTrue("GLES 3 が無い", GlShapeRasterizer.isAvailable) + ShapeTileRenderer.useGpu = true + val gpu = renderer().renderBitmap(x, y, z, ratio)!! + ShapeTileRenderer.useGpu = false + val cpu = renderer().renderBitmap(x, y, z, ratio)!! + ShapeTileRenderer.useGpu = true + return gpu to cpu + } + + /** 画素の何割が、どれかのチャンネルで [tolerance] を超えて違うか。 */ + private fun mismatch( + a: Bitmap, + b: Bitmap, + tolerance: Int, + ): Double { + assertEquals(a.width, b.width) + val pa = IntArray(a.width * a.height).also { a.getPixels(it, 0, a.width, 0, 0, a.width, a.height) } + val pb = IntArray(b.width * b.height).also { b.getPixels(it, 0, b.width, 0, 0, b.width, b.height) } + var bad = 0 + for (i in pa.indices) { + var d = 0 + for (shift in intArrayOf(0, 8, 16, 24)) d = max(d, abs(((pa[i] ushr shift) and 0xFF) - ((pb[i] ushr shift) and 0xFF))) + if (d > tolerance) bad++ + } + return bad.toDouble() / pa.size + } + + private fun polygons(states: List) = + ShapeTileRenderer(tileSize = 256, pixelScale = { 1f }, painter = PolygonTilePainter).apply { + setItems(states.map(TilePolygon::from)) + } + + private fun polylines(states: List) = + ShapeTileRenderer(tileSize = 256, pixelScale = { 1f }, painter = PolylineTilePainter).apply { + setItems(states.map(TilePolyline::from)) + } + + private fun circles(states: List) = + ShapeTileRenderer(tileSize = 256, pixelScale = { 1f }, painter = CircleTilePainter).apply { + setItems(states.sortedBy(::effectiveZIndex).map(TileCircle::from)) + } + + private fun box( + south: Double, + west: Double, + north: Double, + east: Double, + ) = listOf(p(south, west), p(south, east), p(north, east), p(north, west)) + + private val colors = listOf(Color.Red, Color.Blue, Color.Green, Color(0xFFFF8800), Color(0xFF8800FF)) + + /** 穴と枠線。穴は抜け、枠線は外周だけ。 */ + @Test + fun polygonWithHolesMatchesTheCanvas() { + val state = + PolygonState( + points = box(-60.0, -120.0, 60.0, 120.0), + holes = listOf(box(-30.0, -80.0, 20.0, 0.0), box(-10.0, 20.0, 40.0, 90.0)), + fillColor = Color.Blue.copy(alpha = 0.6f), + strokeColor = Color.Red, + strokeWidth = 3.dp, + ) + val (gpu, cpu) = both({ polygons(listOf(state)) }, 0, 0, 0) + assertEquals(0, gpu.getPixel(80, 128) ushr 24) + assertTrue(mismatch(gpu, cpu, 48) < 0.02) + } + + /** 半透明のポリゴンが重なる。渡した順に重なる。 */ + @Test + fun translucentPolygonsStackInOrder() { + val states = + (0 until 60).map { i -> + val lat = -60.0 + (i * 37 % 110) + val lng = -150.0 + (i * 53 % 280) + PolygonState( + points = listOf(p(lat, lng), p(lat + 10, lng + 25), p(lat + 25, lng + 5)), + fillColor = colors[i % 5].copy(alpha = 0.5f), + strokeColor = colors[(i + 2) % 5].copy(alpha = 0.7f), + strokeWidth = (1 + i % 3).dp, + ) + } + val (gpu, cpu) = both({ polygons(states) }, 0, 0, 0) + assertTrue(mismatch(gpu, cpu, 48) < 0.03) + } + + /** 半透明の太い線が自分と交差する。交差も継ぎ目も 1 度だけ塗る。 */ + @Test + fun translucentSelfCrossingLineIsPaintedOnce() { + val line = + PolylineState( + points = listOf(p(0.0, -140.0), p(0.0, 100.0), p(50.0, -60.0), p(-60.0, 0.0), p(60.0, 0.0)), + strokeColor = Color.Red.copy(alpha = 0.5f), + strokeWidth = 12.dp, + ) + val (gpu, cpu) = both({ polylines(listOf(line)) }, 0, 0, 0) + val crossing = gpu.getPixel(128, 128) ushr 24 + assertTrue("交差は 1 度だけ: alpha=$crossing", abs(crossing - 128) <= 3) + assertTrue(mismatch(gpu, cpu, 48) < 0.02) + } + + /** 多くの線(255 本を超えて番号が一巡する)。Retina のタイル。 */ + @Test + fun manyLinesMatchTheCanvasOnRetinaTiles() { + val lines = + (0 until 600).map { i -> + val lat = -70.0 + (i * 13 % 140) + val lng = -170.0 + (i * 29 % 300) + PolylineState( + points = listOf(p(lat, lng), p(lat + 4, lng + 20), p(lat - 6, lng + 40), p(lat + 2, lng + 70)), + strokeColor = colors[i % 5].copy(alpha = if (i % 3 == 0) 0.6f else 1f), + strokeWidth = (1 + i % 5).dp, + ) + } + val (gpu, cpu) = both({ polylines(lines) }, 0, 0, 0, ratio = 2) + assertEquals(512, gpu.width) + assertTrue(mismatch(gpu, cpu, 48) < 0.04) + } + + /** 街の円(重なり・縁・半透明)。 */ + @Test + fun cityCirclesMatchTheCanvas() { + val states = + (0 until 400).map { i -> + CircleState( + center = p(42.30 + (i * 37 % 100) / 1000.0, -71.10 + (i * 53 % 100) / 1000.0), + radiusMeters = 20.0 + i * 7 % 300, + fillColor = colors[i % 5].copy(alpha = 0.3f + (i % 7) / 10f), + strokeColor = colors[(i + 1) % 5].copy(alpha = 0.8f), + strokeWidth = (1 + i % 3).dp, + ) + } + // ボストンを含む z13 のタイル。 + val (gpu, cpu) = both({ circles(states) }, 2479, 3030, 13) + assertTrue(mismatch(gpu, cpu, 48) < 0.03) + } + + /** 引いたズーム: 多くが 1 点。1 画素に重なった円は最後の 1 つ。 */ + @Test + fun zoomedOutCircleDotsMatchTheCanvas() { + val states = + (0 until 20_000).map { i -> + CircleState( + center = p(30.0 + (i * 7919 % 2000) / 100.0, -120.0 + (i * 104729 % 5000) / 100.0), + radiusMeters = 100.0 + i % 700, + fillColor = colors[i % 5].copy(alpha = 0.65f), + strokeColor = colors[i % 5].copy(alpha = 0.35f), + strokeWidth = 0.5.dp, + ) + } + val (gpu, cpu) = both({ circles(states) }, 0, 0, 1) + assertTrue(mismatch(gpu, cpu, 48) < 0.03) + } + + /** 高緯度の大きな円は 128 角形(ポリゴンと同じ道)で描く。 */ + @Test + fun bentCirclesAreDrawnAsTheirPolygon() { + val states = + listOf( + CircleState(center = p(68.0, 20.0), radiusMeters = 900_000.0, fillColor = Color.Blue.copy(alpha = 0.5f), strokeColor = Color.Red, strokeWidth = 3.dp), + CircleState(center = p(10.0, -40.0), radiusMeters = 50_000.0, fillColor = Color.Green, strokeColor = Color.Black, strokeWidth = 1.dp), + ) + val (gpu, cpu) = both({ circles(states) }, 0, 0, 0) + assertTrue(mismatch(gpu, cpu, 48) < 0.02) + } + + /** + * 全国規模の集合はファイルに置かれ、GPU は記録をバイト列から直接読む + * ([CircleTilePainter.recordAll])。1 つずつ読む Canvas と同じ絵になる。 + */ + @Test + fun fileBackedCirclesMatchTheCanvas() { + val states = + (0 until 30_000).map { i -> + CircleState( + center = p(30.0 + (i * 7919 % 2000) / 100.0, -120.0 + (i * 104729 % 5000) / 100.0), + radiusMeters = 100.0 + i % 9000, + fillColor = colors[i % 5].copy(alpha = 0.65f), + strokeColor = colors[(i + 1) % 5].copy(alpha = 0.6f), + strokeWidth = (i % 3).dp, + ) + }.sortedBy(::effectiveZIndex).map(TileCircle::from) + fun renderer() = + ShapeTileRenderer(tileSize = 256, pixelScale = { 1f }, painter = CircleTilePainter).apply { + setStorage(CircleTileFileStorage.create(temporary.newFolder(), states.size, { states[it] })) + } + for ((z, x, y) in listOf(Triple(1, 0, 0), Triple(4, 3, 6), Triple(6, 12, 25))) { + val (gpu, cpu) = both(::renderer, x, y, z) + assertTrue("z=$z", mismatch(gpu, cpu, 48) < 0.03) + } + // Stored by place: the GPU reads them in storage order and must still draw + // in list order, the same picture as the canvas and as index order. + val order = StorageOrder.sortedBy(states.size) { StorageOrder.mortonCellKey(states[it]!!.latitude, states[it]!!.longitude) } + fun byPlace() = + ShapeTileRenderer(tileSize = 256, pixelScale = { 1f }, painter = CircleTilePainter).apply { + setStorage(CircleTileFileStorage.create(temporary.newFolder(), states.size, { states[it] }, order = order)) + } + for ((z, x, y) in listOf(Triple(1, 0, 0), Triple(4, 3, 6), Triple(6, 12, 25))) { + val (gpu, cpu) = both(::byPlace, x, y, z) + assertTrue("by place z=$z", mismatch(gpu, cpu, 48) < 0.03) + ShapeTileRenderer.useGpu = true + val plain = renderer().renderBitmap(x, y, z, 1)!! + assertEquals("by place z=$z: the same tile as index order", 0.0, mismatch(gpu, plain, 0), 0.0) + } + } +} diff --git a/src/androidTest/java/com/mapconductor/core/tileserver/LocalTileServerCancellationTest.kt b/src/androidTest/java/com/mapconductor/core/tileserver/LocalTileServerCancellationTest.kt new file mode 100644 index 0000000..869a1af --- /dev/null +++ b/src/androidTest/java/com/mapconductor/core/tileserver/LocalTileServerCancellationTest.kt @@ -0,0 +1,241 @@ +package com.mapconductor.core.tileserver + +import androidx.test.ext.junit.runners.AndroidJUnit4 +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import java.io.InputStream +import java.net.Socket +import java.net.URI +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicInteger + +/** + * The local server has to tell a map the truth about why it has no tile. + * + * "Not found" is a permanent answer, and a map that believes it leaves the + * area showing whatever older zoom it still has -- which is what a patchwork + * of two zoom levels on one screen looks like. A request the map itself + * abandoned is not a missing tile and must not be answered as one. + */ +@RunWith(AndroidJUnit4::class) +class LocalTileServerCancellationTest { + private val routeId = "cancellation-test" + private lateinit var server: LocalTileServer + + /** A one-pixel PNG, enough for the server to have something to send. */ + private val png = + byteArrayOf( + 0x89.toByte(), 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, + 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52, + 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, + 0x08, 0x06, 0x00, 0x00, 0x00, 0x1F, 0x15, 0xC4.toByte(), + 0x89.toByte(), 0x00, 0x00, 0x00, 0x0A, 0x49, 0x44, 0x41, + 0x54, 0x78, 0x9C.toByte(), 0x63, 0x00, 0x01, 0x00, 0x00, + 0x05, 0x00, 0x01, 0x0D, 0x0A, 0x2D, 0xB4.toByte(), 0x00, + 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE.toByte(), + 0x42, 0x60, 0x82.toByte(), + ) + + private class SlowProvider( + private val png: ByteArray, + private val started: CountDownLatch, + ) : TileProviderInterface { + val cancelled = AtomicInteger() + + override fun renderTile(request: TileRequest): ByteArray = png + + override fun renderTile( + request: TileRequest, + isCancelled: () -> Boolean, + ): ByteArray? { + started.countDown() + // Long enough for the caller to give up while this "renders". + repeat(40) { + Thread.sleep(50) + if (isCancelled()) { + cancelled.incrementAndGet() + return null + } + } + return png + } + } + + @Before + fun setUp() { + server = TileServerRegistry.get() + } + + @After + fun tearDown() { + server.unregister(routeId) + } + + private fun tileUrl(z: Int): URI { + val template = + server + .urlTemplate(routeId, 512) + .replace("{z}", "$z") + .replace("{x}", "0") + .replace("{y}", "0") + return URI(template) + } + + /** + * One response, read as bytes. + * + * A tile body is a PNG, and a character reader turns bytes into however + * many characters they happen to decode to -- which is not the number the + * Content-Length promised, so the next read waits forever for a byte that + * has already arrived. + */ + private class Response( + val status: String, + val body: ByteArray, + ) + + private fun readResponse(input: InputStream): Response? { + val head = StringBuilder() + while (!head.endsWith("\r\n\r\n")) { + val byte = input.read() + if (byte == -1) return null + head.append(byte.toChar()) + } + val lines = head.toString().split("\r\n") + val length = + lines + .firstOrNull { it.startsWith("Content-Length:", ignoreCase = true) } + ?.substringAfter(':') + ?.trim() + ?.toIntOrNull() + ?: 0 + val body = ByteArray(length) + var read = 0 + while (read < length) { + val n = input.read(body, read, length - read) + if (n <= 0) break + read += n + } + return Response(lines.first(), body.copyOf(read)) + } + + private fun statusOf(url: URI): String { + Socket(url.host, url.port).use { socket -> + socket.soTimeout = 15_000 + socket.getOutputStream().write( + "GET ${url.path} HTTP/1.1\r\nHost: ${url.host}\r\nConnection: close\r\n\r\n".toByteArray(), + ) + socket.getOutputStream().flush() + return readResponse(socket.getInputStream())?.status ?: "" + } + } + + /** + * A request the client walks away from must not come back as 404. There is + * nobody left to read the answer, so the only thing that matters is what + * the server decides the tile *is* -- and it is not missing. + */ + @Test + fun aTileTheClientAbandonedIsNotReportedMissing() { + val started = CountDownLatch(1) + val provider = SlowProvider(png, started) + server.register(routeId, provider) + + val url = tileUrl(10) + val socket = Socket(url.host, url.port) + socket.getOutputStream().write( + "GET ${url.path} HTTP/1.1\r\nHost: ${url.host}\r\n\r\n".toByteArray(), + ) + socket.getOutputStream().flush() + assertTrue("the render never started", started.await(10, TimeUnit.SECONDS)) + socket.close() + + // The provider should notice and give up rather than draw a tile + // nobody is waiting for. + val deadline = System.currentTimeMillis() + 10_000 + while (provider.cancelled.get() == 0 && System.currentTimeMillis() < deadline) { + Thread.sleep(50) + } + assertEquals("the abandoned render was not cancelled", 1, provider.cancelled.get()) + + // And the tile is still perfectly available to whoever asks next. + assertTrue(statusOf(tileUrl(11)).contains("200")) + } + + /** + * The liveness check reads from the very stream the request parser reads, + * so it has to put back whatever it takes. Two requests down one + * connection is where that goes wrong. + */ + @Test + fun keepAliveStillWorksAlongsideTheLivenessCheck() { + server.register( + routeId, + object : TileProviderInterface { + override fun renderTile(request: TileRequest): ByteArray = png + }, + ) + + val url = tileUrl(10) + Socket(url.host, url.port).use { socket -> + socket.soTimeout = 10_000 + val out = socket.getOutputStream() + val input = socket.getInputStream() + + repeat(2) { index -> + val path = url.path.replace("/512/10/", "/512/1$index/") + out.write("GET $path HTTP/1.1\r\nHost: ${url.host}\r\n\r\n".toByteArray()) + out.flush() + + val response = readResponse(input) + assertTrue("request $index got nothing", response != null) + assertTrue("request $index got ${response!!.status}", response.status.contains("200")) + assertEquals("request $index body", png.size, response.body.size) + } + } + } + + @Test + fun frequentCancellationChecksDoNotBecomeSocketTimeoutWaits() { + val elapsed = java.util.concurrent.atomic.AtomicLong() + server.register(routeId, object : TileProviderInterface { + override fun renderTile(request: TileRequest): ByteArray = png + override fun renderTile(request: TileRequest, isCancelled: () -> Boolean): ByteArray { + val began = System.nanoTime() + repeat(10_000) { assertTrue("live client was cancelled", !isCancelled()) } + elapsed.set((System.nanoTime() - began) / 1_000_000) + return png + } + }) + assertTrue(statusOf(tileUrl(10)).contains("200")) + assertTrue("10k checks took ${elapsed.get()}ms", elapsed.get() < 1500) + } + + @Test + fun idleKeepAliveConnectionsDoNotStarveNewTiles() { + server.register(routeId, object : TileProviderInterface { + override fun renderTile(request: TileRequest): ByteArray = png + }) + val url = tileUrl(10) + val idle = mutableListOf() + try { + repeat(8) { + val socket = Socket(url.host, url.port) + idle.add(socket) + socket.soTimeout = 10_000 + socket.getOutputStream().write("GET ${url.path} HTTP/1.1\r\nHost: ${url.host}\r\n\r\n".toByteArray()) + socket.getOutputStream().flush() + assertTrue(readResponse(socket.getInputStream())!!.status.contains("200")) + } + val began = System.nanoTime() + assertTrue(statusOf(url).contains("200")) + val elapsed = (System.nanoTime() - began) / 1_000_000 + assertTrue("new tile waited ${elapsed}ms behind idle connections", elapsed < 1500) + } finally { idle.forEach { it.close() } } + } +} diff --git a/src/androidTest/java/com/mapconductor/core/tileserver/LocalTileServerSemanticsTest.kt b/src/androidTest/java/com/mapconductor/core/tileserver/LocalTileServerSemanticsTest.kt new file mode 100644 index 0000000..1fff025 --- /dev/null +++ b/src/androidTest/java/com/mapconductor/core/tileserver/LocalTileServerSemanticsTest.kt @@ -0,0 +1,161 @@ +package com.mapconductor.core.tileserver + +import androidx.test.ext.junit.runners.AndroidJUnit4 +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.io.InputStream +import java.net.Socket +import java.net.URI +import android.graphics.BitmapFactory + +/** + * What the server answers when a provider has no tile to give. + * + * The three answers mean different things to a map SDK, and mixing them up + * shows on screen: a 404 is remembered as permanent, so a transiently empty + * tile answered with it becomes a hole that is never asked about again, with + * the neighbours' overhang cut off at its edge. Empty gets a transparent + * picture, a thrown render gets a retryable 503, and 404 is reserved for + * requests that name nothing. The iOS LocalTileServer answers the same way. + */ +@RunWith(AndroidJUnit4::class) +class LocalTileServerSemanticsTest { + private val routeId = "semantics-test" + private lateinit var server: LocalTileServer + + @Before + fun setUp() { + server = TileServerRegistry.get() + } + + @After + fun tearDown() { + server.unregister(routeId) + } + + private class Response( + val status: String, + val headers: Map, + val body: ByteArray, + ) + + // Bytes, not a character reader: a PNG body decoded as characters no + // longer matches its Content-Length. Same shape as the reader in + // LocalTileServerCancellationTest. + private fun readResponse(input: InputStream): Response? { + val head = StringBuilder() + while (!head.endsWith("\r\n\r\n")) { + val byte = input.read() + if (byte == -1) return null + head.append(byte.toChar()) + } + val lines = head.toString().split("\r\n") + val headers = HashMap() + for (line in lines.drop(1)) { + val at = line.indexOf(':') + if (at > 0) headers[line.substring(0, at).trim().lowercase()] = line.substring(at + 1).trim() + } + val length = headers["content-length"]?.toIntOrNull() ?: 0 + val body = ByteArray(length) + var read = 0 + while (read < length) { + val n = input.read(body, read, length - read) + if (n <= 0) break + read += n + } + return Response(lines.first(), headers, body.copyOf(read)) + } + + private fun fetch(url: URI): Response { + Socket(url.host, url.port).use { socket -> + socket.soTimeout = 15_000 + socket.getOutputStream().write( + "GET ${url.path} HTTP/1.1\r\nHost: ${url.host}\r\nConnection: close\r\n\r\n".toByteArray(), + ) + socket.getOutputStream().flush() + val response = readResponse(socket.getInputStream()) + assertNotNull("no response at all", response) + return response!! + } + } + + private fun tileUrl( + z: Int, + route: String = routeId, + ): URI { + val template = + server + .urlTemplate(route, 512) + .replace("{z}", "$z") + .replace("{x}", "0") + .replace("{y}", "0") + return URI(template) + } + + /** A route nobody registered names nothing; only that earns a 404. */ + @Test + fun anUnknownRouteIs404() { + assertTrue(fetch(tileUrl(10, route = "no-such-route")).status.contains("404")) + } + + /** An empty spot is a real answer: a transparent tile, not a 404. */ + @Test + fun anEmptyTileIsATransparentPicture() { + server.register( + routeId, + object : TileProviderInterface { + override fun renderTile(request: TileRequest): ByteArray? = null + }, + ) + val response = fetch(tileUrl(10)) + assertTrue("got ${response.status}", response.status.contains("200")) + val bitmap = BitmapFactory.decodeByteArray(response.body, 0, response.body.size) + assertNotNull("body is not a decodable PNG", bitmap) + assertEquals(512, bitmap.width) + assertEquals(512, bitmap.height) + assertEquals("corner pixel", 0, bitmap.getPixel(0, 0)) + assertEquals("centre pixel", 0, bitmap.getPixel(256, 256)) + } + + /** A retina path gets a transparent tile at the density it asked for. */ + @Test + fun anEmptyRetinaTileMatchesItsDensity() { + server.register( + routeId, + object : TileProviderInterface { + override fun renderTile(request: TileRequest): ByteArray? = null + }, + ) + val base = tileUrl(10) + val response = fetch(URI(base.toString().replace("0.png", "0@2x.png"))) + val bitmap = BitmapFactory.decodeByteArray(response.body, 0, response.body.size) + assertNotNull(bitmap) + assertEquals(1024, bitmap.width) + } + + /** A provider that throws gets a 503 the map knows to retry — never 404. */ + @Test + fun aRenderFailureIs503WithRetryAfter() { + server.register( + routeId, + object : TileProviderInterface { + override fun renderTile(request: TileRequest): ByteArray = throw IllegalStateException("boom") + }, + ) + val response = fetch(tileUrl(10)) + assertTrue("got ${response.status}", response.status.contains("503")) + assertEquals("1", response.headers["retry-after"]) + assertTrue( + "cache-control was ${response.headers["cache-control"]}", + response.headers["cache-control"]?.contains("no-store") == true, + ) + // And the connection is still fine for the next request. + server.unregister(routeId) + assertTrue(fetch(tileUrl(11)).status.contains("404")) + } +} diff --git a/src/androidTest/java/com/mapconductor/core/tileserver/TilePngEncoderTest.kt b/src/androidTest/java/com/mapconductor/core/tileserver/TilePngEncoderTest.kt new file mode 100644 index 0000000..a03779a --- /dev/null +++ b/src/androidTest/java/com/mapconductor/core/tileserver/TilePngEncoderTest.kt @@ -0,0 +1,223 @@ +package com.mapconductor.core.tileserver + +import androidx.test.ext.junit.runners.AndroidJUnit4 +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.io.ByteArrayOutputStream +import java.nio.ByteBuffer +import java.nio.ByteOrder +import kotlin.math.abs +import android.graphics.Bitmap +import android.graphics.BitmapFactory +import android.graphics.Color + +/** + * On-device checks for the Rust PNG encoder. + * + * Instrumented rather than local because the thing most likely to be wrong is + * not the Kotlin: it is whether `libtile_png_jni.so` is packaged for the + * device's ABI at all. A JVM test would pass with no native library present, + * since every failure path here deliberately returns null. + */ +@RunWith(AndroidJUnit4::class) +class TilePngEncoderTest { + /** + * The whole point of putting the library in the core: it has to load in an + * ordinary consumer process, with no help from the caller. + * + * If this fails, everything below it passes vacuously — the encoder would + * return null and the platform fallback would quietly cover for it. + */ + @Test + fun libraryLoadsOnThisDevice() { + assertTrue( + "libtile_png_jni.so did not load — check jniLibs carries this device's ABI", + TilePngEncoder.isAvailable, + ) + } + + /** + * Opaque pixels, where premultiplication is the identity, so the round trip + * has to be exact. This is the test that catches a swapped R and B: the + * classic way a fast encoder produces a plausible-looking wrong image. + */ + @Test + fun opaquePixelsSurviveExactly() { + val source = opaqueFixture() + val png = TilePngEncoder.encode(source) + assertNotNull("encoder declined an ARGB_8888 bitmap", png) + + val decoded = decode(png!!) + assertEquals(source.width, decoded.width) + assertEquals(source.height, decoded.height) + for (y in 0 until source.height) { + for (x in 0 until source.width) { + assertEquals( + "pixel ($x,$y)", + source.getPixel(x, y), + decoded.getPixel(x, y), + ) + } + } + } + + /** + * Partly transparent pixels against the encoder this one replaces. + * + * Both paths undo the same premultiplication, so they may round a channel + * differently, but they must not disagree about the image. Alpha carries no + * rounding at all and is compared exactly; colour is allowed one step, which + * is what integer un-premultiplication can legitimately cost. + */ + @Test + fun transparentPixelsAgreeWithBitmapCompress() { + val source = translucentFixture() + + val rust = decode(TilePngEncoder.encode(source)!!) + val platform = decode(compress(source)) + + var worstColourStep = 0 + for (y in 0 until source.height) { + for (x in 0 until source.width) { + val a = rust.getPixel(x, y) + val b = platform.getPixel(x, y) + assertEquals("alpha at ($x,$y)", Color.alpha(b), Color.alpha(a)) + // Fully transparent pixels carry no recoverable colour: both + // encoders are free to write anything under alpha 0. + if (Color.alpha(b) == 0) continue + val step = + maxOf( + abs(Color.red(a) - Color.red(b)), + abs(Color.green(a) - Color.green(b)), + abs(Color.blue(a) - Color.blue(b)), + ) + assertTrue("colour at ($x,$y) differs by $step", step <= 1) + worstColourStep = maxOf(worstColourStep, step) + } + } + println("TILEPNG translucent round trip: worst colour step $worstColourStep") + } + + /** + * A bitmap the encoder cannot read has to come back as null, because the + * caller's fallback is the only thing standing between that and a blank + * tile. RGB_565 has a different byte layout entirely. + */ + @Test + fun unsupportedConfigDeclinesInsteadOfGuessing() { + val source = opaqueFixture().copy(Bitmap.Config.RGB_565, false) + assertNull(TilePngEncoder.encode(source)) + } + + /** A heap buffer's address does not survive the JNI crossing. */ + @Test + fun indirectBufferIsRefused() { + val heap = ByteBuffer.allocate(TILE * TILE * 4).order(ByteOrder.nativeOrder()) + assertNull(TilePngEncoder.encode(heap, TILE, TILE, premultiplied = false)) + } + + /** + * Not an assertion about speed — the numbers vary with the device and + * nothing here should fail because a phone was busy. It prints the + * comparison so the reason this encoder exists stays visible in the log. + * + * Deliberately run on noise rather than on the smooth fixtures above. + * Synthetic tiles mislead badly here: a flat colour under an alpha ramp + * compresses to a couple of kilobytes, which flatters `compress` on size + * and starves it of the work this encoder is meant to save. Noise is not + * realistic either, only wrong in the opposite direction — the honest + * comparison, on tiles the marker renderer actually produced, is + * `MarkerTileCostTest` in android-vectortile. + */ + @Test + fun reportsCostAgainstThePlatformEncoder() { + val source = noiseFixture() + + val platformSamples = ArrayList(REPEATS) + var platformBytes = 0 + repeat(REPEATS) { + val started = System.nanoTime() + platformBytes = compress(source).size + platformSamples.add((System.nanoTime() - started) / 1_000_000.0) + } + + val rustSamples = ArrayList(REPEATS) + var rustBytes = 0 + repeat(REPEATS) { + val started = System.nanoTime() + rustBytes = TilePngEncoder.encode(source)!!.size + rustSamples.add((System.nanoTime() - started) / 1_000_000.0) + } + + println( + "TILEPNG %dx%d compress=%.1fms/%dB rust=%.1fms/%dB".format( + TILE, TILE, + median(platformSamples), platformBytes, + median(rustSamples), rustBytes, + ), + ) + } + + private fun opaqueFixture(): Bitmap { + val bitmap = Bitmap.createBitmap(TILE, TILE, Bitmap.Config.ARGB_8888) + for (y in 0 until TILE) { + for (x in 0 until TILE) { + // Distinct per channel, so a channel swap cannot coincide. + bitmap.setPixel(x, y, Color.argb(255, x % 256, y % 256, (x + 2 * y) % 256)) + } + } + return bitmap + } + + private fun translucentFixture(): Bitmap { + val bitmap = Bitmap.createBitmap(TILE, TILE, Bitmap.Config.ARGB_8888) + for (y in 0 until TILE) { + for (x in 0 until TILE) { + bitmap.setPixel(x, y, Color.argb((x * 3) % 256, 240, 90, 30)) + } + } + return bitmap + } + + /** Incompressible content, from a fixed seed so runs stay comparable. */ + private fun noiseFixture(): Bitmap { + val bitmap = Bitmap.createBitmap(TILE, TILE, Bitmap.Config.ARGB_8888) + val pixels = IntArray(TILE * TILE) + var state = 0x2545F491 + for (index in pixels.indices) { + state = state * 1_664_525 + 1_013_904_223 + val bits = state ushr 8 + pixels[index] = + Color.argb( + 128 + (bits and 0x7F), + (bits ushr 7) and 0xFF, + (bits ushr 15) and 0xFF, + (bits ushr 23) and 0xFF, + ) + } + bitmap.setPixels(pixels, 0, TILE, 0, 0, TILE, TILE) + return bitmap + } + + private fun compress(bitmap: Bitmap): ByteArray { + val stream = ByteArrayOutputStream(TILE * TILE) + bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream) + return stream.toByteArray() + } + + private fun decode(png: ByteArray): Bitmap = + BitmapFactory + .decodeByteArray(png, 0, png.size) + .copy(Bitmap.Config.ARGB_8888, false) + + private fun median(samples: List): Double = samples.sorted()[samples.size / 2] + + private companion object { + const val TILE = 512 + const val REPEATS = 5 + } +} diff --git a/src/androidTest/res/xml/test_network_security_config.xml b/src/androidTest/res/xml/test_network_security_config.xml new file mode 100644 index 0000000..a7b17d9 --- /dev/null +++ b/src/androidTest/res/xml/test_network_security_config.xml @@ -0,0 +1,8 @@ + + + + + 127.0.0.1 + localhost + + diff --git a/src/main/assets/mapconductor/blank-style.json b/src/main/assets/mapconductor/blank-style.json new file mode 100644 index 0000000..f8a9a5b --- /dev/null +++ b/src/main/assets/mapconductor/blank-style.json @@ -0,0 +1 @@ +{"version":8,"name":"blank","sources":{},"layers":[{"id":"background","type":"background","paint":{"background-color":"#f2efe9"}}]} diff --git a/src/main/java/com/mapconductor/core/MathExt.kt b/src/main/java/com/mapconductor/core/MathExt.kt index 248ad60..1b297f1 100644 --- a/src/main/java/com/mapconductor/core/MathExt.kt +++ b/src/main/java/com/mapconductor/core/MathExt.kt @@ -3,12 +3,29 @@ package com.mapconductor.core import java.math.BigDecimal import java.math.RoundingMode +/** + * Fixed-point text, with NaN and the infinities passed through as words. + * + * `BigDecimal` throws on them, and a number formatter is the wrong place to + * end a process: a provider that cannot answer a projection yet produced a + * NaN coordinate, and printing it took the app down rather than showing + * something odd. The odd thing on screen is the better failure -- it says + * which value is wrong. + */ fun Double.toFixed(decimals: Int = 0): String = - BigDecimal(this) - .setScale(decimals, RoundingMode.DOWN) - .toPlainString() + if (!isFinite()) { + toString() + } else { + BigDecimal(this) + .setScale(decimals, RoundingMode.DOWN) + .toPlainString() + } fun Float.toFixed(decimals: Int = 0): String = - BigDecimal(this.toDouble()) - .setScale(decimals, RoundingMode.DOWN) - .toPlainString() + if (!isFinite()) { + toString() + } else { + BigDecimal(this.toDouble()) + .setScale(decimals, RoundingMode.DOWN) + .toPlainString() + } diff --git a/src/main/java/com/mapconductor/core/OverlayAddedTracker.kt b/src/main/java/com/mapconductor/core/OverlayAddedTracker.kt new file mode 100644 index 0000000..136c8fc --- /dev/null +++ b/src/main/java/com/mapconductor/core/OverlayAddedTracker.kt @@ -0,0 +1,131 @@ +package com.mapconductor.core + +import android.util.Log +import java.util.concurrent.CopyOnWriteArrayList +import kotlinx.coroutines.yield + +/** + * Calls each state's `onAdded` once the map has it. + * + * One per overlay type per map, kept by the overlay that hands that type's + * states to the map ([com.mapconductor.core.polygon.PolygonOverlay] and the + * others). After every hand-over -- `compositionXxx` has returned, so the + * provider has made its objects or handed the tile template to the map -- it + * asks the map which of the states it does not yet count as "on the map" now + * are (`hasXxx`) and calls `onAdded` on those. + * + * It lives here rather than in each overlay controller because that is the one + * place every provider's overlays pass through: several providers add markers + * or polygons through their own controllers (MapLibre / Mapbox / Mappls + * polygon conductors, the per-provider marker controllers with tiling, Longdo + * and MapTiler's Compose-drawn markers), and `hasXxx` is already how each one + * says what it has. + * + * - An in-place change never reaches here (it goes to `updateXxx`), so it + * calls nothing. Neither does a move between native drawing and tiles: the + * id stays on the map. + * - An id that leaves the list is forgotten, so adding it again calls again. + * - Clearing or destroying the map calls nothing. A different controller (the + * map was recreated) starts from nothing. + * + * Not thread-safe: the overlays call it from the composition's coroutine, + * i.e. the main thread, and that is where the callbacks run. Asking the map + * about 1e5 states takes a couple of hundred ms there, so the asking yields + * every [CHECKS_PER_YIELD] states to let frames through. If the composition + * moves on meanwhile (the coroutine is cancelled), nothing is recorded or + * called; the next hand-over asks again. + */ +@InternalMapConductorApi +internal class OverlayAddedTracker( + private val onAddedOf: (T) -> ((T) -> Unit)?, +) { + private var controller: Any? = null + private var onMap: Set = emptySet() + + /** + * [data] has just been handed to [controller]. Calls `onAdded` on the + * states [isOnMap] now reports that were not on the map before. + */ + suspend fun synced( + controller: Any, + data: Collection, + isOnMap: (T) -> Boolean, + sourceIds: Set? = null, + ) { + if (controller !== this.controller) { + this.controller = controller + onMap = emptySet() + } + val previous = onMap + // A completed bulk composition can share its immutable generation's + // source-map keys. Allocate a new ID set only for partial admission. + val next = if (sourceIds == null) HashSet(data.size * 2) else null + var missing: MutableSet? = null + var added: MutableList? = null + var checked = 0 + val listening = OverlayAddedListeners.active + for (state in data) { + if (++checked % CHECKS_PER_YIELD == 0) yield() + val id = state.id + if (id in previous) { + next?.add(id) + } else if (isOnMap(state)) { + next?.add(id) + if (listening || onAddedOf(state) != null) (added ?: ArrayList().also { added = it }).add(state) + } else if (sourceIds != null) { + (missing ?: HashSet().also { missing = it }).add(id) + } + } + // Recorded and called without suspending, so a cancellation cannot + // leave some of them called and the rest forgotten. + onMap = next ?: if (missing == null) sourceIds!! else sourceIds!!.filterTo(HashSet()) { it !in missing!! } + added?.let(::notify) + } + + private fun notify(states: List) { + OverlayAddedListeners.notify(states) + for (state in states) { + val callback = onAddedOf(state) ?: continue + try { + callback(state) + } catch (e: Exception) { + // One app callback that throws must not keep the others from running. + runCatching { Log.e("MapConductor", "onAdded of ${state.id} threw", e) } + } + } + } + + @InternalMapConductorApi + private companion object { + const val CHECKS_PER_YIELD = 4096 + } +} + +/** + * Hears every batch of states [OverlayAddedTracker] finds on the map, before + * their `onAdded` calls, on the main thread. For the framework layer (the + * Compose collections count their own states with it), not for apps. + */ +@InternalMapConductorApi +object OverlayAddedListeners { + private val listeners = CopyOnWriteArrayList<(List) -> Unit>() + + internal val active: Boolean + get() = listeners.isNotEmpty() + + /** Adds [listener]; call the returned function to remove it. */ + fun add(listener: (List) -> Unit): () -> Unit { + listeners.add(listener) + return { listeners.remove(listener) } + } + + internal fun notify(states: List) { + for (listener in listeners) { + try { + listener(states) + } catch (e: Exception) { + runCatching { Log.e("MapConductor", "an overlay-added listener threw", e) } + } + } + } +} diff --git a/src/main/java/com/mapconductor/core/OverlayCollector.kt b/src/main/java/com/mapconductor/core/OverlayCollector.kt index 3f7fc8f..3ad897a 100644 --- a/src/main/java/com/mapconductor/core/OverlayCollector.kt +++ b/src/main/java/com/mapconductor/core/OverlayCollector.kt @@ -1,162 +1,238 @@ -package com.mapconductor.core - -import androidx.compose.runtime.snapshotFlow -import kotlin.time.Duration -import kotlin.time.Duration.Companion.milliseconds -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.FlowPreview -import kotlinx.coroutines.Job -import kotlinx.coroutines.flow.MutableSharedFlow -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.collectLatest -import kotlinx.coroutines.flow.sample -import kotlinx.coroutines.launch - -interface ComponentState { - val id: String -} - -/** - * The read/write contract of an [OverlayCollector], with the fingerprint type - * erased. - * - * Consumers (`CompositionLocal`s, `MarkerCollector`'s delegation, extension - * modules such as marker clustering) only ever need `T`, so declaring them - * against this interface keeps `FingerPrint` — an implementation detail of the - * in-place change diff — out of every signature. - * - * ios-sdk / react-sdk have no equivalent interface: their `OverlayCollector` - * needs no fingerprint type parameter, so the class alone is the API. - */ -interface OverlayCollectorInterface { - val flow: MutableStateFlow> - - suspend fun add(state: T) - - fun remove(id: String) - - fun setUpdateHandler(handler: (suspend (T) -> Unit)?) - - fun replaceAll(states: List) -} - -/** - * Per-map, per-overlay-type source of truth for overlay states. - * - * Same role and name as `ios-sdk-core`'s `OverlayCollector.swift` and - * `js-sdk-core`'s `overlay/OverlayCollector.ts`: one collector per overlay type - * per map, holding an `id -> state` map that the renderer subscribes to. - * - * Two independent change channels, and the three platforms agree on the shape - * of each: - * - * - **Membership** (add / remove) is **debounced**: a 5ms quiet window that each - * event extends, with a count valve so a large mount does not wait for the - * burst to end. Delivered through [flow]. - * - **In-place mutation** of an already-collected state is **sampled**: at most - * one delivery per 5ms window per state, latest value wins. Delivered through - * the update handler, never through [flow]. - */ -class OverlayCollector( - private val fingerPrintOf: (T) -> FingerPrint, - private val updateDebounce: Duration, - scope: CoroutineScope = CoroutineScope(Dispatchers.Main.immediate), -) : OverlayCollectorInterface { - private val scope = scope - private val addSharedFlow = MutableSharedFlow(1000) - private val removeSharedFlow = MutableSharedFlow(1000) - - @Volatile private var updateHandler: (suspend (T) -> Unit)? = null - private var watcherJob: Job? = null - - override val flow = MutableStateFlow>(mutableMapOf()) - - init { - scope.launch { - addSharedFlow.debounceBatch(5.milliseconds, 100).collect { states -> - val newMap = flow.value.toMutableMap() - states.forEach { state -> - newMap[state.id] = state - } - flow.value = newMap - } - } - - scope.launch { - removeSharedFlow.debounceBatch(5.milliseconds, 300).collect { ids -> - val newMap = flow.value.toMutableMap() - ids.forEach { id -> - newMap.remove(id) - } - flow.value = newMap - } - } - } - - override suspend fun add(state: T) { - addSharedFlow.emit(state) - } - - override fun remove(id: String) { - removeSharedFlow.tryEmit(id) - } - - override fun setUpdateHandler(handler: (suspend (T) -> Unit)?) { - updateHandler = handler - watcherJob?.cancel() - watcherJob = null - if (handler == null) return - watcherJob = scope.launch { watchStateChanges() } - } - - override fun replaceAll(states: List) { - flow.value = states.associateBy { it.id }.toMutableMap() - } - - /** - * Watches in-place mutations of all collected states with a single - * [snapshotFlow] that reads every state's fingerprint, then diffs - * successive fingerprint maps and delivers only the changed states to - * the update handler. - * - * A single watcher is intentional: one watcher coroutine (and snapshot - * apply-observer) per state does not scale — with tens of thousands of - * states, every update-handler registration (e.g. switching map - * providers) spawned O(n) coroutines, and every snapshot commit anywhere - * in the app paid an O(n) observer sweep. - * - * [sample] — not debounce — is deliberate: a drag mutates the same state - * every frame, and a debounce would keep extending its window and deliver - * nothing until the finger stopped. Sampling emits the latest value once - * per window while the change stream is still running. - * - * The first emission after a (re)start is recorded as the baseline and - * not delivered: membership changes (add/remove/replaceAll) reach the - * renderer through [flow], not the update handler. - */ - @OptIn(FlowPreview::class) - private suspend fun watchStateChanges() { - flow.collectLatest { states -> - if (states.isEmpty()) return@collectLatest - var baseline: Map? = null - snapshotFlow { - val prints = HashMap(states.size * 2) - for (state in states.values) { - prints[state.id] = fingerPrintOf(state) - } - prints - }.sample(updateDebounce) - .collect { current -> - val previous = baseline - baseline = current - if (previous == null) return@collect - for ((id, print) in current) { - if (previous[id] != print) { - states[id]?.let { updateHandler?.invoke(it) } - } - } - } - } - } -} +package com.mapconductor.core + +import java.util.concurrent.ConcurrentHashMap +import kotlin.time.Duration +import kotlin.time.Duration.Companion.milliseconds +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.channels.Channel +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.isActive +import kotlinx.coroutines.launch +import kotlinx.coroutines.withTimeoutOrNull + +interface ComponentState { + val id: String + + /** + * Where this state reports writes to its own fields. + * + * Every implementation owns one and routes its mutable fields through + * [StateMutationSignal.notifying]. Without that the collector never hears + * about an in-place change and the renderer keeps drawing the old value — + * silently, which is why this is required rather than defaulted. + * + * Only an assignment to a field is reported. Changing the object a field + * holds — adding to a list passed in as `points`, say — reaches no one, and + * assigning a value equal to the current one is ignored, so re-assigning a + * list after editing it in place does nothing either. Assign a new value. + */ + val mutations: StateMutationSignal +} + +/** + * The read/write contract of an [OverlayCollector], with the fingerprint type + * erased. + * + * Consumers (`CompositionLocal`s, `MarkerCollector`'s delegation, extension + * modules such as marker clustering) only ever need `T`. + * + * It carried a second type parameter until the collector stopped diffing + * fingerprints to find in-place changes; that is what this interface existed to + * keep out of every signature, and both are now gone. + */ +interface OverlayCollectorInterface { + val flow: MutableStateFlow> + + suspend fun add(state: T) + + fun remove(id: String) + + fun setUpdateHandler(handler: (suspend (T) -> Unit)?) + + fun replaceAll(states: List) +} + +/** + * Per-map, per-overlay-type source of truth for overlay states. + * + * Same role and name as `ios-sdk-core`'s `OverlayCollector.swift` and + * `js-sdk-core`'s `overlay/OverlayCollector.ts`: one collector per overlay type + * per map, holding an `id -> state` map that the renderer subscribes to. + * + * Two independent change channels, and the three platforms agree on the shape + * of each: + * + * - **Membership** (add / remove) is **debounced**: a 5ms quiet window that each + * event extends, with a count valve so a large mount does not wait for the + * burst to end. Delivered through [flow]. + * - **In-place mutation** of an already-collected state is **sampled**: at most + * one delivery per 5ms window per state, latest value wins. Delivered through + * the update handler, never through [flow]. + */ +@InternalMapConductorApi +class OverlayCollector( + private val updateDebounce: Duration, + scope: CoroutineScope = CoroutineScope(Dispatchers.Main.immediate), +) : OverlayCollectorInterface { + private val scope = scope + private val addSharedFlow = MutableSharedFlow(1000) + private val removeSharedFlow = MutableSharedFlow(1000) + + @Volatile private var updateHandler: (suspend (T) -> Unit)? = null + private var watcherJob: Job? = null + + /** + * Where mutated states queue up for the watcher, or null when nobody is + * listening — a state left registered would otherwise fill it forever. + * + * Replaced rather than drained when the handler changes: whatever the old + * watcher had not delivered is about to be delivered to the wrong handler. + */ + @Volatile private var mutated: Channel? = null + + override val flow = MutableStateFlow>(mutableMapOf()) + + /** + * Who is currently reporting mutations, kept here rather than read back out + * of [flow]. + * + * Membership reaches [flow] through a debounce, so a state added and + * removed inside the same window is not in the map when the removal + * arrives — clearing by id there found nothing and left it reporting for + * the rest of the collector's life. + */ + private val listening = ConcurrentHashMap() + + /** Only direct adds waiting for their debounced membership publication. */ + private val pendingAdds = ConcurrentHashMap.newKeySet() + + init { + scope.launch { + addSharedFlow.debounceBatch(5.milliseconds, 100).collect { states -> + flow.update { current -> + copyOverlayStates(current).apply { + states.forEach { state -> this[state.id] = state } + } + } + } + } + + scope.launch { + removeSharedFlow.debounceBatch(5.milliseconds, 300).collect { ids -> + flow.update { current -> + copyOverlayStates(current).apply { + ids.forEach { id -> remove(id) } + } + } + } + } + + // [flow] is writable from outside, and the compose `Markers(list)` writes + // its whole list straight into it rather than calling [add] 144k times. + // Those states were never listened to, so an in-place change to one of + // them -- an icon swapped to relabel a street tree -- reached nobody, and + // the tiles kept drawing the old icon. Listen to whatever arrives this + // way too. Runs per membership change, not per mutation. + scope.launch { + flow.collect { states -> listenToWrittenStates(states) } + } + } + + private fun listenToWrittenStates(states: Map) { + for ((id, state) in states) { + if (listening[id] !== state) { + listen(state) + } + pendingAdds.remove(id) + } + // Only stop what this path started: a state added through [add] may not + // have reached [flow] yet (membership is debounced). + // The listener map already identifies every registered state. Keep a + // small exception set for pending direct adds rather than duplicating + // the IDs of an entire bulk collection in another concurrent hash set. + for (id in listening.keys) { + if (id !in states && id !in pendingAdds) { + unlisten(id) + } + } + } + + override suspend fun add(state: T) { + pendingAdds.add(state.id) + listen(state) + addSharedFlow.emit(state) + } + + override fun remove(id: String) { + pendingAdds.remove(id) + unlisten(id) + removeSharedFlow.tryEmit(id) + } + + + private fun listen(state: T) { + val previous = listening.put(state.id, state) + if (previous !== null && previous !== state) previous.mutations.listen(null) + state.mutations.listen { mutated?.trySend(state) } + } + + private fun unlisten(id: String) { + listening.remove(id)?.mutations?.listen(null) + } + + override fun setUpdateHandler(handler: (suspend (T) -> Unit)?) { + updateHandler = handler + watcherJob?.cancel() + watcherJob = null + mutated = null + if (handler == null) return + val channel = Channel(Channel.UNLIMITED) + mutated = channel + watcherJob = scope.launch { watchStateChanges(channel) } + } + + override fun replaceAll(states: List) { + val next = copyOverlayStates(emptyMap()) + for (state in states) next[state.id] = state + for (id in listening.keys.toList()) { + if (next[id] !== listening[id]) unlisten(id) + } + for (state in next.values) listen(state) + flow.value = next + } + + /** + * Delivers in-place mutations that the states themselves reported. + * + * Reading every state to find out which changed cost the size of the + * collection on every snapshot commit in the app, whether or not anything + * here had changed — see [StateMutationSignal]. Now a write announces + * itself and this only runs when one did. + * + * [updateDebounce] is a sampling window, not a debounce: a drag mutates the + * same state every frame, and a debounce would keep extending its window + * and deliver nothing until the finger stopped. The first mutation opens a + * window, everything arriving inside it is folded in by id with the latest + * winning, and the batch goes out when the window closes. + */ + private suspend fun watchStateChanges(mutated: Channel) { + while (currentCoroutineContext().isActive) { + val pending = LinkedHashMap() + val first = mutated.receive() + pending[first.id] = first + withTimeoutOrNull(updateDebounce) { + while (true) { + val next = mutated.receive() + pending[next.id] = next + } + } + val handler = updateHandler ?: return + for (state in pending.values) handler(state) + } + } +} diff --git a/src/main/java/com/mapconductor/core/OverlayStateMaps.kt b/src/main/java/com/mapconductor/core/OverlayStateMaps.kt new file mode 100644 index 0000000..c38e4bb --- /dev/null +++ b/src/main/java/com/mapconductor/core/OverlayStateMaps.kt @@ -0,0 +1,20 @@ +package com.mapconductor.core + +import kotlinx.collections.immutable.toPersistentMap +import kotlinx.collections.immutable.persistentHashSetOf + +/** + * A new writable generation, sharing unchanged entries with the published map. + * Finish writing before publishing; never mutate a published generation. + * Keeps the collector's MutableMap contract and insertion order. + */ +@InternalMapConductorApi +fun copyOverlayStates(current: Map): MutableMap = + synchronized(current) { current.toPersistentMap().builder() } + +/** Compact membership snapshot without a linked hash entry for every state. */ +@InternalMapConductorApi +fun overlayStateIds(states: Iterable): Set = + persistentHashSetOf().builder().apply { + for (state in states) add(state.id) + }.build() diff --git a/src/main/java/com/mapconductor/core/RemoteImageDrawable.kt b/src/main/java/com/mapconductor/core/RemoteImageDrawable.kt new file mode 100644 index 0000000..55d2052 --- /dev/null +++ b/src/main/java/com/mapconductor/core/RemoteImageDrawable.kt @@ -0,0 +1,99 @@ +package com.mapconductor.core + +import android.graphics.Bitmap +import android.graphics.Canvas +import android.graphics.ColorFilter +import android.graphics.Paint +import android.graphics.PixelFormat +import android.graphics.drawable.BitmapDrawable +import android.graphics.drawable.Drawable + +/** + * URL の画像を、読み終えるまでは透明に、読み終えたらその画像を描く Drawable。 + * [com.mapconductor.core.marker.ImageIcon] が `imageUrl` で作られたときの中身。 + * + * 画像は一度届いたら手放さない([RemoteImageLoader] のキャッシュから追い出されても描ける)。 + * 透明から画像への変化は一方向で、一度しか起きない。 + */ +@InternalMapConductorApi +internal class RemoteImageDrawable( + val url: String, +) : Drawable() { + private val lock = Any() + + @Volatile + private var bitmap: Bitmap? = RemoteImageLoader.cached(url) + private var settled = bitmap != null + private var listeners: MutableList<() -> Unit>? = null + private val paint = Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG) + + init { + if (!settled) RemoteImageLoader.load(url, ::onLoaded) + } + + /** 画像が届いているか。 */ + val isReady: Boolean + get() = bitmap != null + + /** URL と、届いているかどうか。届いた時点で一度だけ変わる。 */ + fun identity(): Int = 31 * url.hashCode() + if (isReady) 1 else 0 + + /** + * 読み込みが終わったら(失敗も含めて)[listener] を一度だけ呼ぶ。 + * もう終わっていれば呼ばずに false を返す。呼ぶのは読み込みのスレッド。 + */ + fun whenLoaded(listener: () -> Unit): Boolean = + synchronized(lock) { + if (settled) return false + val list = listeners ?: mutableListOf<() -> Unit>().also { listeners = it } + list.add(listener) + true + } + + private fun onLoaded(result: Bitmap?) { + val toCall = + synchronized(lock) { + bitmap = result + settled = true + listeners.also { listeners = null } + } + toCall?.forEach { it() } + } + + override fun draw(canvas: Canvas) { + val image = bitmap ?: return + canvas.drawBitmap(image, null, bounds, paint) + } + + override fun setAlpha(alpha: Int) { + paint.alpha = alpha + } + + override fun setColorFilter(colorFilter: ColorFilter?) { + paint.colorFilter = colorFilter + } + + @Deprecated("Deprecated in Java") + override fun getOpacity(): Int = PixelFormat.TRANSLUCENT + + override fun getIntrinsicWidth(): Int = bitmap?.width ?: -1 + + override fun getIntrinsicHeight(): Int = bitmap?.height ?: -1 +} + +/** + * URL から読んだ画像を包む [BitmapDrawable]。 + * [com.mapconductor.core.groundimage.GroundImageState] が `imageUrl` で作られたときの `image`。 + * + * 同じ URL の同じ画像なら等しい。毎回作り直す `GroundImage(imageUrl = …)` でも + * 指紋が変わらず、作り直しのたびに描き直さずに済む。読み終えるまでは 1 px の透明な画像。 + */ +@InternalMapConductorApi +internal class UrlImageDrawable( + val url: String, + bitmap: Bitmap?, +) : BitmapDrawable(null, bitmap ?: RemoteImageLoader.transparentPixel) { + override fun equals(other: Any?): Boolean = other is UrlImageDrawable && other.url == url && other.bitmap === bitmap + + override fun hashCode(): Int = 31 * url.hashCode() + System.identityHashCode(bitmap) +} diff --git a/src/main/java/com/mapconductor/core/RemoteImageLoader.kt b/src/main/java/com/mapconductor/core/RemoteImageLoader.kt new file mode 100644 index 0000000..a84d7d1 --- /dev/null +++ b/src/main/java/com/mapconductor/core/RemoteImageLoader.kt @@ -0,0 +1,184 @@ +package com.mapconductor.core + +import java.io.File +import java.net.HttpURLConnection +import java.net.URL +import java.net.URLDecoder +import android.graphics.Bitmap +import android.graphics.BitmapFactory +import android.util.Base64 +import android.util.Log +import android.util.LruCache +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.launch + +/** + * URL で渡された画像([com.mapconductor.core.marker.ImageIcon] の `imageUrl`、 + * [com.mapconductor.core.groundimage.GroundImageState] の `imageUrl`)を読む。 + * + * - 同じ URL は同時に一度だけ取りに行き、待っている全員に同じ [Bitmap] を渡す。 + * 14 万本のマーカーが 1 つのアイコンを共有していても、通信は 1 回で済む。 + * - 読んだ画像は大きさの合計で [MAX_CACHE_BYTES] まで覚えておく。 + * - 失敗した URL はアプリが終わるまで失敗のままにし、その後の要求にはすぐ null を返す。 + * ログは URL ごとに一度だけ出す。react-sdk / ios-sdk と同じ。 + * - 読めるのは http / https / file / data。http(s) にはアプリの `android.permission.INTERNET` が要る。 + * + * 読み込みの完了は、呼び出し元とは別のスレッドから通知する。 + */ +@InternalMapConductorApi +internal object RemoteImageLoader { + private const val TAG = "MapConductor" + private const val MAX_CACHE_BYTES = 32 * 1024 * 1024 + private const val MAX_REDIRECTS = 10 + + /** URL からバイト列を取る。テストで差し替える。 */ + @Volatile + internal var fetch: (url: String) -> ByteArray = ::defaultFetch + + /** 取得と復号を走らせる先。テストで差し替える。 */ + @Volatile + internal var dispatcher: CoroutineDispatcher = Dispatchers.IO + + private val scope = CoroutineScope(SupervisorJob()) + private val lock = Any() + private val cache = + object : LruCache(MAX_CACHE_BYTES) { + override fun sizeOf( + key: String, + value: Bitmap, + ): Int = value.allocationByteCount + } + private val waiting = HashMap Unit>>() + private val failed = HashSet() + + /** 読み終えるまでの代わりに使う、1 px の透明な画像。 */ + val transparentPixel: Bitmap by lazy { + Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888).apply { density = Bitmap.DENSITY_NONE } + } + + /** 読み終えて覚えている画像。無ければ null(読み込みは始めない)。 */ + fun cached(url: String): Bitmap? = synchronized(lock) { cache.get(url) } + + /** + * [url] の画像を読み、終わったら [onDone] を一度だけ呼ぶ(失敗は null)。 + * + * 覚えている画像や、失敗した URL なら、その場で呼ぶ。 + */ + fun load( + url: String, + onDone: (Bitmap?) -> Unit, + ) { + val settled: Bitmap? + synchronized(lock) { + val hit = cache.get(url) + when { + hit != null -> settled = hit + url in failed -> settled = null + else -> { + val listeners = waiting[url] + if (listeners != null) { + listeners.add(onDone) + } else { + waiting[url] = mutableListOf(onDone) + start(url) + } + return + } + } + } + onDone(settled) + } + + private fun start(url: String) { + scope.launch(dispatcher) { + val result = + runCatching { + decode(fetch(url)) ?: throw IllegalArgumentException("not an image") + } + val bitmap = result.getOrNull() + val listeners = + synchronized(lock) { + if (bitmap != null) { + cache.put(url, bitmap) + } else if (failed.add(url)) { + Log.w(TAG, "Failed to load image: $url", result.exceptionOrNull()) + } + waiting.remove(url).orEmpty() + } + listeners.forEach { it(bitmap) } + } + } + + /** 覚えている画像と失敗を忘れ、差し替えた取得手段を元に戻す。テスト用。 */ + internal fun resetForTest() { + synchronized(lock) { + cache.evictAll() + failed.clear() + } + fetch = ::defaultFetch + dispatcher = Dispatchers.IO + } + + /** + * 画素の大きさのまま復号する。密度は [Bitmap.DENSITY_NONE] にして、`BitmapDrawable` に + * 包んでも端末の密度で縮まないようにする。 + */ + private fun decode(bytes: ByteArray): Bitmap? { + val options = BitmapFactory.Options().apply { inScaled = false } + return BitmapFactory.decodeByteArray(bytes, 0, bytes.size, options)?.apply { + density = Bitmap.DENSITY_NONE + } + } + + private fun defaultFetch(url: String): ByteArray = + when { + url.startsWith("data:") -> decodeDataUrl(url) + url.startsWith("file://") -> File(URL(url).path).readBytes() + url.startsWith("http://") || url.startsWith("https://") -> fetchHttp(url) + else -> throw IllegalArgumentException("Unsupported image URL: $url") + } + + private fun decodeDataUrl(url: String): ByteArray { + val comma = url.indexOf(',') + require(comma >= 0) { "Malformed data URL" } + val header = url.substring(0, comma) + val body = url.substring(comma + 1) + return if (header.endsWith(";base64")) { + Base64.decode(body, Base64.DEFAULT) + } else { + URLDecoder.decode(body, "UTF-8").toByteArray() + } + } + + /** + * リダイレクトは手で追う(HttpURLConnection の自動追従は http と https をまたがない)。 + * android-kml の `KMLLoader` と同じ。 + */ + private fun fetchHttp(urlStr: String): ByteArray { + var url = URL(urlStr) + repeat(MAX_REDIRECTS) { + val connection = url.openConnection() as HttpURLConnection + try { + connection.connectTimeout = 15_000 + connection.readTimeout = 30_000 + connection.instanceFollowRedirects = true + when (val status = connection.responseCode) { + HttpURLConnection.HTTP_OK -> return connection.inputStream.use { it.readBytes() } + in 300..399 -> { + val location = + connection.getHeaderField("Location") + ?: throw IllegalStateException("HTTP $status without Location: $url") + url = URL(url, location) + } + else -> throw IllegalStateException("HTTP $status: $url") + } + } finally { + connection.disconnect() + } + } + throw IllegalStateException("Too many redirects: $urlStr") + } +} diff --git a/src/main/java/com/mapconductor/core/StateMutationSignal.kt b/src/main/java/com/mapconductor/core/StateMutationSignal.kt new file mode 100644 index 0000000..b1810a2 --- /dev/null +++ b/src/main/java/com/mapconductor/core/StateMutationSignal.kt @@ -0,0 +1,89 @@ +package com.mapconductor.core + +import androidx.compose.runtime.MutableState +import androidx.compose.runtime.mutableStateOf + +/** + * Where a [ComponentState] reports that one of its own fields was written. + * + * The collector used to find these writes by reading every state's fingerprint + * inside one `snapshotFlow`. That reads a state object per field per state, and + * Compose asks a `snapshotFlow`'s apply observer, on **every** snapshot commit + * anywhere in the app, whether any of the objects it read is among the changed + * ones — a `contains` per object read. With Tokyo's 144,183 street trees that + * is about 1.7 million probes, and a drag commits a snapshot every frame: 270 + * to 380 ms of the main thread per frame on a Pixel 5a, measured, against 20 ms + * with the watcher switched off. + * + * The loop runs the wrong way round. Asking "of everything I read, did any of + * it change?" costs the size of the collection; being told "this one changed" + * costs one call per actual change, and during a drag markers do not change at + * all. So the states push instead. + */ +@InternalMapConductorApi +class StateMutationSignal { + @Volatile + private var listener: (() -> Unit)? = null + + /** + * Sets who hears about writes, or clears it with null. + * + * A state belongs to at most one collector, so there is one listener rather + * than a list. + */ + internal fun listen(listener: (() -> Unit)?) { + this.listener = listener + } + + /** Reports a write. Called from whatever thread performed it. */ + fun notifyMutated() { + listener?.invoke() + } + + /** + * A [MutableState] holding [initial] that reports its writes to this signal. + * + * Use in place of `mutableStateOf` for every field of a [ComponentState] + * that callers may change after the state is collected: + * + * ``` + * override val mutations = StateMutationSignal() + * var icon: MarkerIconInterface? by mutations.notifying(icon) + * ``` + * + * Declare `mutations` above the fields that use it: property initialisers + * run in declaration order, and the other way round it is still null here. + * + * The field reports assignments to itself and nothing else: an in-place + * change to the object it holds (a `MutableList`, a `mutableStateListOf`) + * is not seen, and an assignment equal to the current value is dropped. + * Callers change such a field by assigning a new value. + */ + fun notifying(initial: T): MutableState = NotifyingState(mutableStateOf(initial), this) +} + +/** + * Writes through to [inner] and reports the write, so the field stays readable + * from a composition exactly as a plain `mutableStateOf` field would be. + * + * Only a real change is reported. `mutableStateOf` already compares with + * structural equality before waking its own readers, so nothing new is spent + * here, and the collector's old fingerprint diff ignored equal values too. + */ +@InternalMapConductorApi +private class NotifyingState( + private val inner: MutableState, + private val signal: StateMutationSignal, +) : MutableState { + override var value: T + get() = inner.value + set(value) { + if (inner.value == value) return + inner.value = value + signal.notifyMutated() + } + + override fun component1(): T = value + + override fun component2(): (T) -> Unit = { value = it } +} diff --git a/src/main/java/com/mapconductor/core/circle/Circle.kt b/src/main/java/com/mapconductor/core/circle/Circle.kt index b9177af..5abb449 100644 --- a/src/main/java/com/mapconductor/core/circle/Circle.kt +++ b/src/main/java/com/mapconductor/core/circle/Circle.kt @@ -1,152 +1,307 @@ -package com.mapconductor.core.circle - -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.setValue -import androidx.compose.runtime.snapshotFlow -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.unit.Dp -import androidx.compose.ui.unit.dp -import com.mapconductor.core.ComponentState -import com.mapconductor.core.features.GeoPointInterface -import java.io.Serializable -import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.flow.distinctUntilChanged - -class CircleState( - center: GeoPointInterface, - radiusMeters: Double, - geodesic: Boolean = true, - clickable: Boolean = true, - strokeColor: Color = Color.Red, - strokeWidth: Dp = 1.dp, - fillColor: Color = - Color( - red = 255, - green = 255, - blue = 255, - alpha = 127, - ), - id: String? = null, - zIndex: Int? = null, - extra: Serializable? = null, - onClick: OnCircleEventHandler? = null, -) : ComponentState { - var center by mutableStateOf(center) - var clickable by mutableStateOf(clickable) - var radiusMeters by mutableStateOf(radiusMeters) - var geodesic by mutableStateOf(geodesic) - var strokeColor by mutableStateOf(strokeColor) - var strokeWidth by mutableStateOf(strokeWidth) - var fillColor by mutableStateOf(fillColor) - var extra by mutableStateOf(extra) - var zIndex by mutableStateOf(zIndex) - var onClick by mutableStateOf(onClick) - - override val id = - ( - id ?: circleId( - listOf( - center.hashCode(), - radiusMeters.hashCode(), - clickable.hashCode(), - geodesic.hashCode(), - extra?.hashCode() ?: 0, - strokeColor.hashCode(), - strokeWidth.hashCode(), - fillColor.hashCode(), - zIndex.hashCode(), - ), - ) - ).toString() - - private fun circleId(hashCodes: List): Int = - hashCodes.reduce { result, hashCode -> - 31 * result + hashCode - } - - fun fingerPrint(): CircleFingerPrint = - CircleFingerPrint( - id = this.id.hashCode(), - center = center.hashCode(), - radiusMeters = radiusMeters.hashCode(), - clickable = clickable.hashCode(), - geodesic = geodesic.hashCode(), - strokeColor = strokeColor.hashCode(), - strokeWidth = strokeWidth.hashCode(), - fillColor = fillColor.hashCode(), - zIndex = zIndex.hashCode(), - extra = extra?.hashCode() ?: 0, - ) - - fun asFlow(): Flow = snapshotFlow { fingerPrint() }.distinctUntilChanged() - - fun copy( - center: GeoPointInterface = this.center, - radiusMeters: Double = this.radiusMeters, - geodesic: Boolean = this.geodesic, - clickable: Boolean = this.clickable, - strokeColor: Color = this.strokeColor, - strokeWidth: Dp = this.strokeWidth, - fillColor: Color = this.fillColor, - id: String? = this.id, - zIndex: Int? = this.zIndex, - extra: Serializable? = this.extra, - onClick: OnCircleEventHandler? = this.onClick, - ): CircleState = - CircleState( - center = center, - clickable = clickable, - radiusMeters = radiusMeters, - geodesic = geodesic, - strokeColor = strokeColor, - strokeWidth = strokeWidth, - fillColor = fillColor, - id = id, - zIndex = zIndex, - extra = extra, - onClick = onClick, - ) - - override fun equals(other: Any?): Boolean { - val otherState = (other as? CircleState) ?: return false - return hashCode() == otherState.hashCode() - } - - override fun hashCode(): Int { - var result = extra?.hashCode() ?: 0 - result = 31 * result + center.hashCode() - result = 31 * result + clickable.hashCode() - result = 31 * result + geodesic.hashCode() - result = 31 * result + radiusMeters.hashCode() - result = 31 * result + strokeColor.hashCode() - result = 31 * result + strokeWidth.hashCode() - result = 31 * result + fillColor.hashCode() - result = 31 * result + zIndex.hashCode() - return result - } -} - -data class CircleFingerPrint( - val id: Int, - val center: Int, - val radiusMeters: Int, - val clickable: Int, - val geodesic: Int, - val strokeColor: Int, - val strokeWidth: Int, - val fillColor: Int, - val zIndex: Int, - val extra: Int, -) - -class CircleEvent( - val state: CircleState, - clicked: GeoPointInterface, -) { - // 生成時に wrap して [-180,180] / [-90,90] に正規化する(日付変更線対策)。 - // 正規化をここ(イベント型=出口)に一元化することで、どの配送経路でも wrap 漏れが起きない。 - val clicked: GeoPointInterface = clicked.wrap() -} - -typealias OnCircleEventHandler = (CircleEvent) -> Unit +package com.mapconductor.core.circle + +import androidx.compose.runtime.getValue +import androidx.compose.runtime.setValue +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import com.mapconductor.core.ComponentState +import com.mapconductor.core.StateMutationSignal +import com.mapconductor.core.features.GeoPointInterface +import java.io.Serializable + +class CircleState( + center: GeoPointInterface, + radiusMeters: Double, + geodesic: Boolean = true, + clickable: Boolean = true, + strokeColor: Color = Color.Red, + strokeWidth: Dp = 1.dp, + fillColor: Color = + Color( + red = 255, + green = 255, + blue = 255, + alpha = 127, + ), + id: String? = null, + zIndex: Int? = null, + extra: Serializable? = null, + onClick: OnCircleEventHandler? = null, + onAdded: OnCircleAddedHandler? = null, +) : ComponentState { + /** + * Writes to the fields below are announced here rather than discovered by + * reading them all back. See [StateMutationSignal]. + */ + override val mutations = StateMutationSignal() + + // One Compose snapshot record per circle, rather than one per attribute. + private data class Values( + val center: GeoPointInterface, + val clickable: Boolean, + val radiusMeters: Double, + val geodesic: Boolean, + val strokeColor: Color, + val strokeWidth: Dp, + val fillColor: Color, + val extra: Serializable?, + val zIndex: Int?, + val onClick: OnCircleEventHandler?, + val revision: Long = 0, + val changedFields: Int = 0, + ) { + fun difference(other: Values): Int { + var mask = 0 + if (center != other.center) mask = mask or (1 shl 0) + if (clickable != other.clickable) mask = mask or (1 shl 3) + if (radiusMeters != other.radiusMeters) mask = mask or (1 shl 1) + if (geodesic != other.geodesic) mask = mask or (1 shl 2) + if (strokeColor != other.strokeColor) mask = mask or (1 shl 4) + if (strokeWidth != other.strokeWidth) mask = mask or (1 shl 5) + if (fillColor != other.fillColor) mask = mask or (1 shl 6) + if (extra != other.extra) mask = mask or (1 shl 7) + if (zIndex != other.zIndex) mask = mask or (1 shl 8) + return mask + } + } + internal fun captureValues(): Any = values + internal fun changeMaskSince(snapshot: Any, sameState: Boolean): Int { + val applied = snapshot as Values + val current = values + if (current === applied) return 0 + return if (sameState && current.revision != applied.revision) current.changedFields + else applied.difference(current) + } + internal fun snapshotFingerPrint(snapshot: Any): CircleFingerPrint = fingerPrint(snapshot as Values) + private var values by androidx.compose.runtime.mutableStateOf(Values(center, clickable, radiusMeters, geodesic, strokeColor, strokeWidth, fillColor, extra, zIndex, onClick)) + + private fun update(next: Values) { + if (values == next) return + values = next.copy(revision = values.revision + 1, changedFields = values.changedFields or values.difference(next)) + mutations.notifyMutated() + } + + var center: GeoPointInterface + get() = values.center + set(value) { update(values.copy(center = value)) } + var clickable: Boolean + get() = values.clickable + set(value) { update(values.copy(clickable = value)) } + var radiusMeters: Double + get() = values.radiusMeters + set(value) { update(values.copy(radiusMeters = value)) } + var geodesic: Boolean + get() = values.geodesic + set(value) { update(values.copy(geodesic = value)) } + var strokeColor: Color + get() = values.strokeColor + set(value) { update(values.copy(strokeColor = value)) } + var strokeWidth: Dp + get() = values.strokeWidth + set(value) { update(values.copy(strokeWidth = value)) } + var fillColor: Color + get() = values.fillColor + set(value) { update(values.copy(fillColor = value)) } + var extra: Serializable? + get() = values.extra + set(value) { update(values.copy(extra = value)) } + var zIndex: Int? + get() = values.zIndex + set(value) { update(values.copy(zIndex = value)) } + var onClick: OnCircleEventHandler? + get() = values.onClick + set(value) { update(values.copy(onClick = value)) } + + /** + * Called once each time this circle goes from not being on the map to being on it: + * after the map SDK's object for it has been created, or, when it is drawn in tiles, + * after the URL template of those tiles has been handed to the map as a raster layer + * (the tile images may still be loading then). Not called for an in-place change, + * nor when it moves between native drawing and tiles while staying on the map; + * called again if it is removed and added again. Clearing or destroying the map calls + * nothing. + * + * Runs on the main thread once the map has finished adding the overlays it was given. + * A callback that throws is logged and does not stop the other overlays' callbacks. + * + * Like `onClick`, it is not part of the id, fingerprint, equality or hash: replacing + * it redraws nothing. If the same state is shown on two maps, each map calls it. + */ + var onAdded: OnCircleAddedHandler? = onAdded + + @Deprecated("Binary compatibility only; use the overload with onAdded.", level = DeprecationLevel.HIDDEN) + constructor( + center: GeoPointInterface, + radiusMeters: Double, + geodesic: Boolean = true, + clickable: Boolean = true, + strokeColor: Color = Color.Red, + strokeWidth: Dp = 1.dp, + fillColor: Color = + Color( + red = 255, + green = 255, + blue = 255, + alpha = 127, + ), + id: String? = null, + zIndex: Int? = null, + extra: Serializable? = null, + onClick: OnCircleEventHandler? = null, + ) : this( + center, + radiusMeters, + geodesic, + clickable, + strokeColor, + strokeWidth, + fillColor, + id, + zIndex, + extra, + onClick, + null, + ) + + override val id = + ( + id ?: circleId( + listOf( + center.hashCode(), + radiusMeters.hashCode(), + clickable.hashCode(), + geodesic.hashCode(), + extra?.hashCode() ?: 0, + strokeColor.hashCode(), + strokeWidth.hashCode(), + fillColor.hashCode(), + zIndex.hashCode(), + ), + ) + ).toString() + + private fun circleId(hashCodes: List): Int = + hashCodes.reduce { result, hashCode -> + 31 * result + hashCode + } + + fun fingerPrint(): CircleFingerPrint = fingerPrint(values) + + private fun fingerPrint(snapshot: Values): CircleFingerPrint = + CircleFingerPrint( + id = this.id.hashCode(), + center = snapshot.center.hashCode(), + radiusMeters = snapshot.radiusMeters.hashCode(), + clickable = snapshot.clickable.hashCode(), + geodesic = snapshot.geodesic.hashCode(), + strokeColor = snapshot.strokeColor.hashCode(), + strokeWidth = snapshot.strokeWidth.hashCode(), + fillColor = snapshot.fillColor.hashCode(), + zIndex = snapshot.zIndex.hashCode(), + extra = snapshot.extra?.hashCode() ?: 0, + ) + + fun copy( + center: GeoPointInterface = this.center, + radiusMeters: Double = this.radiusMeters, + geodesic: Boolean = this.geodesic, + clickable: Boolean = this.clickable, + strokeColor: Color = this.strokeColor, + strokeWidth: Dp = this.strokeWidth, + fillColor: Color = this.fillColor, + id: String? = this.id, + zIndex: Int? = this.zIndex, + extra: Serializable? = this.extra, + onClick: OnCircleEventHandler? = this.onClick, + onAdded: OnCircleAddedHandler? = this.onAdded, + ): CircleState = + CircleState( + center = center, + clickable = clickable, + radiusMeters = radiusMeters, + geodesic = geodesic, + strokeColor = strokeColor, + strokeWidth = strokeWidth, + fillColor = fillColor, + id = id, + zIndex = zIndex, + extra = extra, + onClick = onClick, + onAdded = onAdded, + ) + + @Deprecated("Binary compatibility only; use the overload with onAdded.", level = DeprecationLevel.HIDDEN) + fun copy( + center: GeoPointInterface = this.center, + radiusMeters: Double = this.radiusMeters, + geodesic: Boolean = this.geodesic, + clickable: Boolean = this.clickable, + strokeColor: Color = this.strokeColor, + strokeWidth: Dp = this.strokeWidth, + fillColor: Color = this.fillColor, + id: String? = this.id, + zIndex: Int? = this.zIndex, + extra: Serializable? = this.extra, + onClick: OnCircleEventHandler? = this.onClick, + ): CircleState = + copy( + center, + radiusMeters, + geodesic, + clickable, + strokeColor, + strokeWidth, + fillColor, + id, + zIndex, + extra, + onClick, + onAdded, + ) + + override fun equals(other: Any?): Boolean { + val otherState = (other as? CircleState) ?: return false + return hashCode() == otherState.hashCode() + } + + override fun hashCode(): Int { + var result = extra?.hashCode() ?: 0 + result = 31 * result + center.hashCode() + result = 31 * result + clickable.hashCode() + result = 31 * result + geodesic.hashCode() + result = 31 * result + radiusMeters.hashCode() + result = 31 * result + strokeColor.hashCode() + result = 31 * result + strokeWidth.hashCode() + result = 31 * result + fillColor.hashCode() + result = 31 * result + zIndex.hashCode() + return result + } +} + +data class CircleFingerPrint( + val id: Int, + val center: Int, + val radiusMeters: Int, + val clickable: Int, + val geodesic: Int, + val strokeColor: Int, + val strokeWidth: Int, + val fillColor: Int, + val zIndex: Int, + val extra: Int, +) + +class CircleEvent( + val state: CircleState, + clicked: GeoPointInterface, +) { + // 生成時に wrap して [-180,180] / [-90,90] に正規化する(日付変更線対策)。 + // 正規化をここ(イベント型=出口)に一元化することで、どの配送経路でも wrap 漏れが起きない。 + val clicked: GeoPointInterface = clicked.wrap() +} + +typealias OnCircleEventHandler = (CircleEvent) -> Unit + +/** Receives the state whose circle was just added to the map. See [CircleState.onAdded]. */ +typealias OnCircleAddedHandler = (CircleState) -> Unit diff --git a/src/main/java/com/mapconductor/core/circle/CircleController.kt b/src/main/java/com/mapconductor/core/circle/CircleController.kt index 2075365..3e8c992 100644 --- a/src/main/java/com/mapconductor/core/circle/CircleController.kt +++ b/src/main/java/com/mapconductor/core/circle/CircleController.kt @@ -1,11 +1,15 @@ package com.mapconductor.core.circle +import com.mapconductor.core.controller.OnCameraChangeReceiverInterface import com.mapconductor.core.controller.OverlayHit import com.mapconductor.core.controller.OverlayKind import com.mapconductor.core.controller.SlottedOverlayController import com.mapconductor.core.features.GeoPointInterface +import com.mapconductor.core.map.MapCameraPosition +import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.sync.Semaphore import kotlinx.coroutines.sync.withPermit +import kotlinx.coroutines.withContext abstract class CircleController( val circleManager: CircleManagerInterface, @@ -13,12 +17,23 @@ abstract class CircleController( ) : SlottedOverlayController< CircleState, CircleEntityInterface, - > { - override val zIndex: Int = 3 + >, + OnCameraChangeReceiverInterface { + override val zIndex: Int = 4 val semaphore = Semaphore(1) + private var currentCameraPosition: MapCameraPosition? = null var clickListener: OnCircleEventHandler? = null + /** + * Set by a provider that can show circle tiles (see [CircleTiler]). + * Circles it tiles stay in [circleManager], for taps, with no native + * overlay: their entity's `circle` is null and the renderer never sees + * them. A renderer that redraws from the manager must skip those. + */ + var tiler: CircleTiler? = null + private var tiledIds: Set = emptySet() + fun dispatchClick(event: CircleEvent) { // 配送座標の wrap は CircleEvent の生成時に一元化済み。 event.state.onClick?.invoke(event) @@ -27,16 +42,27 @@ abstract class CircleController( override suspend fun add(data: List) { semaphore.withPermit { + val wasTiled = tiledIds + val tiled = tiler?.route(data) ?: emptySet() + val sharedTiles = circleManager.setTiledSource(tiler) + tiledIds = tiled + val native = if (tiled.isEmpty()) data else data.filter { it.id !in tiled } val modifiedEntities = mutableListOf>() - val previous = circleManager.allEntities().map { it.state.id }.toMutableSet() + // Only natively drawn circles are diffed against the renderer. + val previous = + circleManager + .nativeEntities() + .map { it.state.id } + .filterTo(mutableSetOf()) { it !in wasTiled } val added = mutableListOf() val updated = mutableListOf>() val removed = mutableListOf>() - data.forEach { state -> + native.forEach { state -> if (previous.contains(state.id)) { - val prevEntity = circleManager.getEntity(state.id)!! - if (state.fingerPrint() == prevEntity.fingerPrint) { + // Gone only if destroy() cleared the manager meanwhile; nothing left to update. + val prevEntity = circleManager.getEntity(state.id) ?: return@withPermit + if (unchanged(state, prevEntity)) { // 描画結果が不変なら renderer を呼ばず最新の state だけ採用する // (react-sdk と同じ。composition ごとに全オーバーレイへ onChange を // 再実行する無駄・チラつきを避ける)。 @@ -108,16 +134,69 @@ abstract class CircleController( } } + // Tiled circles: kept for taps, nothing native. Those that left + // the tiles and the list are forgotten; those that left the tiles + // for native drawing were added above. + if (wasTiled.isNotEmpty()) { + val nativeIds = native.mapTo(HashSet()) { it.id } + for (id in wasTiled) { + if (id !in tiled && id !in nativeIds) circleManager.removeEntity(id) + } + } + if (tiled.isNotEmpty() && !sharedTiles) { + val tiledStates = tiler!!.tiledStates() + withContext(Dispatchers.Default) { + for (state in tiledStates) { + circleManager.registerEntity(CircleEntity(circle = inTiles(), state = state)) + } + } + } + renderer.onPostProcess() } } + /** What a tiled circle's entity holds instead of a native circle. */ + private fun unchanged(state: CircleState, previous: CircleEntityInterface): Boolean = + (previous as? CircleEntity)?.let { it.changeMask(state) == 0 } + ?: (state.fingerPrint() == previous.fingerPrint) + + @Suppress("UNCHECKED_CAST") + private fun inTiles(): ActualCircle = null as ActualCircle + override suspend fun update(state: CircleState) { semaphore.withPermit { val prevEntity = circleManager.getEntity(state.id) ?: return - val currentFinger = state.fingerPrint() - val prevFinger = prevEntity.fingerPrint - if (currentFinger == prevFinger) { + if (state.id in tiledIds) { + if (CircleTileSet.canTile(state)) { + circleManager.registerEntity(CircleEntity(circle = prevEntity.circle, state = state)) + tiler?.update(state) + return + } + // No longer drawable in a tile (no radius, or over a pole or the + // antimeridian): the map SDK draws it from now on. Still on the + // map, so this is not an add. Whether the rest stay in tiles is + // left to the next add(), which decides tiling for the whole list. + tiledIds = tiledIds - state.id + tiler?.remove(state.id) + val circles = + renderer.onAdd( + listOf( + object : CircleOverlayRendererInterface.AddParamsInterface { + override val state: CircleState = state + }, + ), + ) + val circle = circles.firstOrNull() + if (circle != null) { + circleManager.registerEntity(CircleEntity(circle = circle, state = state)) + } else { + circleManager.removeEntity(state.id) + } + renderer.onPostProcess() + return + } + if (unchanged(state, prevEntity)) { return } @@ -148,17 +227,38 @@ abstract class CircleController( override suspend fun clear() { semaphore.withPermit { - val entities: List> = circleManager.allEntities() + val tiled = tiledIds + tiledIds = emptySet() + tiler?.clear() + val entities: List> = + circleManager.nativeEntities().filter { it.state.id !in tiled } renderer.onRemove(entities) + // manager を空にしてから onPostProcess を呼ぶ。GL 系の描画担当は remove では何もせず、 + // onPostProcess で manager の全部を描き直すので、逆の順だと clear() 後も地図に残る。 circleManager.clear() renderer.onPostProcess() } } - override fun find(position: GeoPointInterface): CircleEntityInterface? = circleManager.find(position) + /** + * The circle a tap at [position] is on: within its radius, or within half + * its stroke past the edge at the camera's zoom. The same whether the + * circle is drawn natively or in tiles. + */ + override fun find(position: GeoPointInterface): CircleEntityInterface? = + circleManager.find(position, currentCameraPosition) + + override suspend fun onCameraChanged(mapCameraPosition: MapCameraPosition) { + currentCameraPosition = mapCameraPosition + } override fun destroy() { - // No native resources to clean up for circles + // The tile server outlives the map; without this its route keeps every + // tiled circle (and the renderer's copies of them) alive. + tiler?.dispose() + // A destroyed controller can still be referenced (by its map controller, + // or a state that has not let go yet); without this it keeps every entity. + circleManager.clear() } override fun has(id: String): Boolean = circleManager.hasEntity(id) diff --git a/src/main/java/com/mapconductor/core/circle/CircleEntity.kt b/src/main/java/com/mapconductor/core/circle/CircleEntity.kt index a940208..0bbb32e 100644 --- a/src/main/java/com/mapconductor/core/circle/CircleEntity.kt +++ b/src/main/java/com/mapconductor/core/circle/CircleEntity.kt @@ -10,5 +10,13 @@ class CircleEntity( override var circle: ActualCircle, override val state: CircleState, ) : CircleEntityInterface { - override val fingerPrint: CircleFingerPrint = state.fingerPrint() + private val applied = state.captureValues() + + // Legacy provider API: create a fingerprint only when a native renderer + // requests it. No fingerprint object is retained per circle. + override val fingerPrint: CircleFingerPrint get() = state.snapshotFingerPrint(applied) + + internal fun changeMask(next: CircleState): Int { + return next.changeMaskSince(applied, next === state) + } } diff --git a/src/main/java/com/mapconductor/core/circle/CircleManager.kt b/src/main/java/com/mapconductor/core/circle/CircleManager.kt index 531b08f..59bd89b 100644 --- a/src/main/java/com/mapconductor/core/circle/CircleManager.kt +++ b/src/main/java/com/mapconductor/core/circle/CircleManager.kt @@ -1,9 +1,11 @@ package com.mapconductor.core.circle -import com.mapconductor.core.calculateZIndex import com.mapconductor.core.features.GeoPointInterface +import com.mapconductor.core.map.MapCameraPosition import com.mapconductor.core.spherical.Spherical +import com.mapconductor.core.spherical.calculateMetersPerPixel import java.util.concurrent.ConcurrentHashMap +import kotlin.math.abs interface CircleManagerInterface { fun registerEntity(entity: CircleEntityInterface) @@ -16,60 +18,124 @@ interface CircleManagerInterface { fun allEntities(): List> + fun nativeEntities(): List> = allEntities().filter { it.circle != null } + + fun setTiledSource(source: CircleTiler?): Boolean = false + fun clear() fun find(position: GeoPointInterface): CircleEntityInterface? + + /** + * The circle a tap at [position] is on, with [cameraPosition]'s zoom to + * measure half the stroke past the edge. Without a camera, or for a + * manager that does not measure the stroke, the same as [find]. + */ + fun find( + position: GeoPointInterface, + cameraPosition: MapCameraPosition?, + ): CircleEntityInterface? = find(position) } class CircleManager : CircleManagerInterface { private val entities: ConcurrentHashMap> = ConcurrentHashMap() + @Volatile private var tiledSource: CircleTiler? = null - override fun getEntity(id: String): CircleEntityInterface? = entities.get(id) + override fun setTiledSource(source: CircleTiler?): Boolean { + tiledSource = source + return true + } - override fun hasEntity(id: String): Boolean = entities.containsKey(id) + @Suppress("UNCHECKED_CAST") + private fun tiledEntity(state: CircleState): CircleEntityInterface = CircleEntity(null as ActualCircle, state) + + override fun getEntity(id: String): CircleEntityInterface? = entities[id] ?: tiledSource?.state(id)?.let(::tiledEntity) + + override fun hasEntity(id: String): Boolean = entities.containsKey(id) || tiledSource?.isTiled(id) == true override fun removeEntity(id: String): CircleEntityInterface? { val removed = entities.remove(id) - return removed + if (removed != null) return removed + val source = tiledSource ?: return null + val state = source.state(id) ?: return null + source.remove(id) + return tiledEntity(state) } override fun registerEntity(entity: CircleEntityInterface) { + if (entity.circle == null && tiledSource?.isTiled(entity.state.id) == true) { + entities.remove(entity.state.id) + return + } entities[entity.state.id] = entity } fun updateEntity(entity: CircleEntityInterface) { - entities[entity.state.id] = entity + registerEntity(entity) } // ArrayList(values) avoids the size==1 race in Kotlin's toList() on concurrent maps. - override fun allEntities(): List> = ArrayList(entities.values) + override fun nativeEntities(): List> = ArrayList(entities.values) + + override fun allEntities(): List> = nativeEntities().toMutableList().also { result -> + tiledSource?.visitStates { state -> if (!entities.containsKey(state.id)) result.add(tiledEntity(state)) } + } override fun clear() { entities.clear() + tiledSource = null } - override fun find(position: GeoPointInterface): CircleEntityInterface? { - val filtered = - allEntities().filter { entity -> - val centerPos = entity.state.center - val distance = Spherical.computeDistanceBetween(centerPos, position) - return@filter (distance <= entity.state.radiusMeters) && entity.state.clickable + override fun find(position: GeoPointInterface): CircleEntityInterface? = find(position, null) + + /** + * The circle a tap at [position] is on (the same on all three platforms, + * and whether the circle is drawn natively or in tiles): + * + * - on it when the tap is within its radius plus half its stroke past the + * edge, the stroke measured on screen at [cameraPosition]'s zoom (no + * camera: the radius alone). The finger's size is not added: a circle is + * an area, as a polygon is, and among a street of small trees the finger + * would pick up the neighbours. + * - clickable = false circles let the tap through. + * - of several, the one on top: the highest zIndex (an unset one is the + * automatic one from the centre), then the nearest centre. + */ + override fun find( + position: GeoPointInterface, + cameraPosition: MapCameraPosition?, + ): CircleEntityInterface? { + val metersPerPixel = cameraPosition?.let { calculateMetersPerPixel(position.latitude, it.zoom) } ?: 0.0 + // Meters per degree of latitude, rounded down: the latitude check may only ever let more through. + val metersPerDegree = 110_000.0 + var best: CircleEntityInterface? = null + var bestState: CircleState? = null + var bestZ = Int.MIN_VALUE + var bestDistance = Double.POSITIVE_INFINITY + fun consider(state: CircleState, entity: CircleEntityInterface?) { + if (!state.clickable) return + val reach = state.radiusMeters + metersPerPixel * state.strokeWidth.value / 2.0 + if (!(reach >= 0.0)) return + // A degree of latitude is never under metersPerDegree: one further + // north or south than the reach cannot be on it. Skips the distance + // for nearly every circle of a city. + if (abs(state.center.latitude - position.latitude) > reach / metersPerDegree) return + val distance = Spherical.computeDistanceBetween(state.center, position) + if (distance > reach) return + val z = effectiveZIndex(state) + if (bestState == null || z > bestZ || (z == bestZ && distance < bestDistance)) { + best = entity + bestState = state + bestZ = z + bestDistance = distance } - - if (filtered.isEmpty()) { - return null } - - var maxZIndex = Int.MIN_VALUE - var maxEntity = filtered[0] - - filtered.forEach { - val zIndex = it.state.zIndex ?: calculateZIndex(it.state.center) - if (maxZIndex < zIndex) { - maxZIndex = zIndex - maxEntity = it - } + for (entity in entities.values) consider(entity.state, entity) + // Tiled circles: only those near the tap, found through the tiles' index. + // Reading every state here took 0.6 s at 700k circles on a tablet. + tiledSource?.states(position.latitude, position.longitude, metersPerPixel)?.forEach { state -> + if (!entities.containsKey(state.id)) consider(state, null) } - return maxEntity + return best ?: bestState?.let(::tiledEntity) } } diff --git a/src/main/java/com/mapconductor/core/circle/CircleOverlay.kt b/src/main/java/com/mapconductor/core/circle/CircleOverlay.kt index 4afb457..d76fb87 100644 --- a/src/main/java/com/mapconductor/core/circle/CircleOverlay.kt +++ b/src/main/java/com/mapconductor/core/circle/CircleOverlay.kt @@ -1,16 +1,36 @@ package com.mapconductor.core.circle +import com.mapconductor.core.OverlayAddedTracker +import com.mapconductor.core.controller.BaseMapViewController import com.mapconductor.core.controller.MapViewControllerInterface import com.mapconductor.core.map.MapOverlayInterface import kotlinx.coroutines.flow.StateFlow -class CircleOverlay( - override val flow: StateFlow>, -) : MapOverlayInterface { - override suspend fun render( - data: MutableMap, - controller: MapViewControllerInterface, - ) { - (controller as? CircleCapableInterface)?.compositionCircles(data.values.toList()) +class CircleOverlay + @JvmOverloads + constructor( + override val flow: StateFlow>, + /** + * This map's circle tiling, when the app sets one (null keeps the + * provider's [CircleTilingOptions.Default]). Applied to the map's + * [CircleTiler] before every hand-over, so a change takes effect the + * next time the circles are handed over. + */ + private val tilingOptions: StateFlow? = null, + ) : MapOverlayInterface { + /** Calls [CircleState.onAdded] once the map has the state. See [OverlayAddedTracker]. */ + private val added = OverlayAddedTracker { it.onAdded } + + override suspend fun render( + data: MutableMap, + controller: MapViewControllerInterface, + ) { + val capable = controller as? CircleCapableInterface ?: return + tilingOptions?.value?.let { options -> + (controller as? BaseMapViewController)?.circleTilers()?.forEach { it.options = options } + } + val states = data.values.toList() + capable.compositionCircles(states) + added.synced(controller, states, capable::hasCircle, sourceIds = data.keys) + } } -} diff --git a/src/main/java/com/mapconductor/core/circle/CircleTileFileStorage.kt b/src/main/java/com/mapconductor/core/circle/CircleTileFileStorage.kt new file mode 100644 index 0000000..02acf9a --- /dev/null +++ b/src/main/java/com/mapconductor/core/circle/CircleTileFileStorage.kt @@ -0,0 +1,393 @@ +package com.mapconductor.core.circle + +import com.mapconductor.core.InternalMapConductorApi +import com.mapconductor.core.shapetile.ShapeTileStorage +import com.mapconductor.core.shapetile.StorageOrder +import java.io.EOFException +import java.io.File +import java.io.RandomAccessFile +import java.nio.ByteBuffer +import java.nio.ByteOrder +import kotlin.math.max + +/** + * Packed immutable circle geometry, read through a bounded block cache. + * No nationwide TileCircle or bounding-box object arrays are retained. + * Small updates share the file; a bounded override map is compacted when full. + * + * With an [order], the records are stored by place ([storageOrder]): a tile's + * circles then lie in a few blocks instead of most of the file. Everything + * here still takes the list's indices. + */ +@InternalMapConductorApi +internal class CircleTileFileStorage private constructor( + private val file: SharedFile, + override val size: Int, + override val maxStroke: Float, + private val order: StorageOrder?, + private val overrides: Map = emptyMap(), +) : ShapeTileStorage() { + init { + file.retain() + } + + internal val cacheFile: File get() = file.path + internal val cachedBytes: Int get() = file.cachedBytes + internal val allocatedReadBuffers: Int get() = file.allocatedReadBuffers + + override val storageOrder: StorageOrder? get() = order + + private fun positionOf(index: Int): Int = order?.positionOf?.get(index) ?: index + + override fun get(index: Int): TileCircle? = + when { + index !in 0 until size -> null + overrides.isNotEmpty() && overrides.containsKey(index) -> overrides[index] + else -> file.read(positionOf(index)) { bytes, offset -> decode(bytes, offset) } + } + + /** + * Calls [action] for each of [indices], with the record's bytes and offset + * in them, or with the overriding circle (bytes null). Records of one block + * are read under one lock, not one per circle: a nationwide tile reads + * hundreds of thousands, on several tile threads at once. + * + * The calls come in storage order, which is [indices]' order only without + * an [order]: `k` says which of [indices] each one is. + */ + internal fun forEachRecord( + indices: IntArray, + checkCancelled: () -> Unit, + action: RecordAction, + ) { + // The block is copied out under the lock and read outside it: other + // tiles read the same file on other threads, and must not wait while + // this one records its circles. + val scratch = ByteBuffer.allocate(BLOCK_BYTES).order(ByteOrder.LITTLE_ENDIAN) + // Each one's stored position (high half) and k (low half), in storage order. + val sorted = LongArray(indices.size) + var count = 0 + for (k in indices.indices) { + val index = indices[k] + if (index !in 0 until size) continue + if (overrides.isNotEmpty() && overrides.containsKey(index)) { + action.record(k, null, 0, overrides[index]) + continue + } + sorted[count++] = (positionOf(index).toLong() shl 32) or k.toLong() + } + if (order != null) sorted.sort(0, count) + var at = 0 + while (at < count) { + checkCancelled() + val block = (sorted[at] ushr 32).toInt() / RECORDS_PER_BLOCK + file.copyBlock(block, scratch) + while (at < count) { + val position = (sorted[at] ushr 32).toInt() + if (position / RECORDS_PER_BLOCK != block) break + action.record(sorted[at].toInt(), scratch, position % RECORDS_PER_BLOCK * RECORD_BYTES, null) + at++ + } + } + } + + /** What [forEachRecord] calls per circle; primitive arguments, so nothing is boxed per call. */ + internal fun interface RecordAction { + /** [bytes] at [offset] is the record, or [bytes] is null and [override] the circle. */ + fun record( + k: Int, + bytes: ByteBuffer?, + offset: Int, + override: TileCircle?, + ) + } + + override fun bbox(index: Int): DoubleArray? = + when { + index !in 0 until size -> null + overrides.isNotEmpty() && overrides.containsKey(index) -> overrides[index]?.bbox + else -> + file.read(positionOf(index)) { bytes, p -> + if (bytes.getInt(p + 76) and 1 == 0) { + null + } else { + val x = bytes.getDouble(p + 24) + val half = bytes.getDouble(p + 40) + doubleArrayOf(x - half, bytes.getDouble(p + 48), x + half, bytes.getDouble(p + 56)) + } + } + } + + override fun updated(updates: List>): ShapeTileStorage { + var widest = maxStroke + for ((index, item) in updates) { + if (index in 0 until size && item != null) { + widest = max(widest, CircleTilePainter.strokeWidth(item)) + } + } + val changed = HashMap(overrides) + var compact = false + for ((index, item) in updates) if (index in 0 until size) { + if (index !in changed && changed.size == MAX_OVERRIDES) { + compact = true + break + } + changed[index] = item + } + if (!compact) return CircleTileFileStorage(file, size, widest, order, changed) + // Compact by streaming, never by materialising every decoded circle. + val next = create(file.path.parentFile!!, size, { get(it) }, order = order) + try { + next.file.patch(updates.map { (index, item) -> positionOf(index) to item }, size) + val result = CircleTileFileStorage(next.file, size, widest, order) + next.release() + return result + } catch (error: Throwable) { + next.release() + throw error + } + } + + override fun close() = file.release() + + @InternalMapConductorApi + private class SharedFile( + val path: File, + ) { + private val handle = RandomAccessFile(path, "rw") + private val channel = handle.channel + private var references = 0 + private val blocks = LinkedHashMap(MAX_BLOCKS, 0.75f, true) + var allocatedReadBuffers = 0 + private set + val cachedBytes: Int get() = synchronized(this) { blocks.values.sumOf { it.capacity() } } + + @Synchronized fun retain() { + references++ + } + + @Synchronized fun release() { + check(--references >= 0) + if (references == 0) dispose() + } + + @Synchronized fun dispose() { + try { + handle.close() + } finally { + blocks.clear() + synchronized(liveFiles) { + liveFiles.remove(path.absolutePath) + path.delete() + } + } + } + + /** Copies [block]'s bytes into [into] (its whole capacity, from 0). */ + @Synchronized fun copyBlock( + block: Int, + into: ByteBuffer, + ) { + val bytes = blockBytes(block) + into.clear() + into.put(bytes.array(), 0, bytes.limit()) + into.flip() + } + + @Synchronized fun read( + index: Int, + action: (ByteBuffer, Int) -> R, + ): R { + val block = index / RECORDS_PER_BLOCK + return action(blockBytes(block), index % RECORDS_PER_BLOCK * RECORD_BYTES) + } + + /** The bytes of [block], read into the cache if they are not there. Call with the lock held. */ + private fun blockBytes(block: Int): ByteBuffer { + val bytes = + blocks[block] ?: run { + val buffer = if (blocks.size < MAX_BLOCKS) { + allocatedReadBuffers++ + ByteBuffer.allocate(BLOCK_BYTES).order(ByteOrder.LITTLE_ENDIAN) + } else { + // Reuse the eldest block's bytes. Allocating another + // 40 KiB array at every miss churns Android's large-object heap. + val iterator = blocks.entries.iterator() + val reusable = iterator.next().value + iterator.remove() + reusable.clear() + reusable + } + val start = HEADER_BYTES + block.toLong() * BLOCK_BYTES + val count = minOf(BLOCK_BYTES.toLong(), channel.size() - start).toInt() + if (count < RECORD_BYTES) throw EOFException("Truncated circle cache") + buffer.limit(count) + var at = start + while (buffer.hasRemaining()) { + val n = channel.read(buffer, at) + if (n <= 0) throw EOFException("Truncated circle cache") + at += n + } + buffer.flip() + blocks[block] = buffer + buffer + } + return bytes + } + + fun write( + size: Int, + itemAt: (Int) -> TileCircle?, + order: StorageOrder?, + checkCancelled: () -> Unit, + ): Float { + val header = + ByteBuffer + .allocate(HEADER_BYTES) + .order(ByteOrder.LITTLE_ENDIAN) + .putInt(MAGIC) + .putInt(1) + .putInt(size) + .putInt(RECORD_BYTES) + header.flip() + while (header.hasRemaining()) channel.write(header) + val bytes = ByteBuffer.allocate(BLOCK_BYTES).order(ByteOrder.LITTLE_ENDIAN) + var widest = 0f + for (position in 0 until size) { + if (position % 4096 == 0) checkCancelled() + val item = itemAt(order?.indexAt?.get(position) ?: position) + encode(bytes, bytes.position(), item) + bytes.position(bytes.position() + RECORD_BYTES) + if (item != null) widest = max(widest, CircleTilePainter.strokeWidth(item)) + if (!bytes.hasRemaining()) { + bytes.flip() + while (bytes.hasRemaining()) channel.write(bytes) + bytes.clear() + } + } + bytes.flip() + while (bytes.hasRemaining()) channel.write(bytes) + return widest + } + + /** [updates] by stored position. */ + @Synchronized fun patch( + updates: List>, + size: Int, + ) { + check(references == 1) // Only an unpublished freshly compacted file may be written. + val bytes = ByteBuffer.allocate(RECORD_BYTES).order(ByteOrder.LITTLE_ENDIAN) + for ((position, item) in updates) { + if (position in 0 until size) { + bytes.clear() + encode(bytes, 0, item) + var at = HEADER_BYTES + position.toLong() * RECORD_BYTES + while (bytes.hasRemaining()) { + val n = channel.write(bytes, at) + check(n > 0) + at += n + } + } + } + blocks.clear() + } + } + + @InternalMapConductorApi + companion object { + private const val MAGIC = 0x5243434d // MCCR, little endian + private const val HEADER_BYTES = 16 + private const val RECORD_BYTES = 80 + private const val RECORDS_PER_BLOCK = 512 + private const val BLOCK_BYTES = RECORD_BYTES * RECORDS_PER_BLOCK + internal const val MAX_BLOCKS = 48 // At most 1.875 MiB per open geometry file. + private const val MAX_OVERRIDES = 2048 + private val liveFiles = HashSet() + + /** [order]: the order to store them in (see the class); index order when null. */ + fun create( + directory: File, + size: Int, + itemAt: (Int) -> TileCircle?, + checkCancelled: () -> Unit = { + }, + order: StorageOrder? = null, + ): CircleTileFileStorage { + require(order == null || order.indexAt.size == size) + require(size >= 0) + val path = + synchronized(liveFiles) { + check(directory.isDirectory || directory.mkdirs()) { "Cannot create circle cache directory" } + // These are disposable private cache files, not user data. Open + // files from this process stay registered until their last reader exits. + directory + .listFiles() + ?.filter { + it.name.startsWith("circle-geometry-") && + it.name.endsWith(".bin") && + it.absolutePath !in liveFiles + }?.forEach { it.delete() } + File.createTempFile("circle-geometry-", ".bin", directory).also { liveFiles.add(it.absolutePath) } + } + var file: SharedFile? = null + try { + file = SharedFile(path) + val widest = file.write(size, itemAt, order, checkCancelled) + return CircleTileFileStorage(file, size, widest, order) + } catch (error: Throwable) { + if (file != + null + ) { + file.dispose() + } else { + synchronized(liveFiles) { + liveFiles.remove(path.absolutePath) + path.delete() + } + } + throw error + } + } + + private fun encode( + bytes: ByteBuffer, + p: Int, + item: TileCircle?, + ) { + if (item == null) { + bytes.putInt(p + 76, 0) + return + } + bytes + .putDouble(p, item.latitude) + .putDouble(p + 8, item.longitude) + .putDouble(p + 16, item.radiusMeters) + .putDouble(p + 24, item.x) + .putDouble(p + 32, item.y) + .putDouble(p + 40, item.halfWidth) + .putDouble(p + 48, item.northY) + .putDouble(p + 56, item.southY) + .putInt(p + 64, item.fill) + .putInt(p + 68, item.stroke) + .putFloat(p + 72, item.strokeWidth) + .putInt(p + 76, if (item.geodesic) 3 else 1) + } + + private fun decode( + bytes: ByteBuffer, + p: Int, + ): TileCircle? { + val flags = bytes.getInt(p + 76) + if (flags and 1 == 0) return null + val x = bytes.getDouble(p + 24) + val half = bytes.getDouble(p + 40) + val north = bytes.getDouble(p + 48) + val south = bytes.getDouble(p + 56) + return TileCircle( + bytes.getDouble(p), bytes.getDouble(p + 8), bytes.getDouble(p + 16), flags and 2 != 0, + x, bytes.getDouble(p + 32), half, north, south, doubleArrayOf(x - half, north, x + half, south), + bytes.getInt(p + 64), bytes.getInt(p + 68), bytes.getFloat(p + 72), + ) + } + } +} diff --git a/src/main/java/com/mapconductor/core/circle/CircleTileGeometry.kt b/src/main/java/com/mapconductor/core/circle/CircleTileGeometry.kt new file mode 100644 index 0000000..73dca59 --- /dev/null +++ b/src/main/java/com/mapconductor/core/circle/CircleTileGeometry.kt @@ -0,0 +1,548 @@ +package com.mapconductor.core.circle + +import androidx.compose.ui.graphics.toArgb +import com.mapconductor.core.InternalMapConductorApi +import com.mapconductor.core.calculateZIndex +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.geometry.DEFAULT_CIRCLE_SEGMENTS +import com.mapconductor.core.geometry.circleToRing +import com.mapconductor.core.normalizeLng +import com.mapconductor.core.polygon.MIN_OUTLINED_PX +import com.mapconductor.core.polygon.isVisibleColor +import com.mapconductor.core.polygon.simplifyRing +import com.mapconductor.core.polygon.toMercatorRing +import com.mapconductor.core.projection.Earth +import com.mapconductor.core.shapetile.GlShapeScene +import com.mapconductor.core.shapetile.ShapeTileRenderer +import com.mapconductor.core.shapetile.ShapeTileStorage +import com.mapconductor.core.shapetile.toTilePixels +import java.util.BitSet +import kotlin.math.PI +import kotlin.math.abs +import kotlin.math.asin +import kotlin.math.cos +import kotlin.math.floor +import kotlin.math.ln +import kotlin.math.max +import kotlin.math.min +import kotlin.math.sin +import android.graphics.Canvas +import android.graphics.Path + +// The geometry of circle tiles: the same steps as the circle part of the +// "Shape tiles" section of js-sdk-core's tile-sw.js and ios-sdk-core's +// CircleTileGeometry, so the three platforms draw the same pixels from the +// same circles. +// +// A circle's radius is a distance on the ground, so unlike a line's width it +// grows on screen with the zoom: twice as many pixels at z+1. Its stroke is a +// width on screen, as the map SDKs draw it, the same at every zoom. +// +// Its box comes from the same formulas as the native 128-gon (circleToRing): +// the spherical circle for geodesic, the local plane round the centre's +// latitude otherwise. At each zoom it is one of three shapes: +// - Dot: under a pixel across, one whole pixel, as a polygon under a pixel is. +// - Arc: a true circle, when Mercator's stretch (the north half taller than +// the south) is a quarter of a pixel or less -- every city tree at every zoom. +// - Ring: otherwise (kilometres across, or far north) the native 128-gon in +// world pixels, snapped and simplified as a polygon's outline is. +// Taps never see any of this -- they are resolved against the original circle +// in CircleManager. + +private const val MAX_LATITUDE = 85.05112878 + +/** Under this radius on screen (in pixels) a circle is a single pixel. */ +private const val CIRCLE_DOT_RADIUS_PX = 0.5 + +/** Mercator's stretch (in pixels) up to which a circle is drawn as a true circle. */ +private const val CIRCLE_ARC_TOLERANCE_PX = 0.25 + +/** Web Mercator y in [0, 1] of [latitude], clamped as the shape tiles clamp it. */ +private fun mercatorY(latitude: Double): Double { + val lat = latitude.coerceIn(-MAX_LATITUDE, MAX_LATITUDE) + val s = sin(lat * PI / 180.0) + return 0.5 - ln((1 + s) / (1 - s)) / (4 * PI) +} + +/** + * The latitude and longitude extent of a circle, in degrees: what the native + * 128-gon spans. [dLng] is the half-width east and west of the centre. + */ +@InternalMapConductorApi +internal class CircleExtent( + val north: Double, + val south: Double, + val dLng: Double, + /** Whether a geodesic circle reaches over a pole (then [dLng] means nothing). */ + val overPole: Boolean, +) + +@InternalMapConductorApi +internal fun circleExtent( + latitude: Double, + radiusMeters: Double, + geodesic: Boolean, +): CircleExtent { + val phi = latitude * PI / 180.0 + if (geodesic) { + // Spherical.computeOffset: the angular distance on a sphere of Earth.RADIUS_METERS. + val delta = radiusMeters / Earth.RADIUS_METERS + val deltaDeg = delta * 180.0 / PI + val overPole = sin(delta) >= cos(phi) + val dLng = if (overPole) 180.0 else asin(min(1.0, sin(delta) / cos(phi))) * 180.0 / PI + return CircleExtent(latitude + deltaDeg, latitude - deltaDeg, dLng, overPole) + } + // circleToRing's local plane round the centre's latitude. + val metersPerDegree = Earth.CIRCUMFERENCE_METERS / 360.0 + val dLat = radiusMeters / metersPerDegree + val dLng = radiusMeters / (metersPerDegree * max(cos(phi), 1e-6)) + return CircleExtent(latitude + dLat, latitude - dLat, dLng, false) +} + +/** + * One circle as the tiles draw it. + * + * [x], [y] is the centre in Web Mercator [0, 1]; [halfWidth] the east-west + * radius and [northY], [southY] the top and bottom, all in the same units. + * [strokeWidth] is in dp, the unit of [CircleState.strokeWidth], which is also + * the tile unit. + */ +@InternalMapConductorApi +internal class TileCircle( + val latitude: Double, + val longitude: Double, + val radiusMeters: Double, + val geodesic: Boolean, + val x: Double, + val y: Double, + val halfWidth: Double, + val northY: Double, + val southY: Double, + /** minX, minY, maxX, maxY. */ + val bbox: DoubleArray, + val fill: Int, + val stroke: Int, + val strokeWidth: Float, +) { + fun matches(state: CircleState): Boolean = + latitude == state.center.latitude && longitude == normalizeLng(state.center.longitude) && + radiusMeters == state.radiusMeters && geodesic == state.geodesic && + fill == state.fillColor.toArgb() && stroke == state.strokeColor.toArgb() && + strokeWidth == state.strokeWidth.value + + // The spherical 128-gon is independent of zoom. Keep it once per immutable + // circle rather than repeating trig and projection at every new zoom. + val mercatorRing: DoubleArray + get() = synchronized(ringCache) { + ringCache[this] ?: toMercatorRing(circleToRing(GeoPoint.fromLatLong(latitude, longitude), radiusMeters, geodesic, DEFAULT_CIRCLE_SEGMENTS)).also { + ringCache[this] = it + } + } + + val fillVisible: Boolean get() = isVisibleColor(fill) + val strokeVisible: Boolean get() = strokeWidth > 0f && isVisibleColor(stroke) + + @InternalMapConductorApi + companion object { + // Nationwide circles must not retain a 128-vertex ring per station. + private val ringCache = object : LinkedHashMap(4096, 0.75f, true) { + override fun removeEldestEntry(eldest: MutableMap.MutableEntry?): Boolean = size > 4096 + } + /** Null when the circle cannot be drawn in a tile (see [CircleTileSet.canTile]). */ + fun from(state: CircleState): TileCircle? { + if (!CircleTileSet.canTile(state)) return null + val lat = state.center.latitude + val lng = normalizeLng(state.center.longitude) + val extent = circleExtent(lat, state.radiusMeters, state.geodesic) + val x = (lng + 180.0) / 360.0 + val y = mercatorY(lat) + val halfWidth = extent.dLng / 360.0 + val northY = mercatorY(extent.north) + val southY = mercatorY(extent.south) + return TileCircle( + latitude = lat, + longitude = lng, + radiusMeters = state.radiusMeters, + geodesic = state.geodesic, + x = x, + y = y, + halfWidth = halfWidth, + northY = northY, + southY = southY, + bbox = doubleArrayOf(x - halfWidth, northY, x + halfWidth, southY), + fill = state.fillColor.toArgb(), + stroke = state.strokeColor.toArgb(), + strokeWidth = state.strokeWidth.value, + ) + } + } +} + +/** What one circle looks like at one zoom, in world pixels. */ +@InternalMapConductorApi +internal sealed class CircleTileShape { + /** Under a pixel across: the pixel at [x], [y] (its top-left corner). */ + @InternalMapConductorApi + class Dot( + val x: Double, + val y: Double, + ) : CircleTileShape() + + /** A true circle round [cx], [cy]. */ + @InternalMapConductorApi + class Arc( + val cx: Double, + val cy: Double, + val radius: Double, + val outlined: Boolean, + ) : CircleTileShape() + + /** The native 128-gon, snapped and simplified, `[x0, y0, ...]`. */ + @InternalMapConductorApi + class Ring( + val points: DoubleArray, + val outlined: Boolean, + ) : CircleTileShape() +} + +/** The circle as drawn at a zoom whose world is [scale] pixels wide; never nothing. */ +@InternalMapConductorApi +internal fun simplifyCircle( + c: TileCircle, + scale: Double, +): CircleTileShape { + val cx = c.x * scale + val cy = c.y * scale + val rx = c.halfWidth * scale + val ryN = (c.y - c.northY) * scale + val ryS = (c.southY - c.y) * scale + val maxR = max(rx, max(ryN, ryS)) + if (maxR < CIRCLE_DOT_RADIUS_PX) return CircleTileShape.Dot(floor(cx), floor(cy)) + val outlined = 2 * maxR >= MIN_OUTLINED_PX + if (max(abs(ryN - rx), abs(ryS - rx)) <= CIRCLE_ARC_TOLERANCE_PX) { + return CircleTileShape.Arc(cx, cy, rx, outlined) + } + val simplified = simplifyRing(c.mercatorRing, scale) ?: return CircleTileShape.Arc(cx, cy, rx, outlined) + return CircleTileShape.Ring(simplified, outlined) +} + +/** The order circles are drawn in, as the native renderers stack them: an unset zIndex is the automatic one. */ +@InternalMapConductorApi +internal fun effectiveZIndex(state: CircleState): Int = state.zIndex ?: calculateZIndex(state.center) + +/** + * How a circle is drawn in a shape tile: filled, then outlined with the stroke + * centred on the edge (half of it outside), as the map SDKs draw it. A circle + * under [MIN_OUTLINED_PX] across has no outline; one under a pixel is a pixel. + */ +@InternalMapConductorApi +internal object CircleTilePainter : ShapeTileRenderer.Painter { + override val cacheSimplifiedShapes: Boolean get() = false + override val thinSubpixelOverlaps: Boolean get() = true + override fun isVisible(item: TileCircle): Boolean = item.fillVisible || item.strokeVisible + override fun subpixelSlot(item: TileCircle, scale: Double, originX: Double, originY: Double, tileSize: Int): Int { + val radius = max(item.halfWidth, max(item.y - item.northY, item.southY - item.y)) * scale + if (radius >= CIRCLE_DOT_RADIUS_PX) return -2 + val x = floor(item.x * scale) - originX + val y = floor(item.y * scale) - originY + return if (x >= 0 && x < tileSize && y >= 0 && y < tileSize) y.toInt() * tileSize + x.toInt() else -1 + } + + override fun bbox(item: TileCircle): DoubleArray = item.bbox + + override fun strokeWidth(item: TileCircle): Float = if (item.strokeVisible) item.strokeWidth else 0f + + override fun simplify( + item: TileCircle, + scale: Double, + ): Any = simplifyCircle(item, scale) + + override fun draw( + canvas: Canvas, + item: TileCircle, + shape: Any, + originX: Double, + originY: Double, + r: Float, + paints: ShapeTileRenderer.Paints, + ): Boolean { + val fillVisible = item.fillVisible + val strokeVisible = item.strokeVisible + if (!fillVisible && !strokeVisible) return false + when (shape) { + is CircleTileShape.Dot -> { + paints.dot.color = if (fillVisible) item.fill else item.stroke + val left = ((shape.x - originX) * r).toFloat() + val top = ((shape.y - originY) * r).toFloat() + canvas.drawRect(left, top, left + r, top + r, paints.dot) + return true + } + is CircleTileShape.Arc -> { + val cx = ((shape.cx - originX) * r).toFloat() + val cy = ((shape.cy - originY) * r).toFloat() + val radius = (shape.radius * r).toFloat() + var drew = false + if (fillVisible) { + paints.fill.color = item.fill + canvas.drawCircle(cx, cy, radius, paints.fill) + drew = true + } + if (strokeVisible && shape.outlined) { + paints.stroke.color = item.stroke + paints.stroke.strokeWidth = item.strokeWidth * r + canvas.drawCircle(cx, cy, radius, paints.stroke) + drew = true + } + return drew + } + is CircleTileShape.Ring -> { + val path = paints.path + path.rewind() + path.fillType = Path.FillType.WINDING + val p = shape.points + path.moveTo(((p[0] - originX) * r).toFloat(), ((p[1] - originY) * r).toFloat()) + var i = 2 + while (i < p.size) { + path.lineTo(((p[i] - originX) * r).toFloat(), ((p[i + 1] - originY) * r).toFloat()) + i += 2 + } + path.close() + var drew = false + if (fillVisible) { + paints.fill.color = item.fill + canvas.drawPath(path, paints.fill) + drew = true + } + if (strokeVisible && shape.outlined) { + paints.stroke.color = item.stroke + paints.stroke.strokeWidth = item.strokeWidth * r + canvas.drawPath(path, paints.stroke) + drew = true + } + return drew + } + else -> return false + } + } + + override val drawsOnGpu: Boolean get() = true + + /** + * The circles of a file-backed set, read straight from the file's bytes + * ([CircleTileFileStorage.forEachRecord]): decoding a [TileCircle] per + * circle took about 3.5 µs, seconds for a tile of a nationwide set, against + * milliseconds to draw them. The same steps as [subpixelSlot], [simplifyCircle] + * and [record]; a circle bent into its 128-gon throws [GlShapeScene.NeedsBatches]. + */ + override fun recordAll( + scene: GlShapeScene, + storage: ShapeTileStorage, + candidates: IntArray, + active: BitSet?, + scale: Double, + originX: Double, + originY: Double, + tileSize: Int, + r: Float, + checkCancelled: () -> Unit, + ): Boolean { + if (storage !is CircleTileFileStorage) return false + fun slotOf(x: Double, y: Double, half: Double, north: Double, south: Double): Int { + val radius = max(half, max(y - north, south - y)) * scale + if (radius >= CIRCLE_DOT_RADIUS_PX) return -2 + val px = floor(x * scale) - originX + val py = floor(y * scale) - originY + return if (px >= 0 && px < tileSize && py >= 0 && py < tileSize) py.toInt() * tileSize + px.toInt() else -1 + } + val lastDot = IntArray(tileSize * tileSize) + storage.forEachRecord(candidates, checkCancelled) { k, bytes, p, override -> + val index = candidates[k] + if (active != null && !active[index]) return@forEachRecord + if (bytes == null) { + val item = override ?: return@forEachRecord + if (!isVisible(item)) return@forEachRecord + val slot = subpixelSlot(item, scale, originX, originY, tileSize) + // The pixel keeps the circle drawn last; calls come in storage order. + if (slot >= 0 && index + 1 > lastDot[slot]) lastDot[slot] = index + 1 + return@forEachRecord + } + if (bytes.getInt(p + 76) and 1 == 0) return@forEachRecord + val fill = bytes.getInt(p + 64) + val stroke = bytes.getInt(p + 68) + val strokeWidth = bytes.getFloat(p + 72) + if (!isVisibleColor(fill) && !(strokeWidth > 0f && isVisibleColor(stroke))) return@forEachRecord + val slot = slotOf(bytes.getDouble(p + 24), bytes.getDouble(p + 32), bytes.getDouble(p + 40), bytes.getDouble(p + 48), bytes.getDouble(p + 56)) + if (slot >= 0 && index + 1 > lastDot[slot]) lastDot[slot] = index + 1 + } + // Gathered, then added in draw order (k): the calls come in storage order. + val deferred = DeferredCircles() + storage.forEachRecord(candidates, checkCancelled) { k, bytes, p, override -> + val index = candidates[k] + if (active != null && !active[index]) return@forEachRecord + if (bytes == null) { + val item = override ?: return@forEachRecord + val slot = subpixelSlot(item, scale, originX, originY, tileSize) + if (slot == -1 || (slot >= 0 && lastDot[slot] != index + 1)) return@forEachRecord + deferred.addItem(k, item) + return@forEachRecord + } + if (bytes.getInt(p + 76) and 1 == 0) return@forEachRecord + val x = bytes.getDouble(p + 24) + val y = bytes.getDouble(p + 32) + val half = bytes.getDouble(p + 40) + val north = bytes.getDouble(p + 48) + val south = bytes.getDouble(p + 56) + val slot = slotOf(x, y, half, north, south) + if (slot == -1 || (slot >= 0 && lastDot[slot] != index + 1)) return@forEachRecord + val fill = bytes.getInt(p + 64) + val stroke = bytes.getInt(p + 68) + val strokeWidth = bytes.getFloat(p + 72) + val fillVisible = isVisibleColor(fill) + val strokeVisible = strokeWidth > 0f && isVisibleColor(stroke) + if (!fillVisible && !strokeVisible) return@forEachRecord + val cx = x * scale + val cy = y * scale + val rx = half * scale + val ryN = (y - north) * scale + val ryS = (south - y) * scale + val maxR = max(rx, max(ryN, ryS)) + if (maxR < CIRCLE_DOT_RADIUS_PX) { + deferred.add( + k, ((floor(cx) - originX) * r).toFloat(), ((floor(cy) - originY) * r).toFloat(), r, r, + if (fillVisible) fill else stroke, 0, kind = 1, + ) + return@forEachRecord + } + // Bent by the projection: its 128-gon, which the batched scene draws. + if (max(abs(ryN - rx), abs(ryS - rx)) > CIRCLE_ARC_TOLERANCE_PX) throw GlShapeScene.NeedsBatches() + val outlined = strokeVisible && 2 * maxR >= MIN_OUTLINED_PX + if (!fillVisible && !outlined) return@forEachRecord + deferred.add( + k, ((cx - originX) * r).toFloat(), ((cy - originY) * r).toFloat(), (rx * r).toFloat(), + if (outlined) strokeWidth * r else 0f, + if (fillVisible) fill else 0, if (outlined) stroke else 0, kind = 0, + ) + } + checkCancelled() + deferred.addTo(scene) { item -> record(scene, item, simplifyCircle(item, scale), originX, originY, r) } + return true + } + + override fun record( + scene: GlShapeScene, + item: TileCircle, + shape: Any, + originX: Double, + originY: Double, + r: Float, + ): Boolean { + val fillVisible = item.fillVisible + val strokeVisible = item.strokeVisible + if (!fillVisible && !strokeVisible) return false + when (shape) { + is CircleTileShape.Dot -> { + val left = ((shape.x - originX) * r).toFloat() + val top = ((shape.y - originY) * r).toFloat() + scene.addCircle(left, top, r, r, if (fillVisible) item.fill else item.stroke, 0, kind = 1) + return true + } + is CircleTileShape.Arc -> { + val outlined = strokeVisible && shape.outlined + if (!fillVisible && !outlined) return false + scene.addCircle( + ((shape.cx - originX) * r).toFloat(), + ((shape.cy - originY) * r).toFloat(), + (shape.radius * r).toFloat(), + if (outlined) item.strokeWidth * r else 0f, + if (fillVisible) item.fill else 0, + if (outlined) item.stroke else 0, + kind = 0, + ) + return true + } + is CircleTileShape.Ring -> { + val outlined = strokeVisible && shape.outlined + if (!fillVisible && !outlined) return false + scene.addPolygon( + listOf(toTilePixels(shape.points, originX, originY, r)), + fill = if (fillVisible) item.fill else 0, + outline = if (outlined) item.stroke else 0, + strokeWidth = item.strokeWidth * r, + ) + return true + } + else -> return false + } + } +} + +/** + * Circles of one tile gathered in storage order, to be added to the scene in + * draw order (`k`, their place among the tile's candidates). Primitive arrays: + * a zoomed-out tile has tens of thousands. + */ +@InternalMapConductorApi +private class DeferredCircles { + private var count = 0 + private var ks = IntArray(1024) + private var floats = FloatArray(1024 * 4) + private var ints = IntArray(1024 * 3) + private val items = ArrayList>() + + fun add( + k: Int, + x: Float, + y: Float, + a: Float, + b: Float, + fill: Int, + stroke: Int, + kind: Int, + ) { + if (count == ks.size) { + ks = ks.copyOf(count * 2) + floats = floats.copyOf(count * 8) + ints = ints.copyOf(count * 6) + } + ks[count] = k + floats[count * 4] = x + floats[count * 4 + 1] = y + floats[count * 4 + 2] = a + floats[count * 4 + 3] = b + ints[count * 3] = fill + ints[count * 3 + 1] = stroke + ints[count * 3 + 2] = kind + count++ + } + + /** An overriding circle: recorded through the painter when its turn comes. */ + fun addItem( + k: Int, + item: TileCircle, + ) { + items.add(k to item) + } + + /** Adds them to [scene] by k; [recordItem] records the overriding circles in their turn. */ + fun addTo( + scene: GlShapeScene, + recordItem: (TileCircle) -> Unit, + ) { + // k (high half) and which entry (low half; the overriding circles after the others). + val order = LongArray(count + items.size) + for (i in 0 until count) order[i] = (ks[i].toLong() shl 32) or i.toLong() + for ((j, entry) in items.withIndex()) order[count + j] = (entry.first.toLong() shl 32) or (count + j).toLong() + order.sort() + for (key in order) { + val i = key.toInt() + if (i >= count) { + recordItem(items[i - count].second) + continue + } + scene.addCircle( + floats[i * 4], floats[i * 4 + 1], floats[i * 4 + 2], floats[i * 4 + 3], + ints[i * 3], ints[i * 3 + 1], kind = ints[i * 3 + 2], + ) + } + } +} diff --git a/src/main/java/com/mapconductor/core/circle/CircleTileSet.kt b/src/main/java/com/mapconductor/core/circle/CircleTileSet.kt new file mode 100644 index 0000000..9675782 --- /dev/null +++ b/src/main/java/com/mapconductor/core/circle/CircleTileSet.kt @@ -0,0 +1,128 @@ +package com.mapconductor.core.circle + +import com.mapconductor.core.ResourceProvider +import com.mapconductor.core.normalizeLng +import com.mapconductor.core.shapetile.ShapeTileRenderer +import com.mapconductor.core.shapetile.ShapeTileSet +import com.mapconductor.core.shapetile.StorageOrder +import com.mapconductor.core.tileserver.LocalTileServer +import com.mapconductor.core.tileserver.TileServerRegistry +import java.io.File +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.ensureActive + +/** + * The circles of one map that are drawn as raster tiles, and their route on + * the local tile server. + * + * Provider-independent: a provider decides which circles to tile + * ([CircleTilingOptions.shouldUseTiles], [canTile]), hands them to + * [setCircles], and shows the returned URL template as a raster layer. + * In-place changes go through [update]; each one ends in a new template (the + * version in it is what makes the map ask again), reported to + * [onTemplateChanged]. Tiles the change did not touch are still cached by the + * renderer and come back without being drawn again. + * + * The same as [com.mapconductor.core.polyline.PolylineTileSet] for circles: + * both are [ShapeTileSet]s, with their own route, version and tile cache. + * Same shape as js-sdk-core's and ios-sdk-core's `CircleTileSet`. + */ +class CircleTileSet( + server: LocalTileServer = TileServerRegistry.get(), + scope: CoroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Default), +) { + internal val renderer: ShapeTileRenderer = + ShapeTileRenderer(tileSize = TILE_SIZE, painter = CircleTilePainter) + + internal val shapes: ShapeTileSet = + ShapeTileSet( + routePrefix = "circles", + server = server, + scope = scope, + renderer = renderer, + idOf = { it.id }, + // The native renderers stack an unset zIndex by the automatic one; so do the tiles. + zIndexOf = ::effectiveZIndex, + toTile = TileCircle::from, + canReuse = { state, tile -> tile.matches(state) }, + createStorage = { states -> + if (states.size <= 2000) { + null + } else { + val context = currentCoroutineContext() + val root = + runCatching { ResourceProvider.getAppContext().cacheDir } + .getOrElse { File(System.getProperty("java.io.tmpdir")) } + // Stored by place, so that a tile reads the few blocks round it. + val order = + StorageOrder.sortedBy(states.size) { + val center = states[it].center + StorageOrder.mortonCellKey(center.latitude, normalizeLng(center.longitude)) + } + CircleTileFileStorage.create( + File(root, "mapconductor-circle-geometry"), states.size, + { TileCircle.from(states[it]) }, { context.ensureActive() }, order, + ) + } + }, + ) + + val routeId: String get() = shapes.routeId + + /** Called with the new template after an [update] or [remove]. */ + var onTemplateChanged: (suspend (String) -> Unit)? + get() = shapes.onTemplateChanged + set(value) { + shapes.onTemplateChanged = value + } + + val tileSize: Int get() = TILE_SIZE + + /** + * Registers [states] (replacing whatever was registered) and returns the + * URL template of their tiles. Draw order is the effective zIndex (an + * unset one is the automatic one from the centre), then the order given. + */ + suspend fun setCircles(states: List): String = shapes.setShapes(states) + + fun has(id: String): Boolean = shapes.has(id) + + /** + * One circle changed in place. A change of zIndex reorders the list and + * needs [setCircles] instead; everything else is applied here. + */ + fun update(state: CircleState) = shapes.update(state) + + /** Takes one circle out of the tiles. Only the tiles it was in are drawn again. */ + fun remove(id: String) = shapes.remove(id) + + fun template(): String = shapes.template() + + fun dispose() = shapes.dispose() + + companion object { + private const val TILE_SIZE = 256 + private const val MAX_LATITUDE = 85.05112878 + + /** + * Whether a circle can be drawn in a tile. One with no radius, or one + * that reaches a pole, the edge of the Mercator world or the + * antimeridian, is drawn by the map SDK. Geodesic or not, the rest can. + */ + fun canTile(state: CircleState): Boolean { + val radius = state.radiusMeters + if (!(radius > 0.0) || !radius.isFinite()) return false + val lat = state.center.latitude + val lngRaw = state.center.longitude + if (!lat.isFinite() || !lngRaw.isFinite()) return false + val extent = circleExtent(lat, radius, state.geodesic) + if (extent.overPole) return false + if (extent.north >= MAX_LATITUDE || extent.south <= -MAX_LATITUDE) return false + val lng = normalizeLng(lngRaw) + return lng - extent.dLng > -180.0 && lng + extent.dLng < 180.0 + } + } +} diff --git a/src/main/java/com/mapconductor/core/circle/CircleTiler.kt b/src/main/java/com/mapconductor/core/circle/CircleTiler.kt new file mode 100644 index 0000000..9342581 --- /dev/null +++ b/src/main/java/com/mapconductor/core/circle/CircleTiler.kt @@ -0,0 +1,136 @@ +package com.mapconductor.core.circle + +import com.mapconductor.core.normalizeLng +import com.mapconductor.core.raster.RasterLayerSource +import com.mapconductor.core.raster.RasterLayerState +import com.mapconductor.core.shapetile.ShapeTiler +import com.mapconductor.core.projection.Earth +import kotlin.math.PI +import kotlin.math.cos +import kotlin.math.ln +import kotlin.math.max +import kotlin.math.sin + +/** The id of the raster layer that shows tiled circles. */ +const val CIRCLE_TILE_LAYER_ID: String = "mc-circle-tiles" + +/** The raster layer state for tiled circles at [template]. */ +fun circleTileRasterLayerState( + template: String, + tileSize: Int = 256, +): RasterLayerState = + RasterLayerState( + id = CIRCLE_TILE_LAYER_ID, + source = RasterLayerSource.UrlTemplate(template = template, tileSize = tileSize), + ) + +/** + * Decides which of a map's circles are drawn as tiles, keeps them registered + * with the local tile server, and tells the provider where the tiles are. + * Used exactly as [com.mapconductor.core.polyline.PolylineTiler]: + * + * 1. [route] with the full list on every composition. It returns the ids now + * in tiles; the controller keeps those in its [CircleManager] (taps are + * resolved there, against the original circles) but gives the map SDK + * nothing for them, and removes any native circle it had drawn for one. + * 2. [update] for an in-place change of a tiled circle, or [remove] when the + * change means it can no longer be tiled (it moved onto the antimeridian, + * say). + * 3. [onTemplate] is how the tiles reach the map: a URL template to show as a + * raster layer, or null to remove it. A provider with a RasterLayer + * controller hands [circleTileRasterLayerState] to its `upsert`, and + * removes it with `removeById(CIRCLE_TILE_LAYER_ID)`. The layer belongs to + * the circle band: over polygons (and their tiles), under native circles, + * polylines (and their tiles) and markers. + * + * [options] is read at every [route]: setting it decides again the next time + * the circles are handed over. + * + * Same as js-sdk-core's and ios-sdk-core's `CircleTiler`. + */ +class CircleTiler( + options: CircleTilingOptions = CircleTilingOptions.Default, +) { + @Volatile + var options: CircleTilingOptions = options + + var onTemplate: (suspend (template: String?, tileSize: Int) -> Unit)? = null + + private val tileSet = CircleTileSet() + + private val tiler = + ShapeTiler( + tileSet = tileSet.shapes, + canTile = CircleTileSet::canTile, + vertexCount = { 0 }, + shouldUseTiles = { count, _ -> this.options.shouldUseTiles(count) }, + idOf = { it.id }, + onTemplate = { template, tileSize -> onTemplate?.invoke(template, tileSize) }, + ) + + /** Re-decides tiling for [data] and returns the ids drawn as tiles. */ + suspend fun route(data: List): Set = tiler.route(data) + + /** The states drawn as tiles, as of the last [route]. */ + fun tiledStates(): List = tiler.tiledStates() + + fun isTiled(id: String): Boolean = tiler.isTiled(id) + + internal fun state(id: String): CircleState? = tileSet.shapes.source(id) + internal fun visitStates(action: (CircleState) -> Unit) = tileSet.shapes.visitSources(action) + + /** + * The tiled circles a tap at [latitude]/[longitude] can hit: those whose + * extent (the box the tiles index them by) comes within reach of the point. + * Found through the tiles' index, so a tap reads a handful of states, not + * every one; [CircleManager.find] then decides on those states as before. + * + * The reach allows for half the widest stroke (pixels, at [metersPerPixel]; + * at least [TAP_STROKE_SLACK_PX], since a stroke that is not drawn, such as a + * transparent one, still counts for a tap) plus [TAP_SLACK_METERS], for a + * planar circle's box (along the parallel) against the great-circle distance + * the tap is decided with. + */ + internal fun states( + latitude: Double, + longitude: Double, + metersPerPixel: Double, + ): List { + val lat = latitude.coerceIn(-MAX_LATITUDE, MAX_LATITUDE) + val s = sin(lat * PI / 180.0) + val x = (normalizeLng(longitude) + 180.0) / 360.0 + val y = 0.5 - ln((1 + s) / (1 - s)) / (4 * PI) + // Mercator units per metre at this latitude. + val perMeter = 1.0 / (Earth.CIRCUMFERENCE_METERS * max(cos(lat * PI / 180.0), 1e-6)) + val stroke = max(TAP_STROKE_SLACK_PX, tileSet.shapes.maxStroke.toDouble()) + val pad = (metersPerPixel * stroke / 2.0 + TAP_SLACK_METERS) * perMeter + return tileSet.shapes.sources(x - pad, y - pad, x + pad, y + pad) + } + + /** An in-place change of a tiled circle; only the tiles it touches are drawn again. */ + fun update(state: CircleState) = tiler.update(state) + + /** + * Takes one circle out of the tiles, for a change that left it no longer + * [CircleTileSet.canTile]; only the tiles it was in are drawn again. The + * controller then hands it to the map SDK. + */ + fun remove(id: String) = tiler.remove(id) + + /** + * Releases the tiles when the map goes away. Unlike [clear], it does not + * call [onTemplate]: there is no map left to remove the layer from. + */ + fun dispose() = tiler.dispose() + + suspend fun clear() = tiler.clear() + + /** The tile set, for tests that look at the pixels. */ + internal val tiles: CircleTileSet get() = tileSet + + private companion object { + const val MAX_LATITUDE = 85.05112878 + const val TAP_STROKE_SLACK_PX = 64.0 + const val TAP_SLACK_METERS = 100.0 + } +} diff --git a/src/main/java/com/mapconductor/core/circle/CircleTilingOptions.kt b/src/main/java/com/mapconductor/core/circle/CircleTilingOptions.kt new file mode 100644 index 0000000..492fd95 --- /dev/null +++ b/src/main/java/com/mapconductor/core/circle/CircleTilingOptions.kt @@ -0,0 +1,28 @@ +package com.mapconductor.core.circle + +/** + * Options for circle tiling. + * + * When enabled and a map holds enough circles, they are drawn into raster + * tiles by the SDK's local tile server instead of being handed to the map SDK + * one by one. Taps are still resolved against the original circles in + * [CircleManager], so tiling changes how circles look, never what a tap hits. + * + * The counterpart of [com.mapconductor.core.polygon.PolygonTilingOptions] and + * [com.mapconductor.core.polyline.PolylineTilingOptions], and the same options + * as js-sdk-core's and ios-sdk-core's `CircleTilingOptions`. A circle has no + * vertices to count, so the threshold is the number of circles alone. + */ +data class CircleTilingOptions( + val enabled: Boolean = true, + /** Tile once a map holds at least this many circles. */ + val minCircleCount: Int = 2001, +) { + /** The one place the threshold is decided; callers must not restate it. */ + fun shouldUseTiles(circleCount: Int): Boolean = enabled && circleCount >= minCircleCount + + companion object { + val Default: CircleTilingOptions = CircleTilingOptions() + val Disabled: CircleTilingOptions = CircleTilingOptions(enabled = false) + } +} diff --git a/src/main/java/com/mapconductor/core/controller/BaseMapViewController.kt b/src/main/java/com/mapconductor/core/controller/BaseMapViewController.kt index 6de43e1..7ff3bd3 100644 --- a/src/main/java/com/mapconductor/core/controller/BaseMapViewController.kt +++ b/src/main/java/com/mapconductor/core/controller/BaseMapViewController.kt @@ -4,7 +4,9 @@ import com.mapconductor.core.OnCameraMoveHandler import com.mapconductor.core.OnMapEventHandler import com.mapconductor.core.OnMapInitializedHandler import com.mapconductor.core.circle.CircleCapableInterface +import com.mapconductor.core.circle.CircleController import com.mapconductor.core.circle.CircleState +import com.mapconductor.core.circle.CircleTiler import com.mapconductor.core.circle.OnCircleEventHandler import com.mapconductor.core.features.GeoPoint import com.mapconductor.core.features.GeoPointInterface @@ -13,18 +15,26 @@ import com.mapconductor.core.groundimage.GroundImageState import com.mapconductor.core.groundimage.OnGroundImageEventHandler import com.mapconductor.core.map.CameraRestriction import com.mapconductor.core.map.MapCameraPosition +import com.mapconductor.core.map.MapDiagnostics import com.mapconductor.core.map.MapViewHolderInterface import com.mapconductor.core.marker.MarkerAnimationOverlayHost import com.mapconductor.core.marker.MarkerCapableInterface +import com.mapconductor.core.marker.MarkerDrawOrder +import com.mapconductor.core.marker.MarkerDrawOrderReceiver +import com.mapconductor.core.marker.MarkerDrawOrderTracker import com.mapconductor.core.marker.MarkerState import com.mapconductor.core.marker.OnMarkerEventHandler +import com.mapconductor.core.marker.StrategyMarkerController import com.mapconductor.core.polygon.OnPolygonEventHandler import com.mapconductor.core.polygon.PolygonCapableInterface import com.mapconductor.core.polygon.PolygonState import com.mapconductor.core.polyline.OnPolylineEventHandler import com.mapconductor.core.polyline.PolylineCapableInterface +import com.mapconductor.core.polyline.PolylineController import com.mapconductor.core.polyline.PolylineState +import com.mapconductor.core.polyline.PolylineTiler import com.mapconductor.core.raster.RasterLayerCapableInterface +import com.mapconductor.core.raster.RasterLayerController import com.mapconductor.core.raster.RasterLayerState import java.util.concurrent.CopyOnWriteArrayList import kotlin.math.abs @@ -47,6 +57,16 @@ abstract class BaseMapViewController : private var lastNotifiedCameraPosition: MapCameraPosition? = null abstract val mainCoroutine: CoroutineScope private val overlayControllers = CopyOnWriteArrayList>() + + /** + * 同じ zIndex のマーカーを地図の向きに合わせて並べ直させる(画面で下ほど手前)。 + * 回転が止まってから、登録されたマーカーのコントローラ全部へ一度だけ配る。 + */ + private val markerDrawOrder by lazy { + MarkerDrawOrderTracker(defaultCoroutine) { frame -> + overlayControllers.forEach { (it as? MarkerDrawOrderReceiver)?.onDrawOrderFrameChanged(frame) } + } + } protected var cameraMoveStartCallback: OnCameraMoveHandler? = null protected var cameraMoveCallback: OnCameraMoveHandler? = null protected var cameraMoveEndCallback: OnCameraMoveHandler? = null @@ -146,6 +166,11 @@ abstract class BaseMapViewController : override fun registerOverlayController(controller: OverlayControllerInterface<*, *>) { if (overlayControllers.contains(controller)) return overlayControllers.add(controller) + // 地図が回った後に登録されたら、今の向きで並べ直させる。 + val frame = markerDrawOrder.frame + if (controller is MarkerDrawOrderReceiver && frame != MarkerDrawOrder.Frame.NorthUp) { + defaultCoroutine.launch { controller.onDrawOrderFrameChanged(frame) } + } // 登録が初期カメラ確定より後になることがある(RN の拡張レンダラや遅延マウントの // クラスタリングなど)。ユーザー操作までカメライベントを出さないプロバイダ // (HERE)では次のイベントが永遠に来ず、「登録したのに一度も計算されない」型の @@ -156,6 +181,21 @@ abstract class BaseMapViewController : } } + /** + * 登録されている [StrategyMarkerController](クラスタリングなどの Strategy で描くマーカー)を + * すべて clear する。各プロバイダの `clearOverlays()` から呼ぶ。 + * + * Strategy のコントローラはプロバイダが持つものではなく、拡張モジュール + * (android-marker-clustering の MarkerRenderingGroup など)が + * [registerOverlayController] で登録していくもの。プロバイダの `clearOverlays()` は + * 自分のフィールドのコントローラしか知らないので、ここで登録簿から拾う。 + * + * 他の種類(ヒートマップのようにカメラだけ購読するもの)は消さない。 + */ + protected suspend fun clearStrategyMarkerControllers() { + overlayControllers.filterIsInstance>().forEach { it.clear() } + } + // ── タップのカスケード ────────────────────────────────────────────── // // marker → circle → groundImage → polyline → polygon → map の一本道。 @@ -262,11 +302,24 @@ abstract class BaseMapViewController : .filterIsInstance>() .filter { it.kind == kind } - /** [kind] のいずれかのコントローラがこの id を持っているか。`hasXxx` の既定実装。 */ + /** The tilers of this map's circle controllers, for [com.mapconductor.core.circle.CircleOverlay]'s per-map options. */ + internal fun circleTilers(): List = + overlayControllersOf(OverlayKind.Circle).mapNotNull { (it as? CircleController<*>)?.tiler } + + /** The tilers of this map's polyline controllers, for [com.mapconductor.core.polyline.PolylineOverlay]'s per-map options. */ + internal fun polylineTilers(): List = + overlayControllersOf(OverlayKind.Polyline).mapNotNull { (it as? PolylineController<*>)?.tiler } + + /** + * [kind] のいずれかのコントローラがこの id を持っているか。`hasXxx` の既定実装。 + * + * 一覧を作らずに直接なめる。composition のたびに全オーバーレイについて呼ばれる + * (`onAdded` の判定)ので、1 回ごとに 2 本のリストを作ると 10 万件で数百 ms になる。 + */ protected fun hasOverlay( kind: OverlayKind, id: String, - ): Boolean = overlayControllersOf(kind).any { it.has(id) } + ): Boolean = overlayControllers.any { it is SlottedOverlayController<*, *> && it.kind == kind && it.has(id) } // Marker override suspend fun compositionMarkers(data: List) { @@ -376,6 +429,105 @@ abstract class BaseMapViewController : override fun hasRasterLayer(state: RasterLayerState): Boolean = hasOverlay(OverlayKind.RasterLayer, state.id) + /** + * Adds or replaces a raster layer that is **not** part of the content + * block. + * + * `compositionRasterLayers` replaces the whole set with what the + * composition declared, so anything mounted from outside it would be + * swept away on the next recomposition. [RasterLayerController.upsert] + * keeps its ids out of that sweep, and this is how the two callers that + * need it get there: marker tiling, and a [MapViewStyle] on a backend + * that cannot draw a vector style and has to be handed tiles rendered + * from one. + * + * Provider-agnostic on purpose. The raster controller is already + * registered as an overlay controller by every provider, so this needs + * nothing per provider -- which is the difference between a seam that + * works on eleven backends and one that is wired on three. + */ + open fun mountRasterLayer(state: RasterLayerState) { + val controllers = rasterLayerControllers() + if (controllers.isEmpty()) { + noRasterMount(state.id) + return + } + mainCoroutine.launch { controllers.forEach { it.upsert(state) } } + } + + /** Takes off what [mountRasterLayer] put on. A layer that is not there is not an error. */ + open fun unmountRasterLayer(id: String) { + val controllers = rasterLayerControllers() + if (controllers.isEmpty()) return + mainCoroutine.launch { controllers.forEach { it.removeById(id) } } + } + + /** + * Says so when a provider has nowhere to mount one. + * + * Most providers reach their tiles through a [RasterLayerController] + * registered as an overlay controller, and get [mountRasterLayer] for + * free. TomTom and Longdo compose rasters into their own style instead + * and have no such controller, so they override the pair. A provider + * that does neither would otherwise show an empty map and say nothing, + * which is the failure this whole design is built against. + */ + private fun noRasterMount(id: String) { + MapDiagnostics.sink.log( + "raster layer $id was not mounted: this provider registers no RasterLayerController " + + "and does not override mountRasterLayer", + ) + } + + private fun rasterLayerControllers(): List> = + overlayControllersOf(OverlayKind.RasterLayer).filterIsInstance>() + + private val styleLoadedListeners = CopyOnWriteArrayList<() -> Unit>() + + /** + * Runs [block] every time this map finishes loading a style document, + * and once now if it already has one. + * + * Everything a [MapViewStyle] put on a live renderer -- paint + * properties, a layer it added -- is gone when that renderer loads a + * document again, for any reason: the app switching basemap, a design + * change, the provider rebuilding its view. This is how it goes back on, + * and it is a registry rather than one listener because both the + * mutation store and the style installation need to hear it. + * + * A provider that has no such thing (Google Maps, MapKit, HERE...) never + * calls [notifyStyleLoaded], and a style installed on it is one that was + * rasterised into tiles -- which survives a basemap change by itself. + * + * @return the ticket to stop listening. + */ + fun addStyleLoadedListener(block: () -> Unit): () -> Unit { + styleLoadedListeners.add(block) + if (styleLoaded) block() + return { styleLoadedListeners.remove(block) } + } + + /** + * Called by the provider once the map has a style up **and** the + * overlays are back on it. + * + * Not when the load starts, and not before the provider has put its own + * layers back: a listener that patches a style mid-rebuild patches + * something that is about to be replaced. + */ + protected fun notifyStyleLoaded() { + styleLoaded = true + styleLoadedListeners.forEach { it() } + } + + /** + * Whether a style document is up now. + * + * Sticky, like [mapInitialized] and for the same reason: a provider can + * finish loading before anything has asked to be told about it. + */ + private var styleLoaded = false + fun setMapInitializedListener(listener: OnMapInitializedHandler?) { this.mapInitializedCallback = listener deliverMapInitializedCallbackIfReady() @@ -402,6 +554,7 @@ abstract class BaseMapViewController : protected suspend fun notifyMapCameraPosition(mapCameraPosition: MapCameraPosition) { lastNotifiedCameraPosition = mapCameraPosition + markerDrawOrder.onCameraChanged(mapCameraPosition) overlayControllers.forEach { if (it is OnCameraChangeReceiverInterface) { it.onCameraChanged(mapCameraPosition) diff --git a/src/main/java/com/mapconductor/core/controller/OverlayKind.kt b/src/main/java/com/mapconductor/core/controller/OverlayKind.kt index 7a2dfc5..ac0bace 100644 --- a/src/main/java/com/mapconductor/core/controller/OverlayKind.kt +++ b/src/main/java/com/mapconductor/core/controller/OverlayKind.kt @@ -9,8 +9,9 @@ package com.mapconductor.core.controller * ジェネリクスは実行時に消えるので状態の型では判別できない。かといって `Class` を * 持たせると、状態型がプロバイダ固有になったときに破綻する。種別という別の軸で持つ。 * - * **描画順(zIndex)とは別軸**であることに注意。現状 polygon(3) > groundImage(2) だが、 - * クリックの探索は groundImage が先。 + * **描画順とは別軸**であることに注意。描画は [OverlayStacking] の帯 + * (ラスター < GroundImage < ポリゴン < サークル < ポリライン < マーカー)で決まるが、 + * クリックの探索は groundImage がポリゴンより先。 */ enum class OverlayKind { Marker, diff --git a/src/main/java/com/mapconductor/core/controller/OverlayStacking.kt b/src/main/java/com/mapconductor/core/controller/OverlayStacking.kt new file mode 100644 index 0000000..0046a16 --- /dev/null +++ b/src/main/java/com/mapconductor/core/controller/OverlayStacking.kt @@ -0,0 +1,134 @@ +package com.mapconductor.core.controller + +import kotlin.math.abs + +/** + * オーバーレイの重なり順(すべてのプロバイダ・3 プラットフォーム共通の決まり)。 + * + * 下から順に: + * 1. ラスターレイヤー(RasterLayerState、アプリが足すタイル) + * 2. GroundImage + * 3. ポリゴン(ネイティブのポリゴンと、SDK のポリゴンのタイルレイヤーが同じ帯) + * 4. サークル + * 5. ポリライン + * 6. マーカー(ネイティブのマーカーと、SDK のマーカーのタイルレイヤーが同じ帯) + * + * 帯の中は zIndex の小さい順、同じ zIndex なら後から渡したものが上。 + * 追加した順・送り直した順(clearOverlays の後など)・デザイン変更の後に左右されない。 + * + * ネイティブ SDK の重なりの持ち方は 2 通りあり、それぞれに 1 つずつ道具を用意する: + * - 種類をまたいで比べられる 1 本の数値(Google Maps の zIndex など)→ [flatZIndex] + * - スタイルの層の並び(MapLibre / Mapbox などの GL 系)→ [insertBefore] + */ +object OverlayStacking { + /** 下から上への帯の並び。 */ + val BOTTOM_TO_TOP: List = + listOf( + OverlayKind.RasterLayer, + OverlayKind.GroundImage, + OverlayKind.Polygon, + OverlayKind.Circle, + OverlayKind.Polyline, + OverlayKind.Marker, + ) + + /** 帯の番号(0 が一番下)。 */ + fun band(kind: OverlayKind): Int = BOTTOM_TO_TOP.indexOf(kind) + + /** + * 帯の幅。[flatZIndex] は `band * BAND_WIDTH` を中心に、zIndex を + * `±BAND_WIDTH / 2` 未満へ押し込める。 + */ + const val BAND_WIDTH: Float = 1000f + + // zIndex が小さいうちはほぼ 1 刻みで並び、大きくなっても帯の外へ出ない。 + private const val SQUASH_SCALE = 100_000.0 + + /** + * 種類をまたいで 1 本の数値で重なりを比べる SDK 向けの値。 + * + * 帯ごとに [BAND_WIDTH] の区間を割り当て、zIndex(Int 全域)を単調に + * その区間の内側へ押し込める。どんな zIndex を渡しても下の帯の上へは出ない。 + * float の精度上、zIndex の差が非常に大きい(数十万以上)ところでは + * 隣り合う値が同じになることがある(その場合の順はネイティブ SDK 次第)。 + */ + fun flatZIndex( + kind: OverlayKind, + zIndex: Int, + ): Float { + val z = zIndex.toDouble() + val squashed = z / (abs(z) + SQUASH_SCALE) * (BAND_WIDTH / 2.0) * 0.999 + return (band(kind) * BAND_WIDTH + squashed).toFloat() + } + + /** + * 重なりの並びを決める鍵。帯 → zIndex の順で比べる。 + * 同じ鍵どうしは、後から入れたものが上([insertBefore] がそう選ぶ)。 + */ + data class Key( + val kind: OverlayKind, + val zIndex: Int = 0, + ) : Comparable { + override fun compareTo(other: Key): Int { + val b = band(kind).compareTo(band(other.kind)) + if (b != 0) return b + return zIndex.compareTo(other.zIndex) + } + } + + /** + * 層の並び(GL 系のスタイルなど)に新しい層を入れるとき、どの層の**下**に入れるか。 + * + * [layersBottomToTop] は今の並び(下から上)。[keyOf] は SDK が足した層なら鍵を、 + * ベースマップなど SDK のものでない層なら null を返す。 + * + * 鍵が [key] より大きい最初の(一番下の)SDK の層を返す。無ければ null + * (呼び出し側は一番上へ足す)。同じ鍵の層の上に入るので、同じ zIndex なら + * 後から渡したものが上になる。 + * + * 並びを持たず毎回スタイルから読むので、スタイルの読み直しや送り直しの後でも + * 結果が変わらない。 + */ + fun insertBefore( + layersBottomToTop: List, + key: Key, + keyOf: (L) -> Key?, + ): L? = + layersBottomToTop.firstOrNull { layer -> + val k = keyOf(layer) ?: return@firstOrNull false + k > key + } +} + +/** + * 層の id で重なりを持つ SDK(GL 系のスタイル)向けの台帳。 + * + * SDK が足した層の id と [OverlayStacking.Key] の対応を持ち、新しい層を入れる位置 + * (どの層の下に入れるか)を [beforeId] で返す。台帳に無い id はベースマップの層として + * 無視する。スタイルを読み直して層が消えても台帳は残るので、足し直すときも同じ位置になる。 + */ +class OverlayLayerStack { + private val keys = java.util.concurrent.ConcurrentHashMap() + + fun put( + layerId: String, + key: OverlayStacking.Key, + ) { + keys[layerId] = key + } + + fun remove(layerId: String) { + keys.remove(layerId) + } + + fun keyOf(layerId: String): OverlayStacking.Key? = keys[layerId] + + /** + * [key] の層を、今の並び [layerIdsBottomToTop](下から上)のどの層の下に入れるか。 + * null なら一番上へ足す。 + */ + fun beforeId( + layerIdsBottomToTop: List, + key: OverlayStacking.Key, + ): String? = OverlayStacking.insertBefore(layerIdsBottomToTop, key) { keys[it] } +} diff --git a/src/main/java/com/mapconductor/core/geocell/HexCellRegistry.kt b/src/main/java/com/mapconductor/core/geocell/HexCellRegistry.kt deleted file mode 100644 index 0e0d1b1..0000000 --- a/src/main/java/com/mapconductor/core/geocell/HexCellRegistry.kt +++ /dev/null @@ -1,329 +0,0 @@ -package com.mapconductor.core.geocell - -import com.mapconductor.core.features.GeoPoint -import com.mapconductor.core.features.GeoPointInterface -import com.mapconductor.core.marker.MarkerEntityInterface -import java.util.concurrent.ConcurrentHashMap -import java.util.concurrent.locks.ReentrantReadWriteLock -import kotlin.concurrent.read -import kotlin.concurrent.write -import kotlin.math.pow -import kotlin.math.sqrt - -/** - * HexCellRegistry - Thread-safe hexagonal cell management with KDTree spatial indexing - * - * @param T The actual marker type - * @param geocell The hexagonal geocell system - * @param zoom The zoom level for this registry - */ -class HexCellRegistry( - private val geocell: HexGeocellInterface, - private val zoom: Double, -) { - private var kdTree: KDTree? = null - private val allCells = ConcurrentHashMap() - private val entryIDsByCell = ConcurrentHashMap>() - private val allEntries = ConcurrentHashMap() - - // entityId -> cellId - @Volatile - private var needsRebuild = false - - // Thread safety for complex operations - - private val lock = ReentrantReadWriteLock() - - /** - * Get the hex cell for a given entity without registering it - */ - fun getCell(entity: MarkerEntityInterface): HexCell { - val coord = geocell.latLngToHexCoord(entity.state.position, zoom) - val centerLatLng = geocell.hexToLatLngCenter(coord, entity.state.position.latitude, zoom) - val centerXY = geocell.projection.project(centerLatLng) - val cellId = geocell.hexToCellId(coord, zoom) // Include zoom in ID - return HexCell(coord, centerLatLng, centerXY, cellId) - } - - /** - * Register or update a point in the registry - * @return The hex cell containing the point - */ - fun setPoint(entity: MarkerEntityInterface): HexCell = - lock.write { - val entityId = entity.state.id - val cell = getCell(entity) - val cellId = cell.id - val previousCellId = allEntries[entityId] - - // [kdTree] が索引しているのは **セル**([allCells])であって entity ではない。 - // なのでセル集合が変わらない更新で dirty を立ててはいけない。立てると次の - // 空間検索が全セルから木を作り直す(24,000 件規模で 200ms 超)。 - // - // 位置が変わらない更新は珍しくない — アイコンやフラグの差し替え( - // `MarkerManager.updateEntity` は毎回 setPoint を呼ぶ)や、 - // [com.mapconductor.core.marker.MarkerViewportSwitch] のタイル⇔ネイティブ切り替えが該当する。 - if (previousCellId == cellId && allCells.containsKey(cellId)) { - entryIDsByCell.compute(cellId) { _, existingSet -> - (existingSet ?: mutableSetOf()).apply { add(entityId) } - } - return cell - } - - var cellsChanged = false - - // Remove from old cell if exists - previousCellId?.let { oldCellId -> - if (removeFromCell(oldCellId, entityId) && !allCells.containsKey(oldCellId)) { - // 空になったセルが消えた=セル集合が変わった - cellsChanged = true - } - } - - // Add to new cell - if (allCells.put(cellId, cell) == null) cellsChanged = true - allEntries[entityId] = cellId - - // Add entity to cell's entry list - entryIDsByCell.compute(cellId) { _, existingSet -> - (existingSet ?: mutableSetOf()).apply { add(entityId) } - } - - if (cellsChanged) markDirty() - return cell - } - - /** - * Check if a hex cell exists in the registry - */ - fun contains(hexId: String): Boolean = allCells.containsKey(hexId) - - /** - * Remove a point from the registry - * @return true if the point was removed, false if it wasn't found - */ - fun removePoint(entity: MarkerEntityInterface): Boolean = - lock.write { - val entityId = entity.state.id - val cellId = allEntries[entityId] ?: return false - - val removed = removeFromCell(cellId, entityId) - if (removed) { - allEntries.remove(entityId) - // セルがまだ他の entity を抱えていれば [allCells] は変わらないので、 - // 木を作り直す必要はない([setPoint] と同じ理由)。 - if (!allCells.containsKey(cellId)) markDirty() - } - - return removed - } - - /** - * Remove an entity from a specific cell - * @return true if removed, false if not found - */ - private fun removeFromCell( - cellId: String, - entityId: String, - ): Boolean { - val entryIds = entryIDsByCell[cellId] ?: return false - val removed = entryIds.remove(entityId) - - if (removed && entryIds.isEmpty()) { - // Remove empty cell - allCells.remove(cellId) - entryIDsByCell.remove(cellId) - } - return removed - } - - /** - * Clear all points and rebuild the spatial index - */ - fun clear() = - lock.write { - allCells.clear() - entryIDsByCell.clear() - allEntries.clear() - kdTree = null - needsRebuild = false - } - - /** - * Mark the spatial index as needing rebuild - */ - private fun markDirty() { - needsRebuild = true - } - - /** - * Rebuild the spatial index if needed - */ - private fun rebuildIfNeeded() { - // まず read で「必要か」を見る(短時間) - val dirty = lock.read { needsRebuild } - if (!dirty) return - - // read を解放してから write で再確認&再構築 - lock.write { - if (!needsRebuild) return // ここに来るまでに別スレッドが rebuild 済みの場合 - kdTree = - if (allCells.isNotEmpty()) { - KDTree(allCells.values.toList()) - } else { - null - } - needsRebuild = false - } - } - - /** - * Find the nearest hex cell to a point - */ - fun findNearest(point: GeoPointInterface): HexCell? { - rebuildIfNeeded() - return lock.read { - kdTree?.nearest(geocell.projection.project(point)) - } - } - - /** - * Find the nearest hex cell with distance - */ - fun findNearestWithDistance(point: GeoPointInterface): HexCellWithDistance? { - rebuildIfNeeded() - return lock.read { - kdTree?.nearestWithDistance(geocell.projection.project(point)) - } - } - - /** - * Find k nearest hex cells with distances - */ - fun findNearestKWithDistance( - point: GeoPointInterface, - k: Int, - ): List { - rebuildIfNeeded() - return lock.read { - kdTree?.nearestKWithDistance(geocell.projection.project(point), k).orEmpty() - } - } - - /** - * Find all hex cells within a radius with distances - */ - fun findWithinRadiusWithDistance( - point: GeoPointInterface, - radius: Double, - ): List { - rebuildIfNeeded() - return lock.read { - kdTree?.withinRadiusWithDistance(geocell.projection.project(point), radius).orEmpty() - } - } - - /** - * Get all hex cells - * - * ArrayList(values) avoids the size==1 race in Kotlin's toList() on concurrent maps. - */ - fun all(): List = ArrayList(allCells.values) - - /** - * Get entity IDs for a specific hex cell - */ - fun getEntryIDsByHexCell(hexCell: HexCell): Set? = - entryIDsByCell[hexCell.id]?.toSet() // Return immutable copy - - /** - * Calculate meters per pixel at a given position and zoom level - * - * Note: This assumes the projection returns coordinates in meters. - * Verify that your projection implementation meets this requirement. - */ - fun metersPerPixel( - position: GeoPointInterface, - zoom: Double, - pixels: Double, - tileSize: Int = 256, - ): Double { - require(pixels > 0) { "Pixels must be positive" } - require(tileSize > 0) { "Tile size must be positive" } - - val deltaLng = 360.0 * pixels / (tileSize * 2.0.pow(zoom)) - - // Handle potential longitude overflow - val newLng = - (position.longitude + deltaLng).let { lng -> - when { - lng > 180.0 -> lng - 360.0 - lng < -180.0 -> lng + 360.0 - else -> lng - } - } - - val p1 = geocell.projection.project(position) - val p2 = - geocell.projection.project( - object : GeoPointInterface { - override val latitude = position.latitude - override val longitude = newLng - override val altitude = position.altitude - - override fun wrap(): GeoPointInterface = GeoPoint(latitude, longitude, altitude ?: 0.0).wrap() - }, - ) - - val deltaX = p2.x - p1.x - val deltaY = p2.y - p1.y - return sqrt(deltaX * deltaX + deltaY * deltaY).toDouble() - } - - /** - * Find hex cells within a pixel radius - */ - fun findWithinPixelRadius( - position: GeoPointInterface, - zoom: Double, - pixels: Double, - tileSize: Int = 256, - ): List { - val meters = metersPerPixel(position, zoom, pixels, tileSize) - return findWithinRadiusWithDistance(position, meters) - } - - /** - * Find hex cells by ID prefix (optimized for common prefixes) - */ - fun findByIdPrefix(prefix: String): List { - require(prefix.isNotEmpty()) { "Prefix cannot be empty" } - - return allCells.entries - .asSequence() - .filter { it.key.startsWith(prefix) } - .map { it.value } - .toList() - } - - /** - * Get statistics about the registry - */ - fun getStats(): RegistryStats = - RegistryStats( - totalCells = allCells.size, - totalEntries = allEntries.size, - kdTreeBuilt = kdTree != null, - needsRebuild = needsRebuild, - ) -} - -/** - * Statistics about the registry state - */ -data class RegistryStats( - val totalCells: Int, - val totalEntries: Int, - val kdTreeBuilt: Boolean, - val needsRebuild: Boolean, -) diff --git a/src/main/java/com/mapconductor/core/geocell/HexGeocellImpl.kt b/src/main/java/com/mapconductor/core/geocell/HexGeocellImpl.kt index 97bbd17..dc9882b 100644 --- a/src/main/java/com/mapconductor/core/geocell/HexGeocellImpl.kt +++ b/src/main/java/com/mapconductor/core/geocell/HexGeocellImpl.kt @@ -1,9 +1,9 @@ package com.mapconductor.core.geocell -import androidx.compose.ui.geometry.Offset import com.mapconductor.core.features.GeoPoint import com.mapconductor.core.features.GeoPointInterface import com.mapconductor.core.marker.MarkerState +import com.mapconductor.core.projection.ProjectedPoint import com.mapconductor.core.projection.ProjectionInterface import com.mapconductor.core.projection.WebMercator import kotlin.math.PI @@ -47,17 +47,12 @@ enum class Direction6( data class HexCell( val coord: HexCoord, val centerLatLng: GeoPointInterface, - val centerXY: Offset, + val centerXY: ProjectedPoint, val id: String, ) { fun idPrefix(levels: Int): String = id.split("_").take(levels + 1).joinToString("_") } -data class HexCellWithDistance( - val cell: HexCell, - val distanceMeters: Double, -) - /** * Hexagonal geocell system for spatial indexing * @@ -139,7 +134,7 @@ class HexGeocell( val angle = Math.toRadians(60.0 * i - 30.0) // Start at -30° for flat-top val x = center.x + circumRadius * cos(angle) val y = center.y + circumRadius * sin(angle) - projection.unproject(Offset(x.toFloat(), y.toFloat())) + projection.unproject(ProjectedPoint(x, y)) } } @@ -233,20 +228,20 @@ class HexGeocell( private fun hexCenterXY( coord: HexCoord, hexSideLength: Double, - ): Offset { + ): ProjectedPoint { // For flat-top hexagons with side length s: // - Distance between adjacent hex centers in q direction = s * 3/2 // - Distance between adjacent hex centers in r direction = s * √3 val x = hexSideLength * (3.0 / 2.0 * coord.q) val y = hexSideLength * (sqrt(3.0) * (coord.r + coord.q / 2.0)) - return Offset(x.toFloat(), y.toFloat()) + return ProjectedPoint(x, y) } /** * Convert pixel coordinates to hex coordinate */ private fun pixelToHex( - offset: Offset, + offset: ProjectedPoint, hexSideLength: Double, ): HexCoord { val q = (2.0 / 3.0 * offset.x / hexSideLength) diff --git a/src/main/java/com/mapconductor/core/geocell/KDTree.kt b/src/main/java/com/mapconductor/core/geocell/KDTree.kt deleted file mode 100644 index a06351b..0000000 --- a/src/main/java/com/mapconductor/core/geocell/KDTree.kt +++ /dev/null @@ -1,277 +0,0 @@ -package com.mapconductor.core.geocell - -import androidx.compose.ui.geometry.Offset -import java.util.PriorityQueue -import kotlin.math.pow -import kotlin.math.sqrt - -/** - * K-D Tree implementation for efficient spatial queries on hex cells - * Supports nearest neighbor, k-NN, and radius searches - */ -class KDTree( - points: List, -) { - private val root = if (points.isNotEmpty()) build(points, 0) else null - - private class Node( - val cell: HexCell, - val left: Node?, - val right: Node?, - val axis: Int, // 0 for x-axis, 1 for y-axis - ) - - /** - * Build the K-D tree recursively - */ - private fun build( - items: List, - depth: Int, - ): Node? { - if (items.isEmpty()) return null - - val axis = depth % 2 - val sorted = - items.sortedBy { - if (axis == 0) it.centerXY.x else it.centerXY.y - } - val mid = sorted.size / 2 - - return Node( - cell = sorted[mid], - left = build(sorted.subList(0, mid), depth + 1), - right = build(sorted.subList(mid + 1, sorted.size), depth + 1), - axis = axis, - ) - } - - /** - * Find the nearest hex cell to a query point - */ - fun nearest(query: Offset): HexCell? = root?.let { nearest(it, query, null, Double.MAX_VALUE) } - - /** - * Recursive nearest neighbor search - */ - private fun nearest( - node: Node, - query: Offset, - best: HexCell?, - bestDistSq: Double, - ): HexCell? { - val axis = node.axis - val queryVal = if (axis == 0) query.x else query.y - val nodeVal = if (axis == 0) node.cell.centerXY.x else node.cell.centerXY.y - - val distSq = squaredDistance(query, node.cell.centerXY).toDouble() - - var currentBest = best - var currentBestDistSq = bestDistSq - - // Update best if current node is closer - if (distSq < currentBestDistSq) { - currentBest = node.cell - currentBestDistSq = distSq - } - - // Determine which subtree to search first - val (nearChild, farChild) = - if (queryVal < nodeVal) { - node.left to node.right - } else { - node.right to node.left - } - - // Search near subtree - nearChild?.let { near -> - currentBest = nearest(near, query, currentBest, currentBestDistSq) - currentBestDistSq = currentBest?.let { - squaredDistance(query, it.centerXY).toDouble() - } ?: currentBestDistSq - } - - // Search far subtree if it might contain closer points - farChild?.let { far -> - val axisDist = (queryVal - nodeVal).pow(2).toDouble() - if (axisDist < currentBestDistSq) { - currentBest = nearest(far, query, currentBest, currentBestDistSq) - } - } - - return currentBest - } - - /** - * Find the nearest hex cell with distance - */ - fun nearestWithDistance(query: Offset): HexCellWithDistance? { - val cell = nearest(query) ?: return null - val distance = distance(query, cell.centerXY).toDouble() - return HexCellWithDistance(cell, distance) - } - - /** - * Find k nearest hex cells with distances - */ - fun nearestKWithDistance( - query: Offset, - k: Int, - ): List { - require(k > 0) { "k must be positive" } - - if (root == null) return emptyList() - - val queue = - PriorityQueue>( - compareByDescending { it.first }, - ) - - nearestK(root, query, k, queue) - - return queue - .map { (distSq, cell) -> - HexCellWithDistance(cell, sqrt(distSq)) - }.sortedBy { it.distanceMeters } - } - - /** - * Recursive k-nearest neighbor search - */ - private fun nearestK( - node: Node, - query: Offset, - k: Int, - queue: PriorityQueue>, - ) { - val distSq = squaredDistance(query, node.cell.centerXY).toDouble() - - if (queue.size < k) { - queue.offer(distSq to node.cell) - } else if (distSq < queue.peek()!!.first) { - queue.poll() - queue.offer(distSq to node.cell) - } - - val axis = node.axis - val queryVal = if (axis == 0) query.x else query.y - val nodeVal = if (axis == 0) node.cell.centerXY.x else node.cell.centerXY.y - - val (nearChild, farChild) = - if (queryVal < nodeVal) { - node.left to node.right - } else { - node.right to node.left - } - - // Search near subtree - nearChild?.let { nearestK(it, query, k, queue) } - - // Search far subtree if it might contain closer points - farChild?.let { - val axisDist = (queryVal - nodeVal).pow(2).toDouble() - if (queue.size < k || axisDist < queue.peek()!!.first) { - nearestK(it, query, k, queue) - } - } - } - - /** - * Find all hex cells within a radius with distances - */ - fun withinRadiusWithDistance( - query: Offset, - radius: Double, - ): List { - require(radius >= 0) { "Radius must be non-negative" } - - if (root == null) return emptyList() - - val radiusSq = radius * radius - val result = mutableListOf() - withinRadius(root, query, radiusSq, result) - return result.sortedBy { it.distanceMeters } - } - - /** - * Recursive radius search - */ - private fun withinRadius( - node: Node, - query: Offset, - radiusSq: Double, - result: MutableList, - ) { - val distSq = squaredDistance(query, node.cell.centerXY).toDouble() - - if (distSq <= radiusSq) { - result.add(HexCellWithDistance(node.cell, sqrt(distSq))) - } - - val axis = node.axis - val queryVal = if (axis == 0) query.x else query.y - val nodeVal = if (axis == 0) node.cell.centerXY.x else node.cell.centerXY.y - - val (nearChild, farChild) = - if (queryVal < nodeVal) { - node.left to node.right - } else { - node.right to node.left - } - - // Search near subtree - nearChild?.let { withinRadius(it, query, radiusSq, result) } - - // Search far subtree if it intersects with query circle - farChild?.let { - val axisDist = (queryVal - nodeVal).pow(2).toDouble() - if (axisDist <= radiusSq) { - withinRadius(it, query, radiusSq, result) - } - } - } - - /** - * Calculate squared Euclidean distance between two points - */ - private fun squaredDistance( - a: Offset, - b: Offset, - ): Float { - val deltaX = a.x - b.x - val deltaY = a.y - b.y - return deltaX * deltaX + deltaY * deltaY - } - - /** - * Calculate Euclidean distance between two points - */ - private fun distance( - a: Offset, - b: Offset, - ): Float = sqrt(squaredDistance(a, b)) - - /** - * Get statistics about the tree structure - */ - fun getStats(): KDTreeStats = - KDTreeStats( - nodeCount = countNodes(root), - maxDepth = maxDepth(root), - isEmpty = root == null, - ) - - private fun countNodes(node: Node?): Int = - if (node == null) 0 else 1 + countNodes(node.left) + countNodes(node.right) - - private fun maxDepth(node: Node?): Int = - if (node == null) 0 else 1 + maxOf(maxDepth(node.left), maxDepth(node.right)) -} - -/** - * Statistics about the K-D tree structure - */ -data class KDTreeStats( - val nodeCount: Int, - val maxDepth: Int, - val isEmpty: Boolean, -) diff --git a/src/main/java/com/mapconductor/core/geometry/OverlayGeometry.kt b/src/main/java/com/mapconductor/core/geometry/OverlayGeometry.kt index 42afbc0..0d6289e 100644 --- a/src/main/java/com/mapconductor/core/geometry/OverlayGeometry.kt +++ b/src/main/java/com/mapconductor/core/geometry/OverlayGeometry.kt @@ -25,6 +25,46 @@ fun densifyAndNormalize( false -> Planar.createInterpolatePoints(points) }.map { it.normalize() } +/** + * ポリゴンのリング(外周・穴)を、閉じる辺(末尾 → 先頭)も含めて密度化する。 + * + * geodesic なら大圏([WGS84Geodesic])、そうでなければ緯度経度の線形補間([Planar])。 + * どちらの `createInterpolatePoints` も隣り合う点の間しか補間しないため、開いたリング + * (末尾 ≠ 先頭)をそのまま渡すと閉じる辺だけが補間されず、描画側で閉じたときに直線の弦に + * なる。ポリゴンの輪郭はリングを閉じてからポリラインとして密度化するので、塗りと輪郭で + * 閉じる辺の形が食い違う(geodesic=false でも、線形補間の辺はメルカトル上でわずかに曲がる)。 + * ここでは閉じる辺も他の辺と同じ方式で補間する。 + * + * 入力が開いたリングなら開いたまま(末尾に先頭の重複点を付けない)、閉じたリングなら閉じた + * まま返す。正規化はしない。頂点 2 未満の入力はそのまま `createInterpolatePoints` に渡す。 + */ +fun densifyPolygonRing( + ring: List, + geodesic: Boolean, + maxSegmentLength: Double = 10000.0, +): List { + val densify: (List) -> List = + if (geodesic) { + { WGS84Geodesic.createInterpolatePoints(it, maxSegmentLength) } + } else { + { Planar.createInterpolatePoints(it, maxSegmentLength) } + } + if (ring.size < 2 || isClosedRing(ring)) return densify(ring) + return densify(ring + ring.first()).dropLast(1) +} + +private fun isClosedRing(ring: List): Boolean { + val first = ring.first() + val last = ring.last() + return first.latitude == last.latitude && first.longitude == last.longitude +} + +/** リング用の [densifyAndNormalize]。閉じる辺も補間する([densifyPolygonRing])。 */ +private fun densifyRingAndNormalize( + ring: List, + geodesic: Boolean, +): List = densifyPolygonRing(ring, geodesic).map { it.normalize() } + /** * ポリライン用パイプライン。密度化・正規化後に子午線で分割したセグメント列を返す。 * 頂点 2 未満の入力、および分割で 2 点未満になったセグメントは除く(空リストになり得る)。 @@ -61,14 +101,14 @@ fun buildPolygonRings( ): PolygonRings { if (points.size < 3) return PolygonRings(emptyList(), emptyList()) val outerRings = - splitRingByMeridian(densifyAndNormalize(points, geodesic), geodesic) + splitRingByMeridian(densifyRingAndNormalize(points, geodesic), geodesic) .filter { it.size >= 3 } val includeHoles = holes.isNotEmpty() && outerRings.size == 1 val holeRings = if (includeHoles) { holes .filter { it.size >= 3 } - .map { densifyAndNormalize(it, geodesic) } + .map { densifyRingAndNormalize(it, geodesic) } .filter { it.size >= 3 } } else { emptyList() @@ -137,12 +177,12 @@ fun buildUnwrappedPolygonRings( geodesic: Boolean, ): PolygonRings { if (points.size < 3) return PolygonRings(emptyList(), emptyList()) - val outer = unwrapContinuous(densifyAndNormalize(points, geodesic)) + val outer = unwrapContinuous(densifyRingAndNormalize(points, geodesic)) val anchor = outer.first().longitude val holeRings = holes .filter { it.size >= 3 } - .map { unwrapContinuous(densifyAndNormalize(it, geodesic), anchorLng = anchor) } + .map { unwrapContinuous(densifyRingAndNormalize(it, geodesic), anchorLng = anchor) } .filter { it.size >= 3 } return PolygonRings(outerRings = listOf(outer), holeRings = holeRings) } diff --git a/src/main/java/com/mapconductor/core/groundimage/GroundImage.kt b/src/main/java/com/mapconductor/core/groundimage/GroundImage.kt index 43df640..1dee7d7 100644 --- a/src/main/java/com/mapconductor/core/groundimage/GroundImage.kt +++ b/src/main/java/com/mapconductor/core/groundimage/GroundImage.kt @@ -1,122 +1,289 @@ -package com.mapconductor.core.groundimage - -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.setValue -import androidx.compose.runtime.snapshotFlow -import com.mapconductor.core.ComponentState -import com.mapconductor.core.features.GeoPoint -import com.mapconductor.core.features.GeoRectBounds -import java.io.Serializable -import android.graphics.drawable.Drawable -import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.flow.distinctUntilChanged - -class GroundImageState( - bounds: GeoRectBounds, - image: Drawable, - opacity: Float = 1.0f, - tileSize: Int = GroundImageTileProvider.DEFAULT_TILE_SIZE, - clickable: Boolean = true, - id: String? = null, - extra: Serializable? = null, - onClick: OnGroundImageEventHandler? = null, -) : ComponentState { - override val id = (id ?: generateId(bounds, image, opacity, tileSize, clickable, extra)).toString() - -// var bounds by StateFlowDelegate(bounds) - var bounds by mutableStateOf(bounds) - var image by mutableStateOf(image) - var opacity by mutableStateOf(opacity) - var tileSize by mutableStateOf(tileSize) - - /** - * タップを受け取るか。`false` ならこのグラウンドイメージはタップに対して透過し、 - * 下のオーバーレイ(無ければ地図クリック)へイベントが流れる。 - * - * 判定はコアの [com.mapconductor.core.groundimage.GroundImageManager.find] が - * 行うため、どのプロバイダでも同じ挙動になる。描画には影響しないので - * [fingerPrint] には含めない(含めると値を変えるたびにタイルが作り直される)。 - */ - var clickable by mutableStateOf(clickable) - var extra by mutableStateOf(extra) - var onClick by mutableStateOf(onClick) - - fun fingerPrint(): GroundImageFingerPrint = - GroundImageFingerPrint( - id = id.hashCode(), - bounds = bounds.hashCode(), - image = image.hashCode(), - opacity = opacity.hashCode(), - tileSize = tileSize.hashCode(), - extra = extra?.hashCode() ?: 0, - ) - - fun asFlow(): Flow = - snapshotFlow { - fingerPrint() - }.distinctUntilChanged() - - private fun generateId( - bounds: GeoRectBounds, - image: Drawable, - opacity: Float, - tileSize: Int, - clickable: Boolean, - extra: Serializable?, - ): Int { - var result = bounds.hashCode() - result = 31 * result + image.hashCode() - result = 31 * result + opacity.hashCode() - result = 31 * result + tileSize.hashCode() - result = 31 * result + clickable.hashCode() - result = 31 * result + (extra?.hashCode() ?: 0) - return result - } - - // ios-sdk / react-sdk の GroundImageState.copy() と揃えるための copy。 - fun copy( - bounds: GeoRectBounds = this.bounds, - image: Drawable = this.image, - opacity: Float = this.opacity, - tileSize: Int = this.tileSize, - clickable: Boolean = this.clickable, - id: String? = this.id, - extra: Serializable? = this.extra, - onClick: OnGroundImageEventHandler? = this.onClick, - ): GroundImageState = - GroundImageState( - bounds = bounds, - image = image, - opacity = opacity, - tileSize = tileSize, - clickable = clickable, - id = id, - extra = extra, - onClick = onClick, - ) - - override fun equals(other: Any?): Boolean = (other as? GroundImageState)?.hashCode() == this.hashCode() - - override fun hashCode(): Int = fingerPrint().hashCode() -} - -data class GroundImageFingerPrint( - val id: Int, - val bounds: Int, - val image: Int, - val opacity: Int, - val tileSize: Int, - val extra: Int, -) - -class GroundImageEvent( - val state: GroundImageState, - clicked: GeoPoint?, -) { - // 生成時に wrap して [-180,180] / [-90,90] に正規化する(日付変更線対策)。 - // 正規化をここ(イベント型=出口)に一元化することで、どの配送経路でも wrap 漏れが起きない。 - val clicked: GeoPoint? = clicked?.let { GeoPoint.from(it.wrap()) } -} - -typealias OnGroundImageEventHandler = (GroundImageEvent) -> Unit +package com.mapconductor.core.groundimage + +import androidx.compose.runtime.getValue +import androidx.compose.runtime.setValue +import com.mapconductor.core.ComponentState +import com.mapconductor.core.RemoteImageLoader +import com.mapconductor.core.StateMutationSignal +import com.mapconductor.core.UrlImageDrawable +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.features.GeoRectBounds +import java.io.Serializable +import android.graphics.drawable.Drawable + +/** + * 地図に貼る画像。 + * + * 画像は `Drawable` で渡すか、[imageUrl](http / https / file / data)で渡す。URL のときは + * SDK が読み、読み終えるまでは透明、読み終えたら [image] がその画像に替わって描き直される。 + * http(s) にはアプリの `android.permission.INTERNET` が要る。react-sdk の `imageUrl` と同じ。 + */ +class GroundImageState( + bounds: GeoRectBounds, + image: Drawable, + opacity: Float = 1.0f, + tileSize: Int = GroundImageTileProvider.DEFAULT_TILE_SIZE, + clickable: Boolean = true, + id: String? = null, + extra: Serializable? = null, + onClick: OnGroundImageEventHandler? = null, + onAdded: OnGroundImageAddedHandler? = null, +) : ComponentState { + override val id = (id ?: generateId(bounds, image, opacity, tileSize, clickable, extra)).toString() + + /** + * Writes to the fields below are announced here rather than discovered by + * reading them all back. See [StateMutationSignal]. + */ + override val mutations = StateMutationSignal() + +// var bounds by StateFlowDelegate(bounds) + var bounds by mutations.notifying(bounds) + private val currentImage = mutations.notifying(image) + private val currentImageUrl = mutations.notifying(null) + + /** 描く画像。書き換えると [imageUrl] は null になる。 */ + var image: Drawable + get() = currentImage.value + set(value) { + currentImageUrl.value = null + currentImage.value = value + } + + /** + * 画像の URL。`Drawable` で作ったか、[image] を書き換えたなら null。 + * + * 書き換えると、読み終えるまで [image] は透明になり、読み終えたらその画像になる。 + * 読めなかったときは透明のまま。読み終える前にまた書き換えたら、古い方の結果は捨てる。 + */ + var imageUrl: String? + get() = currentImageUrl.value + set(value) { + currentImageUrl.value = value + if (value == null) return + currentImage.value = UrlImageDrawable(value, null) + RemoteImageLoader.load(value) { bitmap -> + if (bitmap != null && currentImageUrl.value == value) { + currentImage.value = UrlImageDrawable(value, bitmap) + } + } + } + var opacity by mutations.notifying(opacity) + + var tileSize by mutations.notifying(tileSize) + + /** + * タップを受け取るか。`false` ならこのグラウンドイメージはタップに対して透過し、 + * 下のオーバーレイ(無ければ地図クリック)へイベントが流れる。 + * + * 判定はコアの [com.mapconductor.core.groundimage.GroundImageManager.find] が + * 行うため、どのプロバイダでも同じ挙動になる。描画には影響しないので + * [fingerPrint] には含めない(含めると値を変えるたびにタイルが作り直される)。 + */ + var clickable by mutations.notifying(clickable) + var extra by mutations.notifying(extra) + var onClick by mutations.notifying(onClick) + + /** + * Called once each time this ground image goes from not being on the map to being on it: + * after the map SDK's object for it has been created, or, when it is drawn in tiles, + * after the URL template of those tiles has been handed to the map as a raster layer + * (the tile images may still be loading then). Not called for an in-place change, + * nor when it moves between native drawing and tiles while staying on the map; + * called again if it is removed and added again. Clearing or destroying the map calls + * nothing. + * + * Runs on the main thread once the map has finished adding the overlays it was given. + * A callback that throws is logged and does not stop the other overlays' callbacks. + * + * Like `onClick`, it is not part of the id, fingerprint, equality or hash: replacing + * it redraws nothing. If the same state is shown on two maps, each map calls it. + */ + var onAdded: OnGroundImageAddedHandler? = onAdded + + /** [imageUrl] の画像を貼る。読み終えるまでは透明。ほかの引数は `Drawable` を渡すコンストラクタと同じ。 */ + constructor( + bounds: GeoRectBounds, + imageUrl: String, + opacity: Float = 1.0f, + tileSize: Int = GroundImageTileProvider.DEFAULT_TILE_SIZE, + clickable: Boolean = true, + id: String? = null, + extra: Serializable? = null, + onClick: OnGroundImageEventHandler? = null, + onAdded: OnGroundImageAddedHandler? = null, + ) : this( + bounds = bounds, + image = UrlImageDrawable(imageUrl, null), + opacity = opacity, + tileSize = tileSize, + clickable = clickable, + id = id, + extra = extra, + onClick = onClick, + onAdded = onAdded, + ) { + this.imageUrl = imageUrl + } + + @Deprecated("Binary compatibility only; use the overload with onAdded.", level = DeprecationLevel.HIDDEN) + constructor( + bounds: GeoRectBounds, + image: Drawable, + opacity: Float = 1.0f, + tileSize: Int = GroundImageTileProvider.DEFAULT_TILE_SIZE, + clickable: Boolean = true, + id: String? = null, + extra: Serializable? = null, + onClick: OnGroundImageEventHandler? = null, + ) : this( + bounds, + image, + opacity, + tileSize, + clickable, + id, + extra, + onClick, + null, + ) + + @Deprecated("Binary compatibility only; use the overload with onAdded.", level = DeprecationLevel.HIDDEN) + constructor( + bounds: GeoRectBounds, + imageUrl: String, + opacity: Float = 1.0f, + tileSize: Int = GroundImageTileProvider.DEFAULT_TILE_SIZE, + clickable: Boolean = true, + id: String? = null, + extra: Serializable? = null, + onClick: OnGroundImageEventHandler? = null, + ) : this( + bounds, + imageUrl, + opacity, + tileSize, + clickable, + id, + extra, + onClick, + null, + ) + + fun fingerPrint(): GroundImageFingerPrint = + GroundImageFingerPrint( + id = id.hashCode(), + bounds = bounds.hashCode(), + image = image.hashCode(), + opacity = opacity.hashCode(), + tileSize = tileSize.hashCode(), + extra = extra?.hashCode() ?: 0, + ) + + private fun generateId( + bounds: GeoRectBounds, + image: Drawable, + opacity: Float, + tileSize: Int, + clickable: Boolean, + extra: Serializable?, + ): Int { + var result = bounds.hashCode() + result = 31 * result + image.hashCode() + result = 31 * result + opacity.hashCode() + result = 31 * result + tileSize.hashCode() + result = 31 * result + clickable.hashCode() + result = 31 * result + (extra?.hashCode() ?: 0) + return result + } + + // ios-sdk / react-sdk の GroundImageState.copy() と揃えるための copy。 + fun copy( + bounds: GeoRectBounds = this.bounds, + image: Drawable = this.image, + opacity: Float = this.opacity, + tileSize: Int = this.tileSize, + clickable: Boolean = this.clickable, + id: String? = this.id, + extra: Serializable? = this.extra, + onClick: OnGroundImageEventHandler? = this.onClick, + onAdded: OnGroundImageAddedHandler? = this.onAdded, + ): GroundImageState { + // 画像を差し替えないなら URL ごと引き継ぐ(読み込み中でも、届いたら写る)。 + val url = imageUrl + if (url != null && image === this.image) { + return GroundImageState( + bounds = bounds, + imageUrl = url, + opacity = opacity, + tileSize = tileSize, + clickable = clickable, + id = id, + extra = extra, + onClick = onClick, + onAdded = onAdded, + ) + } + return GroundImageState( + bounds = bounds, + image = image, + opacity = opacity, + tileSize = tileSize, + clickable = clickable, + id = id, + extra = extra, + onClick = onClick, + onAdded = onAdded, + ) + } + + @Deprecated("Binary compatibility only; use the overload with onAdded.", level = DeprecationLevel.HIDDEN) + fun copy( + bounds: GeoRectBounds = this.bounds, + image: Drawable = this.image, + opacity: Float = this.opacity, + tileSize: Int = this.tileSize, + clickable: Boolean = this.clickable, + id: String? = this.id, + extra: Serializable? = this.extra, + onClick: OnGroundImageEventHandler? = this.onClick, + ): GroundImageState = + copy( + bounds, + image, + opacity, + tileSize, + clickable, + id, + extra, + onClick, + onAdded, + ) + + override fun equals(other: Any?): Boolean = (other as? GroundImageState)?.hashCode() == this.hashCode() + + override fun hashCode(): Int = fingerPrint().hashCode() +} + +data class GroundImageFingerPrint( + val id: Int, + val bounds: Int, + val image: Int, + val opacity: Int, + val tileSize: Int, + val extra: Int, +) + +class GroundImageEvent( + val state: GroundImageState, + clicked: GeoPoint?, +) { + // 生成時に wrap して [-180,180] / [-90,90] に正規化する(日付変更線対策)。 + // 正規化をここ(イベント型=出口)に一元化することで、どの配送経路でも wrap 漏れが起きない。 + val clicked: GeoPoint? = clicked?.let { GeoPoint.from(it.wrap()) } +} + +typealias OnGroundImageEventHandler = (GroundImageEvent) -> Unit + +/** Receives the state whose ground image was just added to the map. See [GroundImageState.onAdded]. */ +typealias OnGroundImageAddedHandler = (GroundImageState) -> Unit diff --git a/src/main/java/com/mapconductor/core/groundimage/GroundImageController.kt b/src/main/java/com/mapconductor/core/groundimage/GroundImageController.kt index b51818a..c5c70c5 100644 --- a/src/main/java/com/mapconductor/core/groundimage/GroundImageController.kt +++ b/src/main/java/com/mapconductor/core/groundimage/GroundImageController.kt @@ -36,7 +36,8 @@ abstract class GroundImageController( data.forEach { state -> if (previous.contains(state.id)) { - val prevEntity = groundImageManager.getEntity(state.id)!! + // Gone only if destroy() cleared the manager meanwhile; nothing left to update. + val prevEntity = groundImageManager.getEntity(state.id) ?: return@withPermit if (state.fingerPrint() == prevEntity.fingerPrint) { // 描画結果が不変なら renderer を呼ばず最新の state だけ採用する(react-sdk と同じ)。 groundImageManager @@ -147,8 +148,10 @@ abstract class GroundImageController( semaphore.withPermit { val entities: List> = groundImageManager.allEntities() renderer.onRemove(entities) - renderer.onPostProcess() + // manager を空にしてから onPostProcess を呼ぶ。GL 系の描画担当は remove では何もせず、 + // onPostProcess で manager の全部を描き直すので、逆の順だと clear() 後も地図に残る。 groundImageManager.clear() + renderer.onPostProcess() } } @@ -157,7 +160,9 @@ abstract class GroundImageController( .find(position) override fun destroy() { - // No native resources to clean up + // A destroyed controller can still be referenced (by its map controller, + // or a state that has not let go yet); without this it keeps every entity. + groundImageManager.clear() } override fun has(id: String): Boolean = groundImageManager.hasEntity(id) diff --git a/src/main/java/com/mapconductor/core/groundimage/GroundImageOverlay.kt b/src/main/java/com/mapconductor/core/groundimage/GroundImageOverlay.kt index b93e1df..2e01d4c 100644 --- a/src/main/java/com/mapconductor/core/groundimage/GroundImageOverlay.kt +++ b/src/main/java/com/mapconductor/core/groundimage/GroundImageOverlay.kt @@ -1,5 +1,6 @@ package com.mapconductor.core.groundimage +import com.mapconductor.core.OverlayAddedTracker import com.mapconductor.core.controller.MapViewControllerInterface import com.mapconductor.core.map.MapOverlayInterface import kotlinx.coroutines.flow.StateFlow @@ -7,10 +8,16 @@ import kotlinx.coroutines.flow.StateFlow class GroundImageOverlay( override val flow: StateFlow>, ) : MapOverlayInterface { + /** Calls [GroundImageState.onAdded] once the map has the state. See [OverlayAddedTracker]. */ + private val added = OverlayAddedTracker { it.onAdded } + override suspend fun render( data: MutableMap, controller: MapViewControllerInterface, ) { - (controller as? GroundImageCapableInterface)?.compositionGroundImages(data.values.toList()) + val capable = controller as? GroundImageCapableInterface ?: return + val states = data.values.toList() + capable.compositionGroundImages(states) + added.synced(controller, states, capable::hasGroundImage) } } diff --git a/src/main/java/com/mapconductor/core/map/ApplyStyleMutations.kt b/src/main/java/com/mapconductor/core/map/ApplyStyleMutations.kt new file mode 100644 index 0000000..45f8bbe --- /dev/null +++ b/src/main/java/com/mapconductor/core/map/ApplyStyleMutations.kt @@ -0,0 +1,171 @@ +package com.mapconductor.core.map + +/** + * The seven things a renderer has to be able to do for a style to be + * adjusted in place. + * + * A provider implements these against its own SDK and gets + * [applyStyleMutations] for everything above them — what each mutation + * means, which ones can be skipped, and keeping one bad property from + * costing the rest. MapLibre and Mapbox name their style APIs differently, + * so the adapter has to be per-provider; the decisions do not. + * + * Values arrive as JSON text, which is what crossed the FFI boundary: the + * provider turns it into whatever its SDK wants — a Gson tree for + * MapLibre's `Expression.Converter`, a `Value` for Mapbox v11. + * + * js-sdk-core does the same work structurally, because MapLibre GL JS, + * Mapbox GL JS and the MapTiler SDK happen to share their method names. + */ +interface StyleMutationTarget { + /** + * Whether the renderer has a style up to be changed. + * + * **False is not failure, and must not be reported as one.** A renderer + * with no style loaded yet cannot be asked about layers, so without this + * every mutation came back as one the map "cannot" make -- which is how + * an app got told "N adjustments were not applied" about a map that was + * merely still loading, and, under [VectorStyleMutationSupport]'s + * reloading policy, had the adjusted document handed to it for no + * reason. Nothing is lost by waiting: the store puts the whole set back + * when the style loads. + * + * Override it. The default is for a target that is always ready; a + * provider whose style arrives asynchronously -- which is all three of + * them -- answers whether it has one. + */ + val isReady: Boolean + get() = true + + /** + * False for a layer the loaded style does not have. + * + * Asked only when [isReady], so it is about the style's contents and + * never about whether there is a style: answering false for "not loaded + * yet" is what [isReady] exists to stop. A bridge that cannot be asked + * about a document's layers -- MapTiler's can only be asked about the + * ones it was told to add -- answers true and lets the attempt decide. + * + * Only the four property changes ask. [addLayer] and [removeLayer] guard + * themselves, because "is it already there" is a question only the + * renderer can answer about a layer it owns. + */ + fun hasLayer(layerId: String): Boolean + + fun setPaint( + layerId: String, + key: String, + valueJson: String, + ) + + fun setLayout( + layerId: String, + key: String, + valueJson: String, + ) + + /** `"null"` removes the filter. */ + fun setFilter( + layerId: String, + filterJson: String, + ) + + fun setZoomRange( + layerId: String, + minZoom: Float, + maxZoom: Float, + ) + + /** + * Adds a layer, or does nothing if the renderer already has one with + * this id -- which is the usual case, because a style reload puts the + * whole set back. + */ + fun addLayer( + layerId: String, + layerJson: String, + beforeId: String?, + ) + + /** A layer the renderer does not have is not an error. */ + fun removeLayer(layerId: String) +} + +/** + * Applies style mutations to a live renderer through [target]. + * + * The body of a provider's [VectorStyleMutationSupport]: a provider wires + * this into a [StyleMutationStore] and registers that, and every provider + * then behaves identically by construction. + * + * @return the mutations it could not apply. A layer the loaded style does + * not have, or a property the renderer rejected: the caller is told + * rather than left to assume the map looks the way the rules asked. + * Nothing is thrown — one bad property must not cost the other three + * hundred. Empty while the renderer has no style up, because then there + * is nothing it could not do — only something it has not done yet. + */ +fun applyStyleMutations( + target: StyleMutationTarget, + mutations: List, +): List { + // Not ready is not a refusal. See [StyleMutationTarget.isReady]. + if (!target.isReady) return emptyList() + return mutations.filter { mutation -> + runCatching { !applyOne(target, mutation) }.getOrDefault(true) + } +} + +private fun applyOne( + target: StyleMutationTarget, + mutation: StyleMutation, +): Boolean = + when (mutation) { + is StyleMutation.SetPaint -> { + if (!target.hasLayer(mutation.layerId)) { + false + } else { + target.setPaint(mutation.layerId, mutation.key, mutation.value) + true + } + } + is StyleMutation.SetLayout -> { + if (!target.hasLayer(mutation.layerId)) { + false + } else { + target.setLayout(mutation.layerId, mutation.key, mutation.value) + true + } + } + is StyleMutation.SetFilter -> { + if (!target.hasLayer(mutation.layerId)) { + false + } else { + target.setFilter(mutation.layerId, mutation.value) + true + } + } + is StyleMutation.SetZoomRange -> { + if (!target.hasLayer(mutation.layerId)) { + false + } else { + // The spec's own defaults, for a layer that named neither. + // Every renderer takes both ends at once, so a mutation that + // changes one has to restate the other. + target.setZoomRange( + mutation.layerId, + mutation.minZoom?.toFloat() ?: 0f, + mutation.maxZoom?.toFloat() ?: 24f, + ) + true + } + } + is StyleMutation.AddLayer -> { + target.addLayer(mutation.layerId, mutation.layer, mutation.beforeId) + true + } + is StyleMutation.RemoveLayer -> { + target.removeLayer(mutation.layerId) + true + } + } diff --git a/src/main/java/com/mapconductor/core/map/BaseMapViewSaver.kt b/src/main/java/com/mapconductor/core/map/BaseMapViewSaver.kt index cc858e8..7adc107 100644 --- a/src/main/java/com/mapconductor/core/map/BaseMapViewSaver.kt +++ b/src/main/java/com/mapconductor/core/map/BaseMapViewSaver.kt @@ -1,13 +1,21 @@ package com.mapconductor.core.map import androidx.compose.runtime.saveable.Saver -import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.InternalMapConductorApi import android.os.Bundle /** * Base class for MapView state savers + * + * カメラ(paddings を含む)と [MapViewStateInterface.uiSettings] はここで保存・復元する。 + * デザインは型がプロバイダごとに違うので [saveMapDesign] / [createState] が受け持つ。 + * デザインの `attributionRules` を含め、アプリが設定したものは全部書くこと + * (`MapViewStateBundle.putAttributionRules` を使う)。書かなかった値は回転などの + * 構成変更のあと黙って既定値に戻る。 + * * @param T MapViewStateInterface type */ +@OptIn(InternalMapConductorApi::class) abstract class BaseMapViewSaver> { /** * Save map design type to bundle @@ -47,6 +55,7 @@ abstract class BaseMapViewSaver> { putString("stateId", getStateId(state)) putBundle("mapDesign", mapDesignBundle) putBundle("camera", cameraStateBundle) + putBundle(MapViewStateBundle.KEY_UI_SETTINGS, MapViewStateBundle.uiSettingsToBundle(state.uiSettings)) } }, restore = { storedData -> @@ -56,7 +65,14 @@ abstract class BaseMapViewSaver> { val cameraPosition = createCameraPositionFromBundle(cameraBundle) - createState(stateId, mapDesignBundle, cameraPosition) + createState(stateId, mapDesignBundle, cameraPosition).also { state -> + // uiSettings はどのプロバイダでも MapViewStateInterface の var なので、 + // createState に渡さずここで戻す(以前は保存しておらず、復元後は + // 全部 true の既定値に戻っていた)。 + MapViewStateBundle.uiSettingsFromBundle(storedData.getBundle(MapViewStateBundle.KEY_UI_SETTINGS))?.let { + state.uiSettings = it + } + } }, ) @@ -65,27 +81,8 @@ abstract class BaseMapViewSaver> { */ protected abstract fun getStateId(state: T): String - private fun createCameraBundle(state: T): Bundle = - state.cameraPosition.let { - Bundle().apply { - putDouble("zoom", it.zoom) - putDouble("tilt", it.tilt) - putDouble("bearing", it.bearing) - putDouble("latitude", it.position.latitude) - putDouble("longitude", it.position.longitude) - } - } + private fun createCameraBundle(state: T): Bundle = MapViewStateBundle.cameraToBundle(state.cameraPosition) private fun createCameraPositionFromBundle(cameraBundle: Bundle?): MapCameraPosition = - MapCameraPosition( - position = - GeoPoint.fromLatLong( - latitude = cameraBundle?.getDouble("latitude") ?: 0.0, - longitude = cameraBundle?.getDouble("longitude") ?: 0.0, - ), - zoom = cameraBundle?.getDouble("zoom") ?: 0.0, - bearing = cameraBundle?.getDouble("bearing") ?: 0.0, - tilt = cameraBundle?.getDouble("tilt") ?: 0.0, - paddings = getCameraPaddings(), - ) + MapViewStateBundle.cameraFromBundle(cameraBundle, fallbackPaddings = getCameraPaddings()) } diff --git a/src/main/java/com/mapconductor/core/map/BlankMapStyle.kt b/src/main/java/com/mapconductor/core/map/BlankMapStyle.kt new file mode 100644 index 0000000..0cb6ee5 --- /dev/null +++ b/src/main/java/com/mapconductor/core/map/BlankMapStyle.kt @@ -0,0 +1,27 @@ +package com.mapconductor.core.map + +/** + * A MapLibre-style map with nothing in it but a background. + * + * What a provider shows for "no basemap" when it is built on MapLibre or takes + * a MapLibre style (Mapbox, MapTiler, TomTom). A map that draws its whole + * viewport itself -- vector tiles rendered on the device, say -- fetches and + * paints the basemap under it for nobody; this is the style that fetches + * nothing. ios-sdk-core and js-sdk-core carry the same style. + * + * The same style is bundled as an asset (`mapconductor/blank-style.json`, + * merged into the app from this library) for SDKs that only take a URI. + */ +object BlankMapStyle { + /** このスタイルが持つ唯一の色。 */ + const val BACKGROUND_COLOR: String = "#f2efe9" + + const val JSON: String = + """{"version":8,"name":"blank","sources":{},"layers":[{"id":"background","type":"background","paint":{"background-color":"#f2efe9"}}]}""" + + /** The bundled asset, as the `asset://` URI MapLibre-based SDKs read. */ + const val ASSET_URI: String = "asset://mapconductor/blank-style.json" + + /** The bundled asset, as the `file:` URL a WebView-based SDK reads. */ + const val ASSET_FILE_URL: String = "file:///android_asset/mapconductor/blank-style.json" +} diff --git a/src/main/java/com/mapconductor/core/map/CameraBearing.kt b/src/main/java/com/mapconductor/core/map/CameraBearing.kt new file mode 100644 index 0000000..60e1d3c --- /dev/null +++ b/src/main/java/com/mapconductor/core/map/CameraBearing.kt @@ -0,0 +1,46 @@ +package com.mapconductor.core.map + +import com.mapconductor.core.InternalMapConductorApi + +/** + * [com.mapconductor.core.features.MapCameraPosition.bearing] とネイティブ SDK の回転値の変換。 + * + * MapConductor の `bearing` は **「値を増やすと地図が時計回り(右)に回る」** 向きで定義する。 + * 0 が北で、90 なら地図全体が右へ 90 度回り、画面の上には西が来る。 + * + * ネイティブ SDK は大きく 2 系統に分かれる。 + * + * - **heading 系**(Google Maps / MapLibre / Mapbox / HERE / MapKit ほか) + * 「画面の上が指す方位を北から時計回りに測る」=カメラの向き。値を増やすと地図は + * 反時計回りに回るので、MapConductor とは符号が反転する。[toNativeHeading]。 + * - **rotation 系**(ArcGIS の `Viewpoint.rotation` など)「北を時計回りに回す量」= + * 地図の回転角。MapConductor と同じ向きなので変換は恒等になる。[toNativeRotation]。 + * + * 符号をプロバイダ各所に散らすと必ずどこかが漏れるので、変換はここだけに置く。 + */ +@InternalMapConductorApi +object CameraBearing { + /** 角度を 0 以上 360 未満へ畳む。 */ + fun normalizeDegrees360(degrees: Double): Double { + if (!degrees.isFinite()) return 0.0 + val wrapped = degrees % 360.0 + return if (wrapped < 0.0) wrapped + 360.0 else wrapped + } + + /** + * MapConductor の bearing → heading 系ネイティブ SDK の値。 + * + * カメラが向いている方位でもあるので、負 tilt エミュレーションで + * 「カメラの前進方向」が要るときもこれを使う。 + */ + fun toNativeHeading(bearing: Double): Double = normalizeDegrees360(-bearing) + + /** heading 系ネイティブ SDK の値 → MapConductor の bearing。 */ + fun bearingFromNativeHeading(heading: Double): Double = normalizeDegrees360(-heading) + + /** MapConductor の bearing → rotation 系ネイティブ SDK の値(向きが同じなので恒等)。 */ + fun toNativeRotation(bearing: Double): Double = normalizeDegrees360(bearing) + + /** rotation 系ネイティブ SDK の値 → MapConductor の bearing(同上)。 */ + fun bearingFromNativeRotation(rotation: Double): Double = normalizeDegrees360(rotation) +} diff --git a/src/main/java/com/mapconductor/core/map/CameraPaddingEmulation.kt b/src/main/java/com/mapconductor/core/map/CameraPaddingEmulation.kt new file mode 100644 index 0000000..686678d --- /dev/null +++ b/src/main/java/com/mapconductor/core/map/CameraPaddingEmulation.kt @@ -0,0 +1,194 @@ +package com.mapconductor.core.map + +import com.mapconductor.core.InternalMapConductorApi +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.features.GeoPointInterface +import com.mapconductor.core.spherical.Spherical +import com.mapconductor.core.zoom.AbstractZoomAltitudeConverter +import kotlin.math.abs +import kotlin.math.atan +import kotlin.math.atan2 +import kotlin.math.cos +import kotlin.math.hypot +import kotlin.math.max +import kotlin.math.min +import kotlin.math.pow +import kotlin.math.sin +import kotlin.math.tan + +/** + * カメラのパディング([MapCameraPositionInterface.paddings])を持たない地図SDK向けに、 + * パディングをカメラ中心のずらしで再現する。 + * + * パディングを付けたカメラは「パディングを除いた領域の中央に `position` を置く」。 + * その位置は画面中央から `dx = (left - right) / 2`、`dy = (top - bottom) / 2` + * (dp、右・下が正)だけずれている。ここでは、その画面上のずれが地上で何メートルに + * なるかを解き、ネイティブ SDK へ渡すカメラ中心を求める。逆向きも持つ。 + * + * 視野角はプロバイダが [MapCameraPositionInterface.fov] として持つ値を渡す。 + * コアは視野角の固定値を持たない。 + * + * - `fov > 0`: ピンホールカメラとして遠近込みで解く + * - `fov == 0`: 遠近なしの傾き(縦だけ cos(tilt) 倍に縮む)として解く + * - `fov == null`: 傾きを無視して tilt 0 として解く + * + * 単位: パディングと地図の高さは dp、ズームは統一ズーム(Google Maps 基準、256dp タイル)。 + */ +@InternalMapConductorApi +object CameraPaddingEmulation { + /** 視線が地平線に届かないよう、地面への角度をここで止める。 */ + private const val MAX_RAY_ANGLE_DEG = 89.0 + + /** + * [camera] のパディングを中心のずらしに置き換えた、ネイティブ SDK へ渡すカメラ。 + * 返すカメラの paddings は 0。パディングが無ければ [camera] をそのまま返す。 + * + * @param viewportHeight 地図の高さ(dp) + */ + fun toNativeCamera( + camera: MapCameraPosition, + fov: Double?, + viewportHeight: Double, + ): MapCameraPosition { + if (camera.paddings.isZero()) return camera + val center = + centerForTarget( + target = camera.position, + zoom = camera.zoom, + tilt = camera.tilt, + heading = CameraBearing.toNativeHeading(camera.bearing), + paddings = camera.paddings, + fov = fov, + viewportHeight = viewportHeight, + ) + return camera.copy(position = center, paddings = MapPaddings.Zeros) + } + + /** + * [toNativeCamera] の逆。ネイティブ SDK から読んだカメラ(中心が画面中央)を、 + * [paddings] を付けたカメラ(position がパディング中央)に直す。fov も入れる。 + */ + fun fromNativeCamera( + camera: MapCameraPosition, + paddings: MapPaddingsInterface?, + fov: Double?, + viewportHeight: Double, + ): MapCameraPosition { + val effective = paddings ?: MapPaddings.Zeros + if (effective.isZero()) return camera.copy(paddings = MapPaddings.Zeros, fov = fov) + val target = + targetForCenter( + center = camera.position, + zoom = camera.zoom, + tilt = camera.tilt, + heading = CameraBearing.toNativeHeading(camera.bearing), + paddings = effective, + fov = fov, + viewportHeight = viewportHeight, + ) + return camera.copy(position = target, paddings = effective, fov = fov) + } + + private fun MapPaddingsInterface?.isZero(): Boolean = + this == null || (top == 0.0 && left == 0.0 && bottom == 0.0 && right == 0.0) + + /** + * パディング付きのカメラで [target] を見るために、ネイティブ SDK へ渡すカメラ中心。 + * + * @param heading カメラの向き(北から時計回り、ネイティブ SDK の heading)。 + * MapConductor の bearing からは [CameraBearing.toNativeHeading] で得る。 + */ + fun centerForTarget( + target: GeoPointInterface, + zoom: Double, + tilt: Double, + heading: Double, + paddings: MapPaddingsInterface?, + fov: Double?, + viewportHeight: Double, + ): GeoPoint { + // ズームの縮尺はカメラ中心の緯度で決まるが、中心はまだ分からない。target の緯度で + // 一度解き、求めた中心の緯度で解き直す(差は数十 cm 以下になる)。 + var center: GeoPoint = GeoPoint.from(target) + repeat(2) { + val (forward, right) = + groundOffset(paddings, zoom, center.latitude, tilt, fov, viewportHeight) + ?: return GeoPoint.from(target) + // target は中心から (forward, right) にある。中心はその逆。 + center = move(target, -forward, -right, heading) + } + return center + } + + /** [centerForTarget] の逆。ネイティブ SDK のカメラ中心から、パディング付きの位置を求める。 */ + fun targetForCenter( + center: GeoPointInterface, + zoom: Double, + tilt: Double, + heading: Double, + paddings: MapPaddingsInterface?, + fov: Double?, + viewportHeight: Double, + ): GeoPoint { + val (forward, right) = + groundOffset(paddings, zoom, center.latitude, tilt, fov, viewportHeight) + ?: return GeoPoint.from(center) + return move(center, forward, right, heading) + } + + /** + * 画面中央からパディング中央へのずれを、地上の (前方, 右) メートルで返す。 + * 前方はカメラの向き。ずれが無ければ null。 + */ + internal fun groundOffset( + paddings: MapPaddingsInterface?, + zoom: Double, + latitude: Double, + tilt: Double, + fov: Double?, + viewportHeight: Double, + ): Pair? { + if (paddings == null) return null + val dx = (paddings.left - paddings.right) / 2.0 + val dy = (paddings.top - paddings.bottom) / 2.0 + if (abs(dx) < 1e-9 && abs(dy) < 1e-9) return null + + val metersPerDp = + AbstractZoomAltitudeConverter.WEB_MERCATOR_INITIAL_MPP_256 * + cos(Math.toRadians(latitude.coerceIn(-85.0, 85.0))) / 2.0.pow(zoom) + val t = Math.toRadians(tilt.coerceIn(0.0, MAX_RAY_ANGLE_DEG)) + + // 画面の下向き (dy > 0) は地上では手前(前方の負)。 + if (fov == null || t == 0.0 || viewportHeight <= 0.0) { + return Pair(-dy * metersPerDp, dx * metersPerDp) + } + if (fov <= 0.0) { + return Pair(-dy * metersPerDp / max(cos(t), 0.05), dx * metersPerDp) + } + + val f = (viewportHeight / 2.0) / tan(Math.toRadians(fov) / 2.0) + val distance = f * metersPerDp + val height = distance * cos(t) + val alpha = atan(dy / f) + val ray = min(t - alpha, Math.toRadians(MAX_RAY_ANGLE_DEG)) + // カメラ直下から見た、パディング中央の地点と画面中央の地点までの水平距離の差。 + val back = distance * sin(t) - height * tan(ray) + // 光軸方向の奥行きに比例して横の 1dp が伸びる。 + val depth = height / cos(ray) * cos(alpha) + val right = dx * depth / f + return Pair(-back, right) + } + + private fun move( + origin: GeoPointInterface, + forward: Double, + right: Double, + heading: Double, + ): GeoPoint { + val distance = hypot(forward, right) + if (distance < 1e-9) return GeoPoint.from(origin) + val direction = heading + Math.toDegrees(atan2(right, forward)) + val moved = Spherical.computeOffset(origin, distance, direction) + return GeoPoint(latitude = moved.latitude, longitude = moved.longitude, altitude = origin.altitude ?: 0.0) + } +} diff --git a/src/main/java/com/mapconductor/core/map/MapCameraPositionBase.kt b/src/main/java/com/mapconductor/core/map/MapCameraPositionBase.kt index 9500e2e..eb1f93c 100644 --- a/src/main/java/com/mapconductor/core/map/MapCameraPositionBase.kt +++ b/src/main/java/com/mapconductor/core/map/MapCameraPositionBase.kt @@ -16,42 +16,114 @@ data class VisibleRegion( interface MapCameraPositionInterface { val position: GeoPointInterface val zoom: Double + + /** + * 地図の回転角(度、0 が北)。 + * + * 値を増やすと地図は**時計回り(右)**に回る。90 なら地図が右へ 90 度回り、 + * 画面の上には西が来る。多くのネイティブ SDK の「カメラの向き(heading)」とは + * 符号が逆なので、変換は [CameraBearing] を通すこと。 + */ val bearing: Double val tilt: Double val paddings: MapPaddingsInterface? val visibleRegion: VisibleRegion? + + /** + * 描画しているカメラの**縦方向**の視野角(度)。今の地図の大きさでの値。 + * + * 地図SDKごとに違う(MapLibre 系は約 37°、Google Maps は約 25° など)。値は + * 各プロバイダが持ち、コアは固定値を持たない。 + * + * - `0.0`: tilt を遠近なしで描いている(傾きをエミュレートしているプロバイダ) + * - `null`: 分からない、または地図を傾けられない + * + * [visibleRegion] と同じく**読み取り専用**: カメラを読んだときに入り、 + * カメラを動かすときには使われない。 + */ + val fov: Double? get() = null } class MapCameraPosition( position: GeoPointInterface, - override val zoom: Double = 0.0, - override val bearing: Double = 0.0, - override val tilt: Double = 0.0, + zoom: Double? = null, + bearing: Double? = null, + tilt: Double? = null, override val paddings: MapPaddingsInterface? = MapPaddings.Companion.Zeros, override val visibleRegion: VisibleRegion? = null, + override val fov: Double? = null, ) : MapCameraPositionInterface { override val position: GeoPoint = GeoPoint.from(position) + // 指定された値。null は未指定。 + private val givenZoom: Double? = zoom + private val givenBearing: Double? = bearing + private val givenTilt: Double? = tilt + + /** 指定されなかったときは 0。指定されたかどうかは [isZoomSpecified] で区別する。 */ + override val zoom: Double = zoom ?: 0.0 + + /** 指定されなかったときは 0。指定されたかどうかは [isBearingSpecified] で区別する。 */ + override val bearing: Double = bearing ?: 0.0 + + /** 指定されなかったときは 0。指定されたかどうかは [isTiltSpecified] で区別する。 */ + override val tilt: Double = tilt ?: 0.0 + + /** + * `zoom` / `bearing` / `tilt` が明示されたか。 + * + * 明示された 0(zoom 0 = 世界全体、真北、真上から)と未指定を区別するために持つ。 + * [MapViewState.moveCameraTo] は未指定のプロパティだけを現在のカメラから + * 引き継ぐ([resolvedOnto])。 + */ + val isZoomSpecified: Boolean get() = givenZoom != null + val isBearingSpecified: Boolean get() = givenBearing != null + val isTiltSpecified: Boolean get() = givenTilt != null + + /** + * 未指定の `zoom` / `bearing` / `tilt` と、[paddings] の省略した辺を [current] の値で + * 埋めたカメラを返す。 + * + * 明示されたプロパティは、0 であってもそのまま使う。余白は辺ごとに埋める + * ([MapPaddings.resolvedOnto])。 + */ + fun resolvedOnto(current: MapCameraPositionInterface): MapCameraPosition { + val partialPaddings = (paddings as? MapPaddings)?.takeUnless { it.isFullySpecified } + if (isZoomSpecified && isBearingSpecified && isTiltSpecified && partialPaddings == null) return this + return MapCameraPosition( + position = position, + zoom = givenZoom ?: current.zoom, + bearing = givenBearing ?: current.bearing, + tilt = givenTilt ?: current.tilt, + paddings = partialPaddings?.resolvedOnto(current.paddings) ?: paddings, + visibleRegion = visibleRegion, + fov = fov, + ) + } + fun equals(other: MapCameraPositionInterface): Boolean = this.position.equals(other = other.position) && this.zoomEquals(other) && this.bearingEquals(other) && this.tiltEquals(other) + // 渡されなかったプロパティは、未指定だったならコピー後も未指定のまま。 fun copy( position: GeoPointInterface? = this.position, - zoom: Double? = this.zoom, - bearing: Double? = this.bearing, - tilt: Double? = this.tilt, + zoom: Double? = this.givenZoom, + bearing: Double? = this.givenBearing, + tilt: Double? = this.givenTilt, paddings: MapPaddingsInterface? = this.paddings, visibleRegion: VisibleRegion? = this.visibleRegion, + fov: Double? = this.fov, ) = MapCameraPosition( position = position ?: this.position, - zoom = zoom ?: this.zoom, - bearing = bearing ?: this.bearing, - tilt = tilt ?: this.tilt, + zoom = zoom ?: this.givenZoom, + bearing = bearing ?: this.givenBearing, + tilt = tilt ?: this.givenTilt, paddings = paddings ?: this.paddings, visibleRegion = visibleRegion ?: this.visibleRegion, + fov = fov ?: this.fov, ) private fun zoomEquals(other: MapCameraPositionInterface): Boolean { diff --git a/src/main/java/com/mapconductor/core/map/MapPaddingsImpl.kt b/src/main/java/com/mapconductor/core/map/MapPaddingsImpl.kt index bbb8534..f9e747d 100644 --- a/src/main/java/com/mapconductor/core/map/MapPaddingsImpl.kt +++ b/src/main/java/com/mapconductor/core/map/MapPaddingsImpl.kt @@ -7,17 +7,81 @@ interface MapPaddingsInterface { val right: Double } +/** + * 地図の端から空ける幅(dp)。 + * + * 4 辺はそれぞれ省略できる。省略した辺は、カメラを動かすときに + * [MapViewState.moveCameraTo] が**今のカメラの同じ辺**から引き継ぐ + * ([MapCameraPosition.resolvedOnto])。`MapPaddings(top = 300.0)` なら上だけが + * 300 になり、左・下・右は今のまま。明示された 0 はそのまま 0 として使う。 + * + * 読むときは省略した辺も 0 を返す。省略したかどうかは [isTopSpecified] などで区別する。 + * `paddings` 自体を渡さなかったとき([MapCameraPosition] の既定 [Zeros])は従来どおり + * 4 辺とも 0 で、余白を外す意味になる。 + */ open class MapPaddings @JvmOverloads constructor( - override val top: Double = 0.0, - override val left: Double = 0.0, - override val bottom: Double = 0.0, - override val right: Double = 0.0, + top: Double? = null, + left: Double? = null, + bottom: Double? = null, + right: Double? = null, ) : MapPaddingsInterface { + /** + * 4 辺すべてを指定するコンストラクタ。 + * + * 以前の `MapPaddings(double, double, double, double)` と同じ JVM シグネチャを残して、 + * それを呼んでいた Java / コンパイル済みのコードを壊さないために持つ。 + */ + constructor(top: Double, left: Double, bottom: Double, right: Double) : + this(top as Double?, left as Double?, bottom as Double?, right as Double?) + + // 指定された値。null は省略。 + private val givenTop: Double? = top + private val givenLeft: Double? = left + private val givenBottom: Double? = bottom + private val givenRight: Double? = right + + /** 省略したときは 0。省略したかどうかは [isTopSpecified] で区別する。 */ + override val top: Double = top ?: 0.0 + + /** 省略したときは 0。省略したかどうかは [isLeftSpecified] で区別する。 */ + override val left: Double = left ?: 0.0 + + /** 省略したときは 0。省略したかどうかは [isBottomSpecified] で区別する。 */ + override val bottom: Double = bottom ?: 0.0 + + /** 省略したときは 0。省略したかどうかは [isRightSpecified] で区別する。 */ + override val right: Double = right ?: 0.0 + + val isTopSpecified: Boolean get() = givenTop != null + val isLeftSpecified: Boolean get() = givenLeft != null + val isBottomSpecified: Boolean get() = givenBottom != null + val isRightSpecified: Boolean get() = givenRight != null + + /** 4 辺とも指定されているか。 */ + val isFullySpecified: Boolean + get() = isTopSpecified && isLeftSpecified && isBottomSpecified && isRightSpecified + + /** + * 省略した辺を [current] の同じ辺で埋めた余白を返す。[current] が null なら 0 で埋める。 + * + * 4 辺とも指定されていれば自分自身を返す。 + */ + fun resolvedOnto(current: MapPaddingsInterface?): MapPaddings { + if (isFullySpecified) return this + return MapPaddings( + top = givenTop ?: current?.top ?: 0.0, + left = givenLeft ?: current?.left ?: 0.0, + bottom = givenBottom ?: current?.bottom ?: 0.0, + right = givenRight ?: current?.right ?: 0.0, + ) + } + companion object { val Zeros: MapPaddings = MapPaddings(0.0, 0.0, 0.0, 0.0) + /** [MapPaddings] はそのまま返す(省略した辺は省略したまま)。それ以外は 4 辺とも指定扱い。 */ fun from(paddings: MapPaddingsInterface) = when (paddings) { is MapPaddings -> paddings diff --git a/src/main/java/com/mapconductor/core/map/MapUISettings.kt b/src/main/java/com/mapconductor/core/map/MapUISettings.kt index e1ad308..cefac7b 100644 --- a/src/main/java/com/mapconductor/core/map/MapUISettings.kt +++ b/src/main/java/com/mapconductor/core/map/MapUISettings.kt @@ -19,6 +19,7 @@ data class MapUISettings( val rotateGesture: Boolean = true, /** Tilt the map (change pitch). */ val tiltGesture: Boolean = true, + val paddings: MapPaddings = MapPaddings.Zeros, ) { companion object { /** All gestures enabled — the default. */ @@ -31,6 +32,7 @@ data class MapUISettings( zoomGesture = false, rotateGesture = false, tiltGesture = false, + paddings = MapPaddings.Zeros, ) } } diff --git a/src/main/java/com/mapconductor/core/map/MapViewHolderInterface.kt b/src/main/java/com/mapconductor/core/map/MapViewHolderInterface.kt index 2392ded..0948e68 100644 --- a/src/main/java/com/mapconductor/core/map/MapViewHolderInterface.kt +++ b/src/main/java/com/mapconductor/core/map/MapViewHolderInterface.kt @@ -3,6 +3,9 @@ package com.mapconductor.core.map import androidx.compose.ui.geometry.Offset import com.mapconductor.core.features.GeoPoint import com.mapconductor.core.features.GeoPointInterface +import com.mapconductor.core.projection.MapCoordinateSystem +import com.mapconductor.core.projection.ProjectedPoint +import com.mapconductor.core.projection.WebMercator interface MapViewHolderInterface { val mapView: ActualMapView @@ -36,4 +39,28 @@ interface MapViewHolderInterface { * 既定 null のまま黙って無反応にしない。 */ fun fromScreenOffsetSync(offset: Offset): GeoPoint? = null + + /** + * 地図エンジンが今使っている座標系。[toProjectedPoint] の値はこの座標系になる。 + * + * 既定は EPSG:3857 メートル。Mercator しか持たないエンジンと、地球儀表示中の + * エンジンはこのままでよい。地図ごとに座標系を持てるエンジン(ArcGIS など) + * だけが上書きする。 + */ + val coordinateSystem: MapCoordinateSystem + get() = MapCoordinateSystem.WebMercator + + /** + * 地理座標 → [coordinateSystem] の投影座標。**画面座標ではない。** + * + * 投影の定義域の外などで変換できないときは null。既定は EPSG:3857。 + */ + fun toProjectedPoint(position: GeoPointInterface): ProjectedPoint? = WebMercator.project(position) + + /** + * [coordinateSystem] の投影座標 → 地理座標。[toProjectedPoint] の逆。 + * + * 変換できないときは null。既定は EPSG:3857。 + */ + fun fromProjectedPoint(point: ProjectedPoint): GeoPoint? = GeoPoint.from(WebMercator.unproject(point)) } diff --git a/src/main/java/com/mapconductor/core/map/MapViewState.kt b/src/main/java/com/mapconductor/core/map/MapViewState.kt index b41cc49..9ce07ed 100644 --- a/src/main/java/com/mapconductor/core/map/MapViewState.kt +++ b/src/main/java/com/mapconductor/core/map/MapViewState.kt @@ -99,6 +99,7 @@ interface MapViewStateInterface { abstract class MapViewState( initialCameraPosition: MapCameraPosition = MapCameraPosition.Default, private val optimisticCameraUpdate: Boolean = false, + paddings: MapPaddings = MapPaddings.Zeros, ) : MapViewStateInterface { /** @see MapViewStateInterface.serviceRegistry */ override val serviceRegistry: MutableMapServiceRegistry = MutableMapServiceRegistry() @@ -147,6 +148,23 @@ abstract class MapViewState( this.attachedMapController = null } + /** + * 破棄した [controller] を手放す。地図が壊されたあとで呼ぶ。 + * + * state は地図より長生きする(アプリが保持し、プロバイダを切り替えても残る)。 + * ここで手放さないと、state が最後のコントローラ(とその全オーバーレイ)を + * 抱えたままになる。Compose では `MapViewBase` が地図をコンポジションから + * 外したときに呼ぶので、プロバイダが呼ぶ必要はない。 + * + * その間に別のコントローラが接続されていれば何もしない(新しい地図を + * 古い地図の後始末で切り離さないため)。 + */ + fun detachController(controller: MapViewControllerInterface) { + if (this.attachedMapController === controller) { + this.attachedMapController = null + } + } + /** * 地図から通知された現在のカメラを保持する(地図を動かさない)。 * @@ -168,22 +186,25 @@ abstract class MapViewState( cameraPosition: MapCameraPosition, durationMillis: Long?, ) { + // 明示されたプロパティは 0 でもそのまま使い、未指定のものだけ現在のカメラから + // 引き継ぐ。`MapCameraPosition(position = ...)` なら位置だけが動く。 + val resolved = cameraPosition.resolvedOnto(_cameraPosition) val ctrl = attachedMapController if (ctrl == null) { // まだ地図が無い。接続時に attachController がこの位置へ移動する。 - _cameraPosition = cameraPosition + _cameraPosition = resolved return } if (optimisticCameraUpdate) { - _cameraPosition = cameraPosition + _cameraPosition = resolved } // 引数は既に MapCameraPosition なので、プロバイダごとの // `MapCameraPosition.Companion.from` は恒等変換になる(どの実装も // `is MapCameraPosition -> position` で素通しする)。ここでは呼ばない。 if (durationMillis == null || durationMillis == 0L) { - ctrl.moveCamera(cameraPosition) + ctrl.moveCamera(resolved) } else { - ctrl.animateCamera(cameraPosition, durationMillis) + ctrl.animateCamera(resolved, durationMillis) } } diff --git a/src/main/java/com/mapconductor/core/map/MapViewStateBundle.kt b/src/main/java/com/mapconductor/core/map/MapViewStateBundle.kt new file mode 100644 index 0000000..991cf0a --- /dev/null +++ b/src/main/java/com/mapconductor/core/map/MapViewStateBundle.kt @@ -0,0 +1,191 @@ +package com.mapconductor.core.map + +import com.mapconductor.core.InternalMapConductorApi +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.features.GeoRectBounds +import android.os.Bundle + +/** + * `rememberSaveable` の Saver([BaseMapViewSaver] とプロバイダごとの `*MapViewSaver`)が + * state を [Bundle] へ書き出し、読み戻すための共通部品。 + * + * ## なぜ要るか + * + * 画面回転などの構成変更で Activity が作り直されると、state は Saver が [Bundle] に + * 書いたものからだけ作り直される。書かなかった値は**黙って既定値に戻る** + * (デザインの attributionRules が消える、uiSettings が全部 true に戻る、など)。 + * どのプロバイダも同じ値を同じ形で書けるよう、ここにまとめる。 + * + * ## 値の形 + * + * [Bundle] にはプリミティブと入れ子の [Bundle] だけを入れる。`Serializable` を使わない + * のは、プロセスが落ちたあとの復元でもクラスローダーに依存せず読めるようにするため。 + * リストは「件数 + 添字をキーにした子 Bundle」で表す。 + */ +@InternalMapConductorApi +object MapViewStateBundle { + /** プロバイダの design Bundle で attributionRules を入れるキー。 */ + const val KEY_ATTRIBUTION_RULES: String = "attributionRules" + + /** [BaseMapViewSaver] が uiSettings を入れるキー。 */ + const val KEY_UI_SETTINGS: String = "uiSettings" + + // ---- AttributionRule ------------------------------------------------- + + fun putAttributionRules( + bundle: Bundle, + rules: List, + key: String = KEY_ATTRIBUTION_RULES, + ) { + bundle.putBundle(key, attributionRulesToBundle(rules)) + } + + /** 保存されていなければ空リスト。 */ + fun getAttributionRules( + bundle: Bundle?, + key: String = KEY_ATTRIBUTION_RULES, + ): List = attributionRulesFromBundle(bundle?.getBundle(key)) + + fun attributionRulesToBundle(rules: List): Bundle = + Bundle().apply { + putInt(KEY_COUNT, rules.size) + rules.forEachIndexed { index, rule -> + putBundle(index.toString(), attributionRuleToBundle(rule)) + } + } + + fun attributionRulesFromBundle(bundle: Bundle?): List { + if (bundle == null) return emptyList() + val count = bundle.getInt(KEY_COUNT, 0) + return (0 until count).mapNotNull { index -> + attributionRuleFromBundle(bundle.getBundle(index.toString())) + } + } + + private fun attributionRuleToBundle(rule: AttributionRule): Bundle = + Bundle().apply { + putString("attribution", rule.attribution) + rule.minZoom?.let { putInt("minZoom", it) } + rule.maxZoom?.let { putInt("maxZoom", it) } + rule.bounds?.let { putBundle("bounds", boundsToBundle(it)) } + } + + private fun attributionRuleFromBundle(bundle: Bundle?): AttributionRule? { + val attribution = bundle?.getString("attribution") ?: return null + return AttributionRule( + attribution = attribution, + minZoom = if (bundle.containsKey("minZoom")) bundle.getInt("minZoom") else null, + maxZoom = if (bundle.containsKey("maxZoom")) bundle.getInt("maxZoom") else null, + bounds = bundle.getBundle("bounds")?.let(::boundsFromBundle), + ) + } + + private fun boundsToBundle(bounds: GeoRectBounds): Bundle = + Bundle().apply { + bounds.southWest?.let { putBundle("southWest", pointToBundle(it)) } + bounds.northEast?.let { putBundle("northEast", pointToBundle(it)) } + } + + private fun boundsFromBundle(bundle: Bundle): GeoRectBounds = + GeoRectBounds( + southWest = bundle.getBundle("southWest")?.let(::pointFromBundle), + northEast = bundle.getBundle("northEast")?.let(::pointFromBundle), + ) + + private fun pointToBundle(point: GeoPoint): Bundle = + Bundle().apply { + putDouble("latitude", point.latitude) + putDouble("longitude", point.longitude) + putDouble("altitude", point.altitude) + } + + private fun pointFromBundle(bundle: Bundle): GeoPoint = + GeoPoint( + latitude = bundle.getDouble("latitude"), + longitude = bundle.getDouble("longitude"), + altitude = bundle.getDouble("altitude"), + ) + + // ---- MapPaddings ------------------------------------------------------ + + fun paddingsToBundle(paddings: MapPaddingsInterface): Bundle = + Bundle().apply { + putDouble("top", paddings.top) + putDouble("left", paddings.left) + putDouble("bottom", paddings.bottom) + putDouble("right", paddings.right) + } + + fun paddingsFromBundle(bundle: Bundle?): MapPaddings? { + if (bundle == null) return null + return MapPaddings( + top = bundle.getDouble("top"), + left = bundle.getDouble("left"), + bottom = bundle.getDouble("bottom"), + right = bundle.getDouble("right"), + ) + } + + // ---- MapUISettings ---------------------------------------------------- + + fun uiSettingsToBundle(settings: MapUISettings): Bundle = + Bundle().apply { + putBoolean("scrollGesture", settings.scrollGesture) + putBoolean("zoomGesture", settings.zoomGesture) + putBoolean("rotateGesture", settings.rotateGesture) + putBoolean("tiltGesture", settings.tiltGesture) + putBundle("paddings", paddingsToBundle(settings.paddings)) + } + + /** 保存されていなければ null(呼び出し側は state の既定値をそのまま使う)。 */ + fun uiSettingsFromBundle(bundle: Bundle?): MapUISettings? { + if (bundle == null) return null + return MapUISettings( + scrollGesture = bundle.getBoolean("scrollGesture", true), + zoomGesture = bundle.getBoolean("zoomGesture", true), + rotateGesture = bundle.getBoolean("rotateGesture", true), + tiltGesture = bundle.getBoolean("tiltGesture", true), + paddings = paddingsFromBundle(bundle.getBundle("paddings")) ?: MapPaddings.Zeros, + ) + } + + // ---- MapCameraPosition ----------------------------------------------- + + /** + * カメラを書き出す。キー(zoom / tilt / bearing / latitude / longitude)は + * 以前の [BaseMapViewSaver] と同じなので、古い Bundle もそのまま読める。 + * `visibleRegion` は地図が描画のたびに計算し直すので保存しない。 + */ + fun cameraToBundle(camera: MapCameraPositionInterface): Bundle = + Bundle().apply { + putDouble("zoom", camera.zoom) + putDouble("tilt", camera.tilt) + putDouble("bearing", camera.bearing) + putDouble("latitude", camera.position.latitude) + putDouble("longitude", camera.position.longitude) + putDouble("altitude", camera.position.altitude ?: 0.0) + camera.paddings?.let { putBundle("paddings", paddingsToBundle(it)) } + } + + /** + * @param fallbackPaddings paddings が保存されていなかったとき(以前の形式の Bundle)に使う値。 + */ + fun cameraFromBundle( + bundle: Bundle?, + fallbackPaddings: MapPaddingsInterface? = null, + ): MapCameraPosition = + MapCameraPosition( + position = + GeoPoint( + latitude = bundle?.getDouble("latitude") ?: 0.0, + longitude = bundle?.getDouble("longitude") ?: 0.0, + altitude = bundle?.getDouble("altitude") ?: 0.0, + ), + zoom = bundle?.getDouble("zoom") ?: 0.0, + bearing = bundle?.getDouble("bearing") ?: 0.0, + tilt = bundle?.getDouble("tilt") ?: 0.0, + paddings = paddingsFromBundle(bundle?.getBundle("paddings")) ?: fallbackPaddings, + ) + + private const val KEY_COUNT = "count" +} diff --git a/src/main/java/com/mapconductor/core/map/MapViewStyle.kt b/src/main/java/com/mapconductor/core/map/MapViewStyle.kt new file mode 100644 index 0000000..d2c0269 --- /dev/null +++ b/src/main/java/com/mapconductor/core/map/MapViewStyle.kt @@ -0,0 +1,156 @@ +package com.mapconductor.core.map + +import androidx.compose.runtime.Stable +import com.mapconductor.core.raster.RasterLayerState +import com.mapconductor.core.tileserver.LocalTileServer + +/** + * How a map looks, as a property of the map rather than a layer inside it. + * + * A vector style *is* the basemap, so passing one to `XxxMapView(style = ...)` + * says what it is rather than mounting something over it. What happens + * underneath depends on the backend and the app does not have to know: + * MapLibre, Mapbox and MapTiler are told the style and draw it themselves; + * Google Maps, MapKit, HERE, ArcGIS and the rest are handed raster tiles + * rendered from the same style on the device. Either way the same + * adjustments produce the same map. + * + * An interface rather than a class, for two reasons. Core must not depend on + * the style compiler or the rasteriser — both are optional modules, and one + * of them is a megabyte of native code — so what core holds is the seam and + * the modules bring the implementation. And a provider's own styling, which + * is nothing like a MapLibre style, can be added later as another + * implementation without this changing. + * + * The concrete implementations live in the vector style module + * (`com.mapconductor:vectorstyle`); an app does not implement this. + * + * ios-sdk-core and js-sdk-core carry the same seam. + */ +@Stable +interface MapViewStyle { + /** + * What identifies this style's content. + * + * The map re-installs a style whose key changed and leaves alone one + * whose key did not. Two instances describing the same thing must have + * the same key: a style built inline in a composable is a new instance + * on every recomposition — which is exactly what a colour picker + * produces — and keying off instance identity would reinstall the whole + * style on every unrelated state change. + */ + val key: String + + /** + * Puts the style on the map. Called once the map has a style loaded, + * and again if it loads another one. + * + * @return the ticket that takes it off again. Disposing must leave the + * map as it was found: a style that cannot be fully undone has no + * business being installed, because the app will switch away from it. + */ + fun install(host: MapStyleHost): MapStyleInstallation +} + +/** + * A ticket to undo, and a chance to take a change without tearing down. + * + * Returned by anything that sets something up on a map. + */ +interface MapStyleInstallation { + fun dispose() + + /** + * Takes [next] in place, when it is near enough to what is installed. + * + * Without this the whole point is lost. A style whose key changed is + * installed again, and installing a style means handing the map a + * document -- which is the reload this design exists to avoid. Moving a + * colour slider changes the adjustments and nothing else, so the + * installed style answers true, applies the difference, and the map + * never reloads anything. + * + * @return false when it cannot, and the caller disposes and installs + * [next] from scratch. False is always correct, only slower. + */ + fun update(next: MapViewStyle): Boolean = false + + companion object { + /** For a style that set nothing up. */ + @JvmField + val NONE: MapStyleInstallation = + object : MapStyleInstallation { + override fun dispose() = Unit + } + + /** The common case: one thing to undo, nothing that can be updated. */ + @JvmStatic + fun of(dispose: () -> Unit): MapStyleInstallation = + object : MapStyleInstallation { + override fun dispose() = dispose() + } + } +} + +/** + * What a map offers to the style installed on it. + * + * The provider implements this; a [MapViewStyle] uses it and never touches + * a provider type. That is what keeps one style implementation working on + * every backend. + */ +interface MapStyleHost { + /** + * Where to look for what this map can do: + * [VectorStyleSupportKey] to hand over a style document, + * [VectorStyleMutationSupportKey] to change a loaded one in place, + * [com.mapconductor.core.raster.RasterTilePreferenceKey] for the tile + * size it would rather have. + */ + val serviceRegistry: MapServiceRegistry + + /** For serving a style document, or tiles rendered from one, to the map. */ + val tileServer: LocalTileServer + + /** + * The vector style the map is drawing now, when it is drawing one. + * + * Null on every backend that has no such thing, which is most of them. + * It is how a rule set that adjusts "whatever is showing" finds + * something to adjust: the style has to be read before a rule can be + * matched against its layers, and only the map knows where it came from. + */ + val vectorStyleUrl: String? + get() = null + + /** + * Runs [block] whenever the map finishes loading a style, including the + * one it has now if it already has one. + * + * Everything a style installs on a live renderer is lost when that + * renderer loads a document again, for any reason. This is how it gets + * put back. + */ + fun onStyleLoaded(block: () -> Unit): MapStyleInstallation + + /** + * Adds or updates a raster layer the app did not declare. + * + * The raster path needs somewhere to put its tiles, and that cannot be + * the content block: the style is a property of the view, so it is + * installed from outside the composition. Marker tiling already mounts + * its layer the same way. + */ + fun upsertRaster(state: RasterLayerState) + + fun removeRaster(id: String) + + /** + * Says what the app should know: a rule that matched nothing, an + * adjustment this backend cannot make, a style that could not be read. + * + * Routed to whatever the host gave the style, so a module can report + * without knowing how the app logs. + */ + fun report(diagnostics: List) +} diff --git a/src/main/java/com/mapconductor/core/map/MapViewStyleEffect.kt b/src/main/java/com/mapconductor/core/map/MapViewStyleEffect.kt new file mode 100644 index 0000000..6b21678 --- /dev/null +++ b/src/main/java/com/mapconductor/core/map/MapViewStyleEffect.kt @@ -0,0 +1,55 @@ +package com.mapconductor.core.map + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.SideEffect +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import com.mapconductor.core.controller.BaseMapViewController + +/** + * Keeps the map's [MapViewStyle] installed, for every provider. + * + * Each `XxxMapView` takes a `style` and calls this once; nothing else about + * a provider has to know what a vector style is. What a style then does to + * the map depends on what that map declared it can do — draw a style + * document, change a loaded one in place, or neither, in which case the + * style's own rasteriser renders tiles and they go on as a raster layer. + * + * The decisions are all in [MapViewStyleHost.apply]; what this adds is + * *when* to ask. Two of those are Compose's: + * + * - **On every composition, not only when `style` changes.** A style built + * inline is a new instance each time, and the one that matters — the one + * whose rules just moved — is indistinguishable from the one that did + * not. Only the host can tell, by its key, so it is asked every time. + * - **Not before the controller exists.** A style acts on a live map, and + * the provider builds its controller asynchronously. + * + * ios-sdk-core and js-sdk-react do the same work; the shape differs because + * each framework owns its lifecycle differently, and React Native does not + * do it at all — there the style is carried to this SDK rather than + * installed in JavaScript. + */ +@Composable +fun MapViewStyleEffect( + state: MapViewStateInterface<*>, + style: MapViewStyle?, + controller: BaseMapViewController?, + onDiagnostics: ((List) -> Unit)? = null, +) { + val report by rememberUpdatedState(onDiagnostics) + val host = remember(state, controller) { controller?.let { MapViewStyleHost(state.serviceRegistry, it) } } + + // `SideEffect` rather than a call in the composition body: a + // composition can be run more than once and thrown away, and installing + // a style is not something to do speculatively. This runs once per + // *successful* composition, with no keys, which is what "ask every + // time" means. The host is what decides whether anything happens. + SideEffect { host?.apply(style, report) } + + DisposableEffect(host) { + onDispose { host?.dispose() } + } +} diff --git a/src/main/java/com/mapconductor/core/map/MapViewStyleHost.kt b/src/main/java/com/mapconductor/core/map/MapViewStyleHost.kt new file mode 100644 index 0000000..ab4e0c2 --- /dev/null +++ b/src/main/java/com/mapconductor/core/map/MapViewStyleHost.kt @@ -0,0 +1,136 @@ +package com.mapconductor.core.map + +import com.mapconductor.core.controller.BaseMapViewController +import com.mapconductor.core.raster.RasterLayerState +import com.mapconductor.core.tileserver.LocalTileServer +import com.mapconductor.core.tileserver.TileServerRegistry + +/** + * What a map offers the style installed on it, for every provider at once. + * + * Provider-agnostic by construction: the three things a style needs that + * differ per backend are all reached through seams every provider already + * fills in — the service registry for what the map can do, the controller's + * overlay controllers for mounting tiles, and the controller's style-loaded + * listeners for putting an adjustment back after a reload. Adding a twelfth + * provider needs nothing here. + */ +class MapViewStyleHost( + /** + * What this map can do. The registry rather than the state, because + * React Native's wrapper has one and no state -- and the registry is + * all a style ever reads. ios-sdk and js-sdk-core take the same. + */ + override val serviceRegistry: MapServiceRegistry, + private val controller: BaseMapViewController, +) : MapStyleHost { + private var installation: MapStyleInstallation? = null + private var installedKey: String? = null + private var diagnosticsHandler: ((List) -> Unit)? = null + + /** How many updates in a row the installed style has refused. See [apply]. */ + private var refusedUpdates = 0 + + /** + * Keeps [style] installed on this map. + * + * Called on every recomposition (and on every React Native prop update), + * so most calls do nothing. Three things have to line up and none of + * them is the update: + * + * - **A style whose key did not change must be left alone.** A style + * built inline is a new instance every time — which is exactly what a + * colour picker produces — so comparing instances would reinstall on + * every unrelated state change. + * - **A changed style is usually an adjustment, not a new style.** + * Disposing and installing again hands the map a document and reloads + * it, which is the cost this whole design exists to avoid. What is + * installed is offered the new one first and only replaced if it + * refuses. + * - **Null means take it off.** An app that stops passing a style gets + * the map it had before, not the one the style left behind. + */ + fun apply( + style: MapViewStyle?, + onDiagnostics: ((List) -> Unit)? = null, + ) { + diagnosticsHandler = onDiagnostics + if (style == null) { + dispose() + return + } + val current = installation + if (current == null) { + installation = style.install(this) + installedKey = style.key + return + } + // Nothing changed at all. The key covers the document *and* the + // rules, so an equal key means there is no work -- and doing it + // anyway is not merely wasteful: recompiling re-reports the + // diagnostics, an app that renders them sets state, that recomposes, + // and the two spin against each other. + if (installedKey == style.key) return + + // The adjustments moved. Offer them to what is installed: taking + // them in place is what keeps a slider from reloading the map. + if (current.update(style)) { + installedKey = style.key + refusedUpdates = 0 + return + } + + // Refused -- correct, only slower. Refusing every time means the + // style cannot recognise its own successor and the map is rebuilt + // on each change; the usual cause is a value the style compares by + // identity being rebuilt too, a rasteriser constructed inline + // rather than held in `remember`. + refusedUpdates++ + if (refusedUpdates == CHURN_THRESHOLD) { + MapDiagnostics.sink.log( + "style: the installed style has refused $CHURN_THRESHOLD updates in a row, so " + + "the map is being torn down and rebuilt on every change. Hold the rasteriser " + + "(and anything else the style compares by identity) in `remember` rather " + + "than rebuilding it.", + ) + } + current.dispose() + installation = style.install(this) + installedKey = style.key + } + + /** Takes the style off. The caller does this when the view goes. */ + fun dispose() { + installation?.dispose() + installation = null + installedKey = null + } + + override val tileServer: LocalTileServer + get() = TileServerRegistry.get() + + override val vectorStyleUrl: String? + get() = serviceRegistry.get(VectorStyleSupportKey)?.currentStyleUrl + + override fun onStyleLoaded(block: () -> Unit): MapStyleInstallation = + MapStyleInstallation.of(controller.addStyleLoadedListener(block)) + + override fun upsertRaster(state: RasterLayerState) = controller.mountRasterLayer(state) + + override fun removeRaster(id: String) = controller.unmountRasterLayer(id) + + override fun report(diagnostics: List) { + if (diagnostics.isEmpty()) return + val handler = diagnosticsHandler + if (handler != null) { + handler(diagnostics) + return + } + // Never dropped. A rule that matched nothing, or an adjustment this + // backend could not make, is the kind of thing that otherwise shows + // up as "the style nearly worked" with no way to find out why. + diagnostics.forEach { MapDiagnostics.sink.log("style: $it") } + } +} + +private const val CHURN_THRESHOLD = 5 diff --git a/src/main/java/com/mapconductor/core/map/StyleMutation.kt b/src/main/java/com/mapconductor/core/map/StyleMutation.kt new file mode 100644 index 0000000..a4fc45e --- /dev/null +++ b/src/main/java/com/mapconductor/core/map/StyleMutation.kt @@ -0,0 +1,222 @@ +package com.mapconductor.core.map + +import org.json.JSONArray +import org.json.JSONObject + +/** + * One change to one layer of a vector style the map has already loaded. + * + * This is what lets a style be adjusted without being reloaded. Handing a + * map a new style document is the obvious way to change how it looks, and on + * every provider it is the expensive way: the renderer drops its tiles, + * re-reads the document, re-tessellates, and the overlays the app added have + * to be put back. A paint property set in place costs none of that. + * + * Mutations are produced by the vector style compiler from the same + * evaluation that produces the adjusted document, so the two can never + * disagree about what the style should look like. A provider that can take + * them declares [VectorStyleMutationSupport]. + * + * ## Why the values are JSON text + * + * A style property's value is anything the style spec allows: a string, a + * number, or an expression tree. Each provider needs it in its own form — + * MapLibre on Android wants a Gson tree, MapLibre on iOS an `NSExpression`, + * MapLibre in a browser the plain parsed value — so there is no shared typed + * representation that saves anyone a conversion. Text is the one form all + * three can start from, and it is what crossed the FFI boundary anyway. + * + * `"null"` means the property had no value, which is also how a renderer is + * told to go back to the spec default. + */ +sealed class StyleMutation { + /** The layer this acts on. Every mutation names one. */ + abstract val layerId: String + + /** + * What this mutation occupies, for working out which of two sets of + * mutations replace each other. Two mutations with the same target are + * the same change with different values. + */ + abstract val target: String + + /** + * What this mutation changes, named the way the style spec names it. + * + * For telling an app *what* a renderer would not do. The layer is the + * wrong thing to name on its own: when a backend has no property for a + * spec key, the same key fails on every layer that uses it, so a list + * of layers is hundreds of names for one cause while the key is the + * cause. + */ + open val propertyName: String + get() = "layer" + + /** The mutation that puts back what was there, or null when there is nothing to put back. */ + abstract fun reversed(): StyleMutation? + + data class SetPaint( + override val layerId: String, + val key: String, + /** JSON text. */ + val value: String, + /** JSON text of what was there before. */ + val previous: String, + ) : StyleMutation() { + override val target get() = "paint|$layerId|$key" + + override val propertyName: String get() = key + + override fun reversed() = SetPaint(layerId, key, previous, value) + } + + data class SetLayout( + override val layerId: String, + val key: String, + val value: String, + val previous: String, + ) : StyleMutation() { + override val target get() = "layout|$layerId|$key" + + override val propertyName: String get() = key + + override fun reversed() = SetLayout(layerId, key, previous, value) + } + + data class SetFilter( + override val layerId: String, + val value: String, + val previous: String, + ) : StyleMutation() { + override val target get() = "filter|$layerId" + + override val propertyName: String get() = "filter" + + override fun reversed() = SetFilter(layerId, previous, value) + } + + data class SetZoomRange( + override val layerId: String, + val minZoom: Double?, + val maxZoom: Double?, + val previousMinZoom: Double?, + val previousMaxZoom: Double?, + ) : StyleMutation() { + override val target get() = "zoom|$layerId" + + override val propertyName: String get() = "zoom range" + + override fun reversed() = SetZoomRange(layerId, previousMinZoom, previousMaxZoom, minZoom, maxZoom) + } + + /** + * Adds a layer the style did not have. + * + * Used for one thing: a background under a style that has none, so that + * "everything else muted" looks the same whether the style is drawn by + * the map or rasterised into tiles over another basemap. Without it the + * raster path leaves the gaps transparent and the two disagree. + */ + data class AddLayer( + /** + * The new layer's id. + * + * Carried rather than read back out of [layer]: the compiler knew + * it, every reader needs it, and three JSON parses of the same + * object to recover it are three chances to get it wrong. + */ + override val layerId: String, + /** JSON text of the whole layer object. */ + val layer: String, + /** Insert below this layer; null appends. */ + val beforeId: String?, + ) : StyleMutation() { + override val target get() = "add|$layerId" + + override fun reversed() = RemoveLayer(layerId) + } + + data class RemoveLayer( + override val layerId: String, + ) : StyleMutation() { + override val target get() = "add|$layerId" + + override fun reversed(): StyleMutation? = null + } + + companion object { + private const val TAG = "StyleMutation" + + /** + * Reads the compiler's `mutations` array. + * + * An entry this version does not know is skipped rather than fatal: + * the array is produced by the native library this host shipped with, + * so an unknown op means the two went out of step, and dropping one + * change is better than losing every change. + */ + @JvmStatic + fun parseList(json: String): List { + val array = runCatching { JSONArray(json) }.getOrNull() ?: return emptyList() + return (0 until array.length()).mapNotNull { index -> + array.optJSONObject(index)?.let(::parse) + } + } + + private fun parse(obj: JSONObject): StyleMutation? { + val layerId = obj.optString("layerId").takeIf { it.isNotEmpty() } + return when (obj.optString("op")) { + "setPaint" -> + layerId?.let { + SetPaint(it, obj.optString("key"), jsonTextOf(obj.opt("value")), jsonTextOf(obj.opt("previous"))) + } + "setLayout" -> + layerId?.let { + SetLayout(it, obj.optString("key"), jsonTextOf(obj.opt("value")), jsonTextOf(obj.opt("previous"))) + } + "setFilter" -> + layerId?.let { + SetFilter(it, jsonTextOf(obj.opt("value")), jsonTextOf(obj.opt("previous"))) + } + "setZoomRange" -> + layerId?.let { + SetZoomRange( + it, + obj.optDoubleOrNull("minZoom"), + obj.optDoubleOrNull("maxZoom"), + obj.optDoubleOrNull("previousMinZoom"), + obj.optDoubleOrNull("previousMaxZoom"), + ) + } + "addLayer" -> + obj.optJSONObject("layer")?.let { layer -> + layerId?.let { + AddLayer(it, layer.toString(), obj.optString("beforeId").takeIf { id -> id.isNotEmpty() }) + } + } + "removeLayer" -> layerId?.let(::RemoveLayer) + else -> null + } + } + + private fun JSONObject.optDoubleOrNull(key: String): Double? = + if (isNull(key)) null else optDouble(key).takeIf { !it.isNaN() } + + /** + * A JSON node as the text that would produce it. + * + * `org.json` has no "write this value" call -- `toString()` on a + * String gives the bare characters, which would turn `"none"` into + * something no parser can read back. + */ + @JvmStatic + fun jsonTextOf(value: Any?): String = + when (value) { + null, JSONObject.NULL -> "null" + is String -> JSONObject.quote(value) + is JSONObject, is JSONArray -> value.toString() + is Boolean, is Number -> value.toString() + else -> JSONObject.quote(value.toString()) + } + } +} diff --git a/src/main/java/com/mapconductor/core/map/VectorStyleMutationSupport.kt b/src/main/java/com/mapconductor/core/map/VectorStyleMutationSupport.kt new file mode 100644 index 0000000..2a820b9 --- /dev/null +++ b/src/main/java/com/mapconductor/core/map/VectorStyleMutationSupport.kt @@ -0,0 +1,113 @@ +package com.mapconductor.core.map + +/** + * A map that can be told to change a loaded style in place. + * + * Separate from [VectorStyleSupport], which is about making a style *be* the + * basemap. This one is about changing the one that is already up, without + * the reload that would otherwise cost every tile on screen and every + * overlay the app added. A provider declares it under + * [VectorStyleMutationSupportKey]. + * + * Not every provider can take every change: MapLibre on iOS exposes its + * paint properties as typed `NSExpression`s rather than by name, so a raw + * style-spec key it has no mapping for cannot be set. That is why [apply] + * answers with what it could not do instead of returning nothing — a caller + * that silently assumed success would show a map that is half adjusted and + * say nothing about it. + * + * ios-sdk-core and js-sdk-core carry the same capability. + */ +interface VectorStyleMutationSupport { + /** + * Applies [mutations] to the live style, replacing any set applied + * before: anything the previous set changed and this one does not is put + * back the way it was. + * + * @return the mutations that could not be applied, empty when all were. + */ + fun apply(mutations: List): List + + /** Puts back everything [apply] changed. */ + fun clear() +} + +/** + * [VectorStyleMutationSupport] の登録キー。 + * + * 宣言しないプロバイダは「生きているスタイルは触れない」。スタイル調整は + * その場合、文書を差し替えるか(地図が読み直す)、ラスター経路で描き直す。 + */ +object VectorStyleMutationSupportKey : MapServiceKey + +/** + * The bookkeeping every provider's [VectorStyleMutationSupport] needs, so no + * provider has to get it right twice. + * + * Two things are easy to miss and both show up as "the adjustment worked, + * and then stopped": + * + * - **Replacing a set has to undo what it drops.** Moving a slider sends a + * whole new set each time. A property the new set no longer mentions must + * go back to the value the style gave it — and only the mutation knows + * that value, because by now the renderer's own idea of it is the one this + * put there. + * - **A style load wipes everything.** The app switching basemap, the + * provider reloading, a design change: whatever the reason, the renderer + * comes back with the document's own values and nothing this applied. The + * provider calls [onStyleLoaded] and the whole set goes on again. + * + * @param applyNow puts mutations on the live style and returns the ones it + * could not. Called on whatever thread [apply] was called on; a provider + * whose renderer is main-thread-only hops there itself. + */ +class StyleMutationStore( + private val applyNow: (List) -> List, +) : VectorStyleMutationSupport { + private val lock = Any() + private var current: List = emptyList() + + override fun apply(mutations: List): List { + val (restores, next) = + synchronized(lock) { + val targets = mutations.map { it.target }.toHashSet() + val restores = current.filter { it.target !in targets }.mapNotNull { it.reversed() } + current = mutations + restores to mutations + } + // Restores first: a property moving from one rule's value to no rule + // at all must pass through the style's own value, not stay on the + // old one because the new set happened to be applied first. + // + // Nothing is logged from here. What could not be applied is the + // caller's to report -- it has the app's diagnostics callback, and + // this class is plain logic that unit tests can run off a device. + return applyNow(restores + next) + } + + override fun clear() { + val restores = + synchronized(lock) { + val restores = current.mapNotNull { it.reversed() } + current = emptyList() + restores + } + if (restores.isNotEmpty()) applyNow(restores) + } + + /** + * Re-applies everything after the map has loaded a style. + * + * The provider calls this from whatever it has that fires on a style + * being ready. Without it an adjustment survives only until the next + * design change, which is the kind of bug that is found weeks later by + * someone switching basemap with a slider open. + */ + fun onStyleLoaded() { + val again = synchronized(lock) { current } + if (again.isNotEmpty()) applyNow(again) + } + + /** What is applied right now. For tests and diagnostics. */ + val applied: List get() = synchronized(lock) { current } +} diff --git a/src/main/java/com/mapconductor/core/map/VectorStyleSupport.kt b/src/main/java/com/mapconductor/core/map/VectorStyleSupport.kt new file mode 100644 index 0000000..1a410f3 --- /dev/null +++ b/src/main/java/com/mapconductor/core/map/VectorStyleSupport.kt @@ -0,0 +1,168 @@ +package com.mapconductor.core.map + +import android.os.Handler +import android.os.Looper +import android.util.Log + +/** + * A map that can draw a MapLibre style itself. + * + * MapLibre, Mapbox and MapTiler are vector renderers already: handing them a + * style document is cheaper than rasterising it on the device and feeding the + * result back as PNG tiles, which is what a backend that only takes raster + * (Google Maps, ArcGIS, HERE...) has to be given. A provider that can take + * the style directly registers this under [VectorStyleSupportKey]; a layer + * that has a style to show looks the key up and, if it is there, skips the + * rasteriser altogether. + * + * The style *becomes the basemap*: on every provider that can do this, the + * style is the map, so showing one replaces the design the state names and + * clearing it puts that design back. A style drawn this way is not an + * overlay -- it has no opacity, and nothing of the previous basemap shows + * through it. Anything that needs the style on top of another basemap goes + * through the raster path. + * + * ios-sdk-core and js-sdk-core carry the same capability. + */ +interface VectorStyleSupport { + /** + * Draws [styleUrl] as the map's basemap. + * + * [attributionRules] are the credits the style's sources ask for, carried + * by the design so the map's attribution overlay shows them for as long + * as the style is up. + */ + fun showStyle( + styleUrl: String, + attributionRules: List = emptyList(), + ) + + /** + * Restores the design that was showing before [showStyle], unless the app + * has since chosen another one, in which case that choice is left alone. + */ + fun clearStyle() + + /** + * Where the style the map is drawing came from, when that is knowable. + * + * This is what lets a rule set adjust *whatever is showing* rather than a + * style the app had to name: the document has to be read before a rule + * can be matched against its layers, and only the provider knows where + * it came from. + * + * Null when it is not a URL anything can fetch -- a provider's own named + * design (`mapbox://styles/mapbox/standard`), a style that needs a key + * this does not have. A caller that wanted it says so and leaves the map + * alone rather than showing something unstyled. + */ + val currentStyleUrl: String? + get() = null +} + +/** + * [VectorStyleSupport] の登録キー。 + * + * 宣言しないプロバイダは「スタイルは受け取れない」。ベクタータイル層はその場合 + * ラスタータイルに描いて渡す。 + */ +object VectorStyleSupportKey : MapServiceKey + +/** + * [VectorStyleSupport] for a provider whose design type can name a style URL. + * + * The three MapLibre-based providers differ only in how a URL is wrapped + * into their design type, which is what [designFor] supplies; the + * remember-and-restore dance is the same for all of them and lives here + * once. The "still ours" check on [clearStyle] is what keeps this from + * fighting an app that switched designs while the style was up: a layer + * unmounting must not undo a choice the app made after it. + * + * [clearStyle] takes effect a moment later rather than at once, and a + * [showStyle] of the same URL in between cancels it. A provider that + * rebuilds its whole view on a design change (MapTiler keys the view on the + * design id) also rebuilds the overlay content inside it, so the layer that + * asked for the style is unmounted and mounted again *by the change it + * caused*. Clearing on that unmount would restore the old design, which + * would rebuild the view again, and so on without end -- the map never + * finishes coming up. Waiting one frame lets the remount cancel the clear. + */ +class VectorStyleAsDesign>( + private val state: MapViewStateInterface, + private val urlOf: ((Design) -> String?)? = null, + private val designFor: (styleUrl: String, attributionRules: List) -> Design, +) : VectorStyleSupport { + private val main = Handler(Looper.getMainLooper()) + private var installed: Design? = null + private var installedUrl: String? = null + private var previous: Design? = null + private var pendingClear: Runnable? = null + + override fun showStyle( + styleUrl: String, + attributionRules: List, + ) { + pendingClear?.let { main.removeCallbacks(it) } + pendingClear = null + val current = installed + // Same style, still up: nothing to do, and writing the design again + // would rebuild the view for nothing. + if (current != null && installedUrl == styleUrl && state.mapDesignType.id == current.id) return + val design = designFor(styleUrl, attributionRules) + Log.d(TAG, "showStyle $styleUrl (was ${state.mapDesignType.id})") + // Showing a second style over the first keeps the *original* design + // as the one to go back to; the intermediate style was never the + // app's basemap. + if (current == null) previous = state.mapDesignType + installed = design + installedUrl = styleUrl + state.mapDesignType = design + } + + override fun clearStyle() { + if (installed == null) return + pendingClear?.let { main.removeCallbacks(it) } + val clear = + Runnable { + pendingClear = null + val current = installed ?: return@Runnable + val restore = previous + installed = null + installedUrl = null + previous = null + if (state.mapDesignType.id == current.id && restore != null) { + Log.d(TAG, "clearStyle: restoring ${restore.id}") + state.mapDesignType = restore + } + } + pendingClear = clear + main.postDelayed(clear, CLEAR_GRACE_MS) + } + + /** + * Where the design **the app chose** points, when it points anywhere + * fetchable. + * + * Deliberately not the URL this capability installed. That one is the + * document the style module served a moment ago, and it is unregistered + * from the tile server the instant the style comes off -- so answering + * with it turns "adjust whatever is showing" into a 404 against our own + * corpse. When one of ours is up, the honest answer is the design it + * replaced. + * + * Null unless the provider supplied [urlOf], and null from that for a + * design that is not a plain style document -- a provider's own named + * basemap, or one that needs a key this does not have. + */ + override val currentStyleUrl: String? + get() { + val design = if (installed != null) previous else state.mapDesignType + return design?.let { urlOf?.invoke(it) } + } + + private companion object { + /** Longer than a frame, shorter than anyone notices. */ + const val CLEAR_GRACE_MS = 100L + private const val TAG = "VectorStyle" + } +} diff --git a/src/main/java/com/mapconductor/core/marker/AbstractDefaultIcon.kt b/src/main/java/com/mapconductor/core/marker/AbstractDefaultIcon.kt index 5b31241..28d9eef 100644 --- a/src/main/java/com/mapconductor/core/marker/AbstractDefaultIcon.kt +++ b/src/main/java/com/mapconductor/core/marker/AbstractDefaultIcon.kt @@ -8,9 +8,9 @@ import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.TextUnit import androidx.compose.ui.unit.TextUnitType import androidx.core.graphics.createBitmap +import androidx.core.graphics.withTranslation import com.mapconductor.core.BitmapIconCache import com.mapconductor.core.ResourceProvider -import kotlin.math.max import android.graphics.Canvas import android.graphics.Paint import android.graphics.Path @@ -39,6 +39,8 @@ abstract class AbstractDefaultIcon( val infoAnchor: Offset, val iconSize: Dp, val debug: Boolean, + val labelPosition: String = DEFAULT_LABEL_POSITION, + val labelWritingMode: String = DEFAULT_LABEL_WRITING_MODE, ) // 共通プロパティの委譲 @@ -50,11 +52,143 @@ abstract class AbstractDefaultIcon( val labelTextSize: TextUnit by baseProperties::labelTextSize val labelTypeFace: Typeface by baseProperties::labelTypeFace val labelStrokeColor: Color by baseProperties::labelStrokeColor + val labelPosition: String by baseProperties::labelPosition + + /** + * ラベルの書字方向。CSS の `writing-mode` と同じ書き方で、`horizontal-tb`(既定)か + * `vertical-rl` / `vertical-lr`(縦書き)。縦書きは 1 文字ぶんの幅で縦に並ぶので、 + * 横に詰まって並ぶ点にも名前を付けやすい。 + */ + val labelWritingMode: String by baseProperties::labelWritingMode final override val iconSize: Dp by baseProperties::iconSize - final override val anchor: Offset = Offset(0.5f, 1f) - final override val infoAnchor: Offset by baseProperties::infoAnchor final override val debug: Boolean by baseProperties::debug + /** + * ピン先端の位置(ビットマップに対する割合)。ラベルをピンの横や上に置くと + * ビットマップが片側へ伸びるので、固定の (0.5, 1) ではなくレイアウトから求める。 + */ + final override val anchor: Offset by lazy { + val layout = layout + Offset( + (layout.markerOffsetX + layout.markerSize / 2f) / layout.bitmapWidth, + (layout.markerOffsetY + layout.markerSize) / layout.bitmapHeight, + ) + } + + /** + * 指定値はピン本体に対する割合として扱い、ビットマップに対する割合へ直して返す。 + * ラベルが中央にある限りは指定値と一致する(従来どおり)。 + */ + final override val infoAnchor: Offset by lazy { + val layout = layout + val requested = baseProperties.infoAnchor + Offset( + (layout.markerOffsetX + requested.x * layout.markerSize) / layout.bitmapWidth, + (layout.markerOffsetY + requested.y * layout.markerSize) / layout.bitmapHeight, + ) + } + + /** + * ビットマップの幅と高さが、ピン本体(iconSize × scale の正方形)の何倍か。 + * ラベルを横や上に置くと 1 を超える。当たり判定と吹き出しがアイコンの実寸を使うためのもの。 + */ + internal val extentRatio: Size by lazy { + val layout = layout + Size( + layout.bitmapWidth.toFloat() / layout.markerSize, + layout.bitmapHeight.toFloat() / layout.markerSize, + ) + } + + /** ビットマップ内でのマーカー本体とラベルの配置。すべてピクセル空間。 */ + private class IconLayout( + val markerSize: Int, + val bitmapWidth: Int, + val bitmapHeight: Int, + val markerOffsetX: Float, + val markerOffsetY: Float, + val labelCenterX: Float, + val labelCenterY: Float, + val label: LabelTypesetter.Metrics?, + ) + + private val layout: IconLayout by lazy { computeLayout() } + + init { + // ラベル付きは、はみ出し量を作った時点で記録する([LabelledIconExtent])。 + // JVM の単体テストでは Paint が空実装なので、測れなければ記録しない。 + if (baseProperties.label != null) { + runCatching { layout }.getOrNull()?.let { layout -> + LabelledIconExtent.note( + width = layout.bitmapWidth.toFloat(), + height = layout.bitmapHeight.toFloat(), + anchorX = (layout.markerOffsetX + layout.markerSize / 2f) / layout.bitmapWidth, + anchorY = (layout.markerOffsetY + layout.markerSize) / layout.bitmapHeight, + ) + } + } + } + + /** + * ラベルを除いたピン。タイル描画が使う。 + * + * 色や大きさが同じなら、ラベルの違うアイコンの間で 1 枚を共有する([BitmapIconCache] の + * キーにラベルを含めない)。街路樹のように「樹種 × 向き」でラベルを付け替えても、 + * 焼き込む画像は本体の種類だけで済む。 + */ + internal val tileBody: BitmapIcon + get() { + if (label == null) return toBitmapIcon() + val bodyProperties = + baseProperties.copy( + label = null, + labelPosition = DEFAULT_LABEL_POSITION, + labelWritingMode = DEFAULT_LABEL_WRITING_MODE, + ) + val id = "default_icon_body_${bodyProperties.hashCode() * 31 + getUniqueProperties().hashCode()}".hashCode() + BitmapIconCache.get(id)?.let { return it } + val markerSize = layout.markerSize + val bitmap = createBitmap(markerSize, markerSize) + ResourceProvider.getBitmapDensity().let { density -> + bitmap.density = (density * android.util.DisplayMetrics.DENSITY_DEFAULT).toInt() + } + drawMarker( + canvas = Canvas(bitmap), + canvasSize = markerSize.toFloat(), + iconScale = scale, + ) + val result = + BitmapIcon( + bitmap = bitmap, + anchor = Offset(0.5f, 1f), + size = Size(markerSize.toFloat(), markerSize.toFloat()), + ) + BitmapIconCache.put(id, result) + return result + } + + internal val tileLabel: MarkerTileLabel? + get() { + val text = label ?: return null + val layout = layout + val metrics = layout.label ?: return null + val anchorX = layout.markerOffsetX + layout.markerSize / 2f + val anchorY = layout.markerOffsetY + layout.markerSize + return MarkerTileLabel( + text = text, + textSizePx = convertTextUnitToPx(labelTextSize, 1f), + typeface = labelTypeFace, + textColor = (labelTextColor ?: Color.Black).toArgb(), + strokeColor = labelStrokeColor.toArgb(), + outlinePx = labelOutlineStrokeWidth(scale), + centerOffsetX = layout.labelCenterX - anchorX, + centerOffsetY = layout.labelCenterY - anchorY, + width = metrics.width, + height = metrics.height, + vertical = LabelTypesetter.isVertical(labelWritingMode), + ) + } + /** * サブクラスでマーカーのフィル描画を実装する */ @@ -76,106 +210,129 @@ abstract class AbstractDefaultIcon( return it } - // Calculate canvas size with scale applied - val baseCanvasSize = ResourceProvider.dpToPxForBitmap(iconSize.value) - val markerSize = (baseCanvasSize * scale).toInt() - - // ラベルの幅を測定 - var labelWidth = 0f - var labelHeight = 0f - label?.let { labelText -> - val baseTextSize = convertTextUnitToPx(labelTextSize, 1f) - val textPaint = - Paint().apply { - textSize = baseTextSize - textAlign = Paint.Align.CENTER - typeface = labelTypeFace - isAntiAlias = true - } - labelWidth = textPaint.measureText(labelText) - val metrics = textPaint.fontMetrics - labelHeight = metrics.descent - metrics.ascent - } - - // ビットマップのサイズを決定(マーカーとラベルの両方が収まるように) - // 横幅: マーカーまたはラベルの大きい方 + 余白 - val padding = markerSize * 0.1f // 左右に5%ずつの余白 - val bitmapWidth = max(markerSize.toFloat(), labelWidth + padding).toInt() - // 高さ: マーカーの高さを基準(ラベルはマーカー内に収まる想定) - val bitmapHeight = markerSize - - val bitmap = createBitmap(bitmapWidth, bitmapHeight) + val layout = layout + val bitmap = createBitmap(layout.bitmapWidth, layout.bitmapHeight) // Set bitmap density based on override (e.g., 1.0 for MapLibre to prevent auto-scaling) ResourceProvider.getBitmapDensity().let { density -> bitmap.density = (density * android.util.DisplayMetrics.DENSITY_DEFAULT).toInt() } val canvas = Canvas(bitmap) - // マーカーを中央に配置するためのオフセット - val markerOffsetX = (bitmapWidth - markerSize) / 2f - // Draw marker (scale is already applied in markerSize) drawMarker( canvas = canvas, - canvasSize = markerSize.toFloat(), + canvasSize = layout.markerSize.toFloat(), iconScale = scale, - offsetX = markerOffsetX, + offsetX = layout.markerOffsetX, + offsetY = layout.markerOffsetY, ) // Draw label drawLabel( canvas = canvas, - canvasSize = markerSize.toFloat(), iconScale = scale, textSize = labelTextSize, - offsetX = markerOffsetX, + centerX = layout.labelCenterX, + centerY = layout.labelCenterY, ) - // アンカーを調整(マーカーの底部中央) - val adjustedAnchor = Offset(0.5f, 1f) + val adjustedAnchor = anchor val result = BitmapIcon( bitmap = bitmap, anchor = adjustedAnchor, - size = Size(bitmapWidth.toFloat(), bitmapHeight.toFloat()), + size = Size(layout.bitmapWidth.toFloat(), layout.bitmapHeight.toFloat()), ) BitmapIconCache.put(id, result) return result } /** - * マーカー本体の描画(共通処理) + * react-sdk / ios-sdk と同じレイアウト計算。`labelPosition` が中央なら従来どおり + * ラベルを円形部分の中心に重ね、ビットマップを左右対称に広げる。中央以外なら + * ラベルをピンの輪郭の外側へ置き、ビットマップをその側へだけ伸ばす。 */ - protected fun drawMarker( - canvas: Canvas, - canvasSize: Float, - iconScale: Float, - offsetX: Float = 0f, - ) { - val strokePath = createMarkerPath(canvasSize, iconScale, offsetX) - - // デバッグ用の枠描画 - if (debug) { - drawDebugFrame(canvas) - } - - // フィル描画(サブクラス実装) - drawMarkerFill(canvas, strokePath, canvasSize, iconScale) - - // ストローク描画(共通) - val strokePaint = createStrokePaint(iconScale) - canvas.drawPath(strokePath, strokePaint) + private fun computeLayout(): IconLayout { + val baseCanvasSize = ResourceProvider.dpToPxForBitmap(iconSize.value) + val markerSize = (baseCanvasSize * scale).toInt() + val size = markerSize.toFloat() + // 円形部分の中心 + val headCenterY = size * 0.35f + val pin = markerPinBounds(size, scale) + val outline = labelOutlineStrokeWidth(scale) + val metrics = + label?.let { text -> + LabelTypesetter.measure( + text = text, + textSizePx = convertTextUnitToPx(labelTextSize, 1f), + typeface = labelTypeFace, + outlinePx = outline, + vertical = LabelTypesetter.isVertical(labelWritingMode), + ) + } + val result = + IconLabelLayout.compute( + markerSize = markerSize, + bodyLeft = pin.left, + bodyRight = pin.right, + bodyTop = pin.top, + bodyBottom = pin.bottom, + centerY = headCenterY, + // 横に置くときの縦の中央は、ピンの上端と先端の中間。頭の中心にすると、 + // ピン全体の中央より上に見える。 + sideCenterY = (pin.top + pin.bottom) / 2f, + label = metrics, + outlinePx = outline, + labelPosition = labelPosition, + ) + return IconLayout( + markerSize = markerSize, + bitmapWidth = result.bitmapWidth, + bitmapHeight = result.bitmapHeight, + markerOffsetX = result.markerOffsetX, + markerOffsetY = result.markerOffsetY, + labelCenterX = result.labelCenterX, + labelCenterY = result.labelCenterY, + label = metrics, + ) } + private class PinBounds( + val left: Float, + val right: Float, + val top: Float, + val bottom: Float, + ) + /** - * マーカーのパスを生成 + * ピンの見えている輪郭(設計座標で x: 4〜20, y: 0〜24)を px で返す。 + * 外接箱(23.5 × 25.6)より細いので、ラベルを横に置くときはこちらに沿わせる。 */ - protected fun createMarkerPath( + private fun markerPinBounds( canvasSize: Float, iconScale: Float, - horizontalOffset: Float = 0f, - ): Path { + ): PinBounds { + val metrics = markerPathMetrics(canvasSize, iconScale) + val s = metrics.markerScale + return PinBounds( + left = metrics.offsetX + 4f * s, + right = metrics.offsetX + 20f * s, + top = metrics.offsetY, + bottom = metrics.offsetY + 24f * s, + ) + } + + private class MarkerPathMetrics( + val markerScale: Float, + val offsetX: Float, + val offsetY: Float, + ) + + private fun markerPathMetrics( + canvasSize: Float, + iconScale: Float, + ): MarkerPathMetrics { val originalSize = Size(23.5f, 25.6f) // Since canvasSize is already scaled (baseCanvasSize * scale), @@ -204,8 +361,53 @@ abstract class AbstractDefaultIcon( // Center horizontally, align bottom point to canvas edge // The path's bottom point should touch the canvas bottom, the stroke will extend beyond - val offsetX = (canvasSize - scaledWidth) / 2f + horizontalOffset + val offsetX = (canvasSize - scaledWidth) / 2f val offsetY = (canvasSize - scaledHeight + (strokeWidth.value * markerScale)) / 2f + return MarkerPathMetrics(markerScale, offsetX, offsetY) + } + + /** + * マーカー本体の描画(共通処理) + * + * マーカーは canvas を (offsetX, offsetY) だけずらしてから描く。サブクラスの + * [drawMarkerFill] は常に原点にある canvasSize の正方形を前提にしてよい。 + */ + protected fun drawMarker( + canvas: Canvas, + canvasSize: Float, + iconScale: Float, + offsetX: Float = 0f, + offsetY: Float = 0f, + ) { + // デバッグ用の枠描画 + if (debug) { + drawDebugFrame(canvas) + } + + canvas.withTranslation(offsetX, offsetY) { + val strokePath = createMarkerPath(canvasSize, iconScale) + + // フィル描画(サブクラス実装) + drawMarkerFill(this, strokePath, canvasSize, iconScale) + + // ストローク描画(共通) + val strokePaint = createStrokePaint(iconScale) + drawPath(strokePath, strokePaint) + } + } + + /** + * マーカーのパスを生成 + */ + protected fun createMarkerPath( + canvasSize: Float, + iconScale: Float, + horizontalOffset: Float = 0f, + ): Path { + val metrics = markerPathMetrics(canvasSize, iconScale) + val markerScale = metrics.markerScale + val offsetX = metrics.offsetX + horizontalOffset + val offsetY = metrics.offsetY return Path().apply { moveTo(12f * markerScale + offsetX, 0f * markerScale + offsetY) @@ -290,56 +492,34 @@ abstract class AbstractDefaultIcon( strokeCap = Paint.Cap.ROUND // 追加(尖り部のにじみ軽減) } + // アウトライン幅(アイコンスケールを考慮したストローク幅、最小2px) + private fun labelOutlineStrokeWidth(iconScale: Float): Float = LabelTypesetter.outlinePx(iconScale) + /** - * ラベルテキストの描画 + * ラベルテキストの描画。(centerX, centerY) は [computeLayout] が決めたラベルの中心で、 + * 既定ではマーカーの円形部分の中心になる。 */ protected fun drawLabel( canvas: Canvas, - canvasSize: Float, iconScale: Float, textSize: TextUnit, - offsetX: Float = 0f, + centerX: Float, + centerY: Float, ) { label?.let { labelText -> - // 基本テキストサイズを計算(スケーリング適用) - val baseTextSize = convertTextUnitToPx(textSize, 1f) - - val textPaint = - Paint().apply { - color = labelTextColor?.toArgb() ?: Color.Black.toArgb() - this.textSize = baseTextSize - textAlign = Paint.Align.CENTER - typeface = labelTypeFace - isAntiAlias = true - isSubpixelText = true - } - - // マーカーの円形部分の中心に配置 - val markerCenterX = canvasSize / 2f + offsetX - val markerCenterY = canvasSize * 0.35f // 円形部分の中心 - - val metrics = textPaint.fontMetrics - val textHeight = metrics.descent - metrics.ascent - val baselineOffset = textHeight / 2f - metrics.descent - - // アウトライン描画(アイコンスケールを考慮したストローク幅) - val outlineStrokeWidth = - max( - ResourceProvider.dpToPxForBitmap(1f * iconScale).toFloat(), - 2f, // 最小2px - ) - - val outlinePaint = - Paint(textPaint).apply { - style = Paint.Style.STROKE - strokeWidth = outlineStrokeWidth - color = labelStrokeColor.toArgb() - strokeJoin = Paint.Join.ROUND - strokeCap = Paint.Cap.ROUND - } - - canvas.drawText(labelText, markerCenterX, markerCenterY + baselineOffset, outlinePaint) - canvas.drawText(labelText, markerCenterX, markerCenterY + baselineOffset, textPaint) + LabelTypesetter.draw( + canvas = canvas, + text = labelText, + centerX = centerX, + centerY = centerY, + textSizePx = convertTextUnitToPx(textSize, 1f), + typeface = labelTypeFace, + textColor = (labelTextColor ?: Color.Black).toArgb(), + strokeColor = labelStrokeColor.toArgb(), + outlinePx = labelOutlineStrokeWidth(iconScale), + vertical = LabelTypesetter.isVertical(labelWritingMode), + alignToPixel = false, + ) } } @@ -378,4 +558,35 @@ abstract class AbstractDefaultIcon( override fun toString(): String = "${this::class.simpleName}(baseProperties=$baseProperties, uniqueProperties=${getUniqueProperties()})" + + companion object { + /** + * ラベルの既定位置。ピンの頭に重ねる(従来どおり)。 + * + * `labelPosition` は CSS の `background-position` と同じ書き方で、横 + * (left / center / right)と縦(top / center / bottom)のキーワードを空白区切りで + * 並べる。順序は問わず、片方だけなら残りは center。 + * - left / right はピンの外側に置き、縦はピンの上端・上端と先端の中間・先端に揃える。 + * - center 列の top / bottom はピンの上・下の外側に置く。 + */ + const val DEFAULT_LABEL_POSITION: String = "center center" + + /** ラベルの既定の書字方向。横書き。書き方は [labelWritingMode] を参照。 */ + const val DEFAULT_LABEL_WRITING_MODE: String = LabelTypesetter.HORIZONTAL + + /** `labelPosition` を横・縦それぞれ -1 / 0 / 1 に読み替える。読めない値は中央扱い。 */ + internal fun parseLabelPosition(position: String): Pair { + var h = 0 + var v = 0 + position.trim().lowercase().split(Regex("\\s+")).forEach { word -> + when (word) { + "left" -> h = -1 + "right" -> h = 1 + "top" -> v = -1 + "bottom" -> v = 1 + } + } + return h to v + } + } } diff --git a/src/main/java/com/mapconductor/core/marker/AbstractMarkerController.kt b/src/main/java/com/mapconductor/core/marker/AbstractMarkerController.kt index 1312872..128964f 100644 --- a/src/main/java/com/mapconductor/core/marker/AbstractMarkerController.kt +++ b/src/main/java/com/mapconductor/core/marker/AbstractMarkerController.kt @@ -1,5 +1,6 @@ package com.mapconductor.core.marker +import com.mapconductor.core.InternalMapConductorApi import com.mapconductor.core.controller.OverlayHit import com.mapconductor.core.controller.OverlayKind import com.mapconductor.core.controller.SlottedOverlayController @@ -16,7 +17,8 @@ abstract class AbstractMarkerController( MarkerState, MarkerEntityInterface, >, - MarkerEventHostInterface { + MarkerEventHostInterface, + MarkerDrawOrderReceiver { override val zIndex: Int = 10 val semaphore = Semaphore(1) @@ -315,6 +317,9 @@ abstract class AbstractMarkerController( renderer.onRemove(entities) markerManager.clear() draggingMarkerIds.clear() + // 他の 5 種類と同じく、manager を空にしてから onPostProcess を呼ぶ。GL 系の描画担当は + // onRemove では地図に触らず、onPostProcess で manager の中身から描き直す。 + renderer.onPostProcess() } } @@ -336,9 +341,11 @@ abstract class AbstractMarkerController( * * ## 判定は画面座標で行う * - * 最近傍のマーカーを 1 つだけ取り出し、タップ点とマーカーの**アイコン矩形**を - * 画面座標で突き合わせる([MarkerHitTest])。地理距離ではなくアイコンの大きさを - * 見るので、幅広ラベルやクラスタのように大きいアイコンでも端が反応する。 + * タップ点の周り([MarkerHitPick.SEARCH_RADIUS_DP])のマーカーを候補にし、各候補の + * **アイコン矩形**(ラベル込み)を画面座標で突き合わせる([MarkerHitPick.pick])。 + * 指の下にアイコンかラベルが描かれているマーカーが、先端の近い別のマーカーより優先する。 + * 以前は先端が最寄りの 1 つだけを見ていたので、隣のピンの頭や横に置いたラベルを + * タップすると外れていた。 * * 投影できない([com.mapconductor.core.map.MapViewHolderInterface.toScreenOffset] が * null)ときは「当たらなかった」として null。画面外のマーカーは当たらないのが正しい。 @@ -349,16 +356,12 @@ abstract class AbstractMarkerController( * `clickable = false` かつ `draggable = true` のマーカーがドラッグできなくなる。 * クリックの可否は配送側([dispatchClick] / [clickableOnly])で判断する。 */ + @OptIn(InternalMapConductorApi::class) override fun find(position: GeoPointInterface): MarkerEntityInterface? { - val nearest = markerManager.findNearest(position) ?: return null - val touchScreen = renderer.holder.toScreenOffset(position) ?: return null - val markerScreen = renderer.holder.toScreenOffset(nearest.state.position) ?: return null - - return if (MarkerHitTest.hitsIcon(touchScreen, markerScreen, nearest.state)) { - nearest - } else { - null - } + val holder = renderer.holder + val touchScreen = holder.toScreenOffset(position) ?: return null + val bounds = MarkerHitPick.searchBounds(position, touchScreen, holder::toScreenOffset) ?: return null + return MarkerHitPick.pick(touchScreen, markerManager.findMarkersInBounds(bounds), holder::toScreenOffset) } override val kind: OverlayKind = OverlayKind.Marker @@ -374,6 +377,10 @@ abstract class AbstractMarkerController( override fun getEntity(id: String): MarkerEntityInterface? = markerManager.getEntity(id) override fun has(id: String): Boolean = markerManager.hasEntity(id) + + override suspend fun onDrawOrderFrameChanged(frame: MarkerDrawOrder.Frame) { + semaphore.withPermit { renderer.onDrawOrderFrameChanged(frame, markerManager.allEntities()) } + } } private const val MARKER_RENDER_BATCH_SIZE = 500 diff --git a/src/main/java/com/mapconductor/core/marker/AbstractMarkerOverlayRenderer.kt b/src/main/java/com/mapconductor/core/marker/AbstractMarkerOverlayRenderer.kt index e9896d8..15c1334 100644 --- a/src/main/java/com/mapconductor/core/marker/AbstractMarkerOverlayRenderer.kt +++ b/src/main/java/com/mapconductor/core/marker/AbstractMarkerOverlayRenderer.kt @@ -45,6 +45,30 @@ abstract class AbstractMarkerOverlayRenderer< */ open val supportsAnimationOverlay: Boolean = false + /** 同じ zIndex のマーカーを並べる向き([onDrawOrderFrameChanged] で変わる)。 */ + var drawOrderFrame: MarkerDrawOrder.Frame = MarkerDrawOrder.Frame.NorthUp + private set + + /** [drawOrderFrame] で並べたときの描く順。大きいほど手前。 */ + fun drawOrderOf(state: MarkerState): Double = MarkerDrawOrder.of(state.zIndex, state.position, drawOrderFrame) + + /** [drawOrderOf] の整数版。 */ + fun drawOrderIntOf(state: MarkerState): Int = MarkerDrawOrder.ofInt(state.zIndex, state.position, drawOrderFrame) + + override suspend fun onDrawOrderFrameChanged( + frame: MarkerDrawOrder.Frame, + entities: List>, + ) { + drawOrderFrame = frame + applyDrawOrder(entities) + } + + /** + * [drawOrderFrame] が変わったので、[entities] の描く順を付け直す。 + * 既定は何もしない(北が上の順のまま)。 + */ + protected open suspend fun applyDrawOrder(entities: List>) = Unit + /** Hide/show the native marker while the overlay animation runs. */ open fun setMarkerVisible( markerEntity: MarkerEntityInterface, diff --git a/src/main/java/com/mapconductor/core/marker/ColorDefaultIcon.kt b/src/main/java/com/mapconductor/core/marker/ColorDefaultIcon.kt index c06398a..614388a 100644 --- a/src/main/java/com/mapconductor/core/marker/ColorDefaultIcon.kt +++ b/src/main/java/com/mapconductor/core/marker/ColorDefaultIcon.kt @@ -31,6 +31,8 @@ class ColorDefaultIcon( labelTextSize: TextUnit = 18.sp, labelTypeFace: Typeface = Typeface.DEFAULT, labelStrokeColor: Color = Color.White, + labelPosition: String = DEFAULT_LABEL_POSITION, + labelWritingMode: String = DEFAULT_LABEL_WRITING_MODE, infoAnchor: Offset = Offset(0.5f, 0f), iconSize: Dp = Settings.Default.iconSize, debug: Boolean = false, @@ -46,6 +48,8 @@ class ColorDefaultIcon( labelTextSize = labelTextSize, labelTypeFace = labelTypeFace, labelStrokeColor = labelStrokeColor, + labelPosition = labelPosition, + labelWritingMode = labelWritingMode, infoAnchor = infoAnchor, iconSize = iconSize, debug = debug, @@ -78,6 +82,8 @@ class ColorDefaultIcon( labelTextSize: TextUnit = this.labelTextSize, labelTypeFace: Typeface = this.labelTypeFace, labelStrokeColor: Color = this.labelStrokeColor, + labelPosition: String = this.labelPosition, + labelWritingMode: String = this.labelWritingMode, iconSize: Dp = this.iconSize, debug: Boolean = this.debug, ): ColorDefaultIcon = @@ -93,6 +99,8 @@ class ColorDefaultIcon( labelTextSize = labelTextSize, labelTypeFace = labelTypeFace, labelStrokeColor = labelStrokeColor, + labelPosition = labelPosition, + labelWritingMode = labelWritingMode, iconSize = iconSize, debug = debug, ), diff --git a/src/main/java/com/mapconductor/core/marker/DrawableDefaultIcon.kt b/src/main/java/com/mapconductor/core/marker/DrawableDefaultIcon.kt index d89dcbf..7ed55c0 100644 --- a/src/main/java/com/mapconductor/core/marker/DrawableDefaultIcon.kt +++ b/src/main/java/com/mapconductor/core/marker/DrawableDefaultIcon.kt @@ -37,6 +37,7 @@ class DrawableDefaultIcon( labelTextSize: TextUnit = 18.sp, labelTypeFace: Typeface = Typeface.DEFAULT, labelStrokeColor: Color = Color.White, + labelPosition: String = DEFAULT_LABEL_POSITION, infoAnchor: Offset = Offset(0.5f, 0f), iconSize: Dp = Settings.Default.iconSize, debug: Boolean = false, @@ -52,6 +53,7 @@ class DrawableDefaultIcon( labelTextSize = labelTextSize, labelTypeFace = labelTypeFace, labelStrokeColor = labelStrokeColor, + labelPosition = labelPosition, infoAnchor = infoAnchor, iconSize = iconSize, debug = debug, @@ -162,6 +164,7 @@ class DrawableDefaultIcon( labelTextSize: TextUnit = this.labelTextSize, labelTypeFace: Typeface = this.labelTypeFace, labelStrokeColor: Color = this.labelStrokeColor, + labelPosition: String = this.labelPosition, iconSize: Dp = this.iconSize, debug: Boolean = this.debug, ): DrawableDefaultIcon = @@ -177,6 +180,7 @@ class DrawableDefaultIcon( labelTextSize = labelTextSize, labelTypeFace = labelTypeFace, labelStrokeColor = labelStrokeColor, + labelPosition = labelPosition, iconSize = iconSize, debug = debug, ), diff --git a/src/main/java/com/mapconductor/core/marker/ImageDefaultIcon.kt b/src/main/java/com/mapconductor/core/marker/ImageDefaultIcon.kt index 4ada27b..8770444 100644 --- a/src/main/java/com/mapconductor/core/marker/ImageDefaultIcon.kt +++ b/src/main/java/com/mapconductor/core/marker/ImageDefaultIcon.kt @@ -34,6 +34,7 @@ class ImageDefaultIcon( labelTextSize: TextUnit = 18.sp, labelTypeFace: Typeface = Typeface.DEFAULT, labelStrokeColor: Color = Color.White, + labelPosition: String = DEFAULT_LABEL_POSITION, infoAnchor: Offset = Offset(0.5f, 0f), iconSize: Dp = Settings.Default.iconSize, debug: Boolean = false, @@ -49,6 +50,7 @@ class ImageDefaultIcon( labelTextSize = labelTextSize, labelTypeFace = labelTypeFace, labelStrokeColor = labelStrokeColor, + labelPosition = labelPosition, infoAnchor = infoAnchor, iconSize = iconSize, debug = debug, @@ -113,6 +115,7 @@ class ImageDefaultIcon( labelTextSize: TextUnit = this.labelTextSize, labelTypeFace: Typeface = this.labelTypeFace, labelStrokeColor: Color = this.labelStrokeColor, + labelPosition: String = this.labelPosition, iconSize: Dp = this.iconSize, debug: Boolean = this.debug, ): ImageDefaultIcon = @@ -128,6 +131,7 @@ class ImageDefaultIcon( labelTextSize = labelTextSize, labelTypeFace = labelTypeFace, labelStrokeColor = labelStrokeColor, + labelPosition = labelPosition, iconSize = iconSize, debug = debug, ), diff --git a/src/main/java/com/mapconductor/core/marker/ImageIcon.kt b/src/main/java/com/mapconductor/core/marker/ImageIcon.kt index a592b77..0b4c79a 100644 --- a/src/main/java/com/mapconductor/core/marker/ImageIcon.kt +++ b/src/main/java/com/mapconductor/core/marker/ImageIcon.kt @@ -2,27 +2,203 @@ package com.mapconductor.core.marker import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.TextUnit +import androidx.compose.ui.unit.sp +import androidx.core.graphics.createBitmap import com.mapconductor.core.BitmapIconCache +import com.mapconductor.core.RemoteImageDrawable import com.mapconductor.core.ResourceProvider import com.mapconductor.settings.Settings +import android.graphics.Canvas +import android.graphics.Rect +import android.graphics.Typeface import android.graphics.drawable.BitmapDrawable import android.graphics.drawable.ColorDrawable import android.graphics.drawable.Drawable import android.graphics.drawable.GradientDrawable +/** + * 画像をそのまま(大きさだけ合わせて)使うアイコン。既定のピンの形にはしない。 + * + * ## ラベル + * + * [label] を渡すと画像に文字を添える。書き方と既定値は [ColorDefaultIcon] と同じで、 + * ios-sdk / react-sdk の `ImageIcon` とも揃えてある。 + * + * - `left` / `right` は画像の外側に置き、縦は画像の上端・中間・下端に揃える。 + * - `center` 列の `top` / `bottom` は画像の上・下の外側に置く。 + * - `"center center"`(既定)は画像の中央に重ねる。 + * + * [labelWritingMode] に `"vertical-rl"` を渡すと縦書きになる([AbstractDefaultIcon.labelWritingMode])。 + * + * コンストラクタの `anchor` / `infoAnchor` は、ラベルの有無によらず**画像に対する割合**。 + * 公開している [anchor] / [infoAnchor] は、ラベルで広がった全体に対する割合へ直した値。 + * + * タイル描画は本体の画像と文字を別々に使うので、ラベル付きのアイコンをいくつ作っても、 + * 本体の画像は元の画像と大きさごとに 1 枚で済む。 + * + * ## URL の画像 + * + * `ImageIcon(imageUrl = "https://…")` は画像を SDK が読む。読み終えるまでは同じ大きさの + * 透明な画像(ラベルは描く)で、届いたらそのアイコンを使っているマーカーが描き直される。 + * 同じ URL は一度しか取りに行かない。http / https / file / data を読め、http(s) には + * アプリの `android.permission.INTERNET` が要る。読めなかったときは透明のまま。 + * react-sdk / ios-sdk の `ImageIcon` の `imageUrl` と同じ。 + */ class ImageIcon( image: Drawable, override val iconSize: Dp = Settings.Default.iconSize, override val scale: Float = 1.0f, - override val anchor: Offset = Offset(0.5f, 0.5f), - override val infoAnchor: Offset = Offset(0.5f, 0.5f), + anchor: Offset = Offset(0.5f, 0.5f), + infoAnchor: Offset = Offset(0.5f, 0.5f), override val debug: Boolean = false, + val label: String? = null, + val labelTextColor: Color? = Color.Black, + val labelTextSize: TextUnit = 18.sp, + val labelTypeFace: Typeface = Typeface.DEFAULT, + val labelStrokeColor: Color = Color.White, + val labelPosition: String = AbstractDefaultIcon.DEFAULT_LABEL_POSITION, + val labelWritingMode: String = AbstractDefaultIcon.DEFAULT_LABEL_WRITING_MODE, ) : AndroidDrawableIcon( drawable = image, ) { + /** + * [imageUrl](http / https / file / data)の画像を使う。読み終えるまでは透明。 + * ほかの引数は `Drawable` を渡すコンストラクタと同じ。 + */ + constructor( + imageUrl: String, + iconSize: Dp = Settings.Default.iconSize, + scale: Float = 1.0f, + anchor: Offset = Offset(0.5f, 0.5f), + infoAnchor: Offset = Offset(0.5f, 0.5f), + debug: Boolean = false, + label: String? = null, + labelTextColor: Color? = Color.Black, + labelTextSize: TextUnit = 18.sp, + labelTypeFace: Typeface = Typeface.DEFAULT, + labelStrokeColor: Color = Color.White, + labelPosition: String = AbstractDefaultIcon.DEFAULT_LABEL_POSITION, + labelWritingMode: String = AbstractDefaultIcon.DEFAULT_LABEL_WRITING_MODE, + ) : this( + image = RemoteImageDrawable(imageUrl), + iconSize = iconSize, + scale = scale, + anchor = anchor, + infoAnchor = infoAnchor, + debug = debug, + label = label, + labelTextColor = labelTextColor, + labelTextSize = labelTextSize, + labelTypeFace = labelTypeFace, + labelStrokeColor = labelStrokeColor, + labelPosition = labelPosition, + labelWritingMode = labelWritingMode, + ) + + private val requestedAnchor = anchor + private val requestedInfoAnchor = infoAnchor + + /** URL で作ったアイコンならその URL。`Drawable` で作ったなら null。 */ + val imageUrl: String? + get() = (drawable as? RemoteImageDrawable)?.url + + /** + * URL の画像がまだ届いていなければ、届いたとき(失敗も含む)に [listener] を一度だけ呼ぶ。 + * 待つ必要が無ければ呼ばずに false を返す。[MarkerState] が描き直しに使う。 + */ + internal fun whenImageLoaded(listener: () -> Unit): Boolean = + (drawable as? RemoteImageDrawable)?.whenLoaded(listener) ?: false + + private class Layout( + val canvasSize: Int, + val result: IconLabelLayout.Result, + val label: LabelTypesetter.Metrics?, + val textSizePx: Float, + val outlinePx: Float, + ) + + private val layout: Layout by lazy { + val canvasSize = (ResourceProvider.dpToPxForBitmap(iconSize.value) * scale).toInt() + val size = canvasSize.toFloat() + val textSizePx = LabelTypesetter.textSizePx(labelTextSize) + val outline = LabelTypesetter.outlinePx(scale) + val metrics = + label?.let { text -> + LabelTypesetter.measure( + text = text, + textSizePx = textSizePx, + typeface = labelTypeFace, + outlinePx = outline, + vertical = LabelTypesetter.isVertical(labelWritingMode), + ) + } + Layout( + canvasSize = canvasSize, + result = + IconLabelLayout.compute( + markerSize = canvasSize, + bodyLeft = 0f, + bodyRight = size, + bodyTop = 0f, + bodyBottom = size, + centerY = size / 2f, + sideCenterY = size / 2f, + label = metrics, + outlinePx = outline, + labelPosition = labelPosition, + ), + label = metrics, + textSizePx = textSizePx, + outlinePx = outline, + ) + } + + override val anchor: Offset by lazy { toBitmapFraction(requestedAnchor) } + + override val infoAnchor: Offset by lazy { toBitmapFraction(requestedInfoAnchor) } + + /** ビットマップの幅と高さが、画像(iconSize × scale の正方形)の何倍か。 */ + internal val extentRatio: Size by lazy { + val layout = layout + Size( + layout.result.bitmapWidth.toFloat() / layout.canvasSize, + layout.result.bitmapHeight.toFloat() / layout.canvasSize, + ) + } + + init { + // ラベル付きは、はみ出し量を作った時点で記録する([LabelledIconExtent])。 + // JVM の単体テストでは Paint が空実装なので、測れなければ記録しない。 + if (label != null) { + runCatching { layout }.getOrNull()?.let { layout -> + val result = layout.result + LabelledIconExtent.note( + width = result.bitmapWidth.toFloat(), + height = result.bitmapHeight.toFloat(), + anchorX = (result.markerOffsetX + requestedAnchor.x * layout.canvasSize) / result.bitmapWidth, + anchorY = (result.markerOffsetY + requestedAnchor.y * layout.canvasSize) / result.bitmapHeight, + ) + } + } + } + + private fun toBitmapFraction(requested: Offset): Offset { + val layout = layout + val result = layout.result + return Offset( + (result.markerOffsetX + requested.x * layout.canvasSize) / result.bitmapWidth, + (result.markerOffsetY + requested.y * layout.canvasSize) / result.bitmapHeight, + ) + } + private fun getDrawableIdentity(): Int = when (drawable) { + // URL と、画像が届いたかどうか。届いた時点で変わり、マーカーが描き直される。 + is RemoteImageDrawable -> drawable.identity() is BitmapDrawable -> { val bmp = drawable.bitmap if (bmp == null || bmp.isRecycled) { @@ -51,47 +227,169 @@ class ImageIcon( return getDrawableIdentity() == other.getDrawableIdentity() && iconSize == other.iconSize && scale == other.scale && - anchor == other.anchor && - infoAnchor == other.infoAnchor && - debug == other.debug + requestedAnchor == other.requestedAnchor && + requestedInfoAnchor == other.requestedInfoAnchor && + debug == other.debug && + label == other.label && + labelTextColor == other.labelTextColor && + labelTextSize == other.labelTextSize && + labelTypeFace == other.labelTypeFace && + labelStrokeColor == other.labelStrokeColor && + labelPosition == other.labelPosition && + labelWritingMode == other.labelWritingMode } - override fun hashCode(): Int { + /** ラベルを除いた見た目の hash。本体の画像のキャッシュキーに使い、ラベル違いで共有する。 */ + private fun bodyHashCode(): Int { var result = getDrawableIdentity() result = 31 * result + iconSize.hashCode() result = 31 * result + scale.hashCode() - result = 31 * result + anchor.hashCode() - result = 31 * result + infoAnchor.hashCode() + result = 31 * result + requestedAnchor.hashCode() + result = 31 * result + requestedInfoAnchor.hashCode() result = 31 * result + debug.hashCode() return result } + override fun hashCode(): Int { + var result = bodyHashCode() + result = 31 * result + (label?.hashCode() ?: 0) + result = 31 * result + (labelTextColor?.hashCode() ?: 0) + result = 31 * result + labelTextSize.hashCode() + result = 31 * result + labelTypeFace.hashCode() + result = 31 * result + labelStrokeColor.hashCode() + result = 31 * result + labelPosition.hashCode() + result = 31 * result + labelWritingMode.hashCode() + return result + } + + internal val tileBody: BitmapIcon + get() { + val id = bodyHashCode() + BitmapIconCache.get(id)?.let { + return it + } + + val scaledSize = layout.canvasSize + + val bitmap = + this.toBitmap( + drawable = drawable, + width = scaledSize, + height = scaledSize, + ) + // Set bitmap density based on override (e.g., 1.0 for MapLibre to prevent auto-scaling) + ResourceProvider.getBitmapDensity().let { density -> + bitmap.density = (density * android.util.DisplayMetrics.DENSITY_DEFAULT).toInt() + } + + val result = + BitmapIcon( + bitmap = bitmap, + anchor = requestedAnchor, + size = Size(scaledSize.toFloat(), scaledSize.toFloat()), + ) + BitmapIconCache.put(id, result) + return result + } + + internal val tileLabel: MarkerTileLabel? + get() { + val text = label ?: return null + val layout = layout + val metrics = layout.label ?: return null + val result = layout.result + val anchorX = result.markerOffsetX + requestedAnchor.x * layout.canvasSize + val anchorY = result.markerOffsetY + requestedAnchor.y * layout.canvasSize + return MarkerTileLabel( + text = text, + textSizePx = layout.textSizePx, + typeface = labelTypeFace, + textColor = (labelTextColor ?: Color.Black).toArgb(), + strokeColor = labelStrokeColor.toArgb(), + outlinePx = layout.outlinePx, + centerOffsetX = result.labelCenterX - anchorX, + centerOffsetY = result.labelCenterY - anchorY, + width = metrics.width, + height = metrics.height, + vertical = LabelTypesetter.isVertical(labelWritingMode), + ) + } + override fun toBitmapIcon(): BitmapIcon { - val id = hashCode() + val body = tileBody + val text = label ?: return body + val id = "image_icon_${hashCode()}".hashCode() BitmapIconCache.get(id)?.let { return it } - val scaledSize = ResourceProvider.dpToPxForBitmap(iconSize.value) * scale - - val bitmap = - this.toBitmap( - drawable = drawable, - width = scaledSize.toInt(), - height = scaledSize.toInt(), - ) - // Set bitmap density based on override (e.g., 1.0 for MapLibre to prevent auto-scaling) + val layout = layout + val result = layout.result + val bitmap = createBitmap(result.bitmapWidth, result.bitmapHeight) ResourceProvider.getBitmapDensity().let { density -> bitmap.density = (density * android.util.DisplayMetrics.DENSITY_DEFAULT).toInt() } + val canvas = Canvas(bitmap) + val left = Math.round(result.markerOffsetX) + val top = Math.round(result.markerOffsetY) + canvas.drawBitmap( + body.bitmap, + null, + Rect(left, top, left + layout.canvasSize, top + layout.canvasSize), + null, + ) + LabelTypesetter.draw( + canvas = canvas, + text = text, + centerX = result.labelCenterX, + centerY = result.labelCenterY, + textSizePx = layout.textSizePx, + typeface = labelTypeFace, + textColor = (labelTextColor ?: Color.Black).toArgb(), + strokeColor = labelStrokeColor.toArgb(), + outlinePx = layout.outlinePx, + vertical = LabelTypesetter.isVertical(labelWritingMode), + alignToPixel = false, + ) - val result = + val icon = BitmapIcon( bitmap = bitmap, anchor = anchor, - size = Size(scaledSize.toFloat(), scaledSize.toFloat()), + size = Size(result.bitmapWidth.toFloat(), result.bitmapHeight.toFloat()), ) - BitmapIconCache.put(id, result) - return result + BitmapIconCache.put(id, icon) + return icon } + + fun copy( + image: Drawable = this.drawable, + iconSize: Dp = this.iconSize, + scale: Float = this.scale, + anchor: Offset = this.requestedAnchor, + infoAnchor: Offset = this.requestedInfoAnchor, + debug: Boolean = this.debug, + label: String? = this.label, + labelTextColor: Color? = this.labelTextColor, + labelTextSize: TextUnit = this.labelTextSize, + labelTypeFace: Typeface = this.labelTypeFace, + labelStrokeColor: Color = this.labelStrokeColor, + labelPosition: String = this.labelPosition, + labelWritingMode: String = this.labelWritingMode, + ): ImageIcon = + ImageIcon( + image = image, + iconSize = iconSize, + scale = scale, + anchor = anchor, + infoAnchor = infoAnchor, + debug = debug, + label = label, + labelTextColor = labelTextColor, + labelTextSize = labelTextSize, + labelTypeFace = labelTypeFace, + labelStrokeColor = labelStrokeColor, + labelPosition = labelPosition, + labelWritingMode = labelWritingMode, + ) } diff --git a/src/main/java/com/mapconductor/core/marker/Marker.kt b/src/main/java/com/mapconductor/core/marker/Marker.kt index dd52185..69e6370 100644 --- a/src/main/java/com/mapconductor/core/marker/Marker.kt +++ b/src/main/java/com/mapconductor/core/marker/Marker.kt @@ -1,177 +1,300 @@ -package com.mapconductor.core.marker - -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.setValue -import androidx.compose.runtime.snapshotFlow -import androidx.compose.ui.geometry.Offset -import androidx.compose.ui.geometry.Size -import com.mapconductor.core.ComponentState -import com.mapconductor.core.features.GeoPointInterface -import java.io.ByteArrayOutputStream -import java.io.Serializable -import android.graphics.Bitmap -import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.flow.distinctUntilChanged - -// ------- Core Types ---------- -class MarkerState( - position: GeoPointInterface, - id: String? = null, - var extra: Serializable? = null, - icon: MarkerIconInterface? = null, - animation: MarkerAnimation? = null, - zIndex: Int? = null, - clickable: Boolean = true, - draggable: Boolean = false, - onClick: OnMarkerEventHandler? = null, - onDragStart: OnMarkerEventHandler? = null, - onDrag: OnMarkerEventHandler? = null, - onDragEnd: OnMarkerEventHandler? = null, - onAnimateStart: OnMarkerEventHandler? = null, - onAnimateEnd: OnMarkerEventHandler? = null, -) : ComponentState { - override val id = - ( - id ?: markerId( - listOf( - position.hashCode(), - extra?.hashCode() ?: 0, - icon?.hashCode() ?: 0, - clickable.hashCode(), - draggable.hashCode(), - animation?.hashCode() ?: 0, - ), - ) - ).toString() - - private fun markerId(hashCodes: List): Int = - hashCodes.reduce { result, hashCode -> - 31 * result + hashCode - } - - var icon by mutableStateOf(icon) - var clickable by mutableStateOf(clickable) - var draggable by mutableStateOf(draggable) - var onClick by mutableStateOf(onClick) - var onDragStart by mutableStateOf(onDragStart) - var onDrag by mutableStateOf(onDrag) - var onDragEnd by mutableStateOf(onDragEnd) - var onAnimateStart by mutableStateOf(onAnimateStart) - var onAnimateEnd by mutableStateOf(onAnimateEnd) - var zIndex by mutableStateOf(zIndex) - - private var internalAnimation by mutableStateOf(animation) - - fun animate(animation: MarkerAnimation?) { - internalAnimation = animation - } - - fun getAnimation(): MarkerAnimation? = internalAnimation - - private val currentPosition = mutableStateOf(position) - var position: GeoPointInterface - get() { - return currentPosition.value - } - set(value) { - currentPosition.value = value - } - - /** - * Copies this state, carrying every property over unless overridden. - * - * [animation] is copied like everything else. It used to be silently - * dropped — the parameter did not exist and the new instance was built - * without one — so `marker.copy(position = p)` on a bouncing marker - * returned a still one. Nothing about a copy implies "stop animating", and - * ios-sdk / react-sdk both carry it over. - */ - fun copy( - id: String? = this.id, - position: GeoPointInterface = this.position, - extra: Serializable? = this.extra, - icon: MarkerIconInterface? = this.icon, - animation: MarkerAnimation? = this.getAnimation(), - zIndex: Int? = this.zIndex, - clickable: Boolean? = this.clickable, - draggable: Boolean? = this.draggable, - onClick: OnMarkerEventHandler? = this.onClick, - onDragStart: OnMarkerEventHandler? = this.onDragStart, - onDrag: OnMarkerEventHandler? = this.onDrag, - onDragEnd: OnMarkerEventHandler? = this.onDragEnd, - onAnimateStart: OnMarkerEventHandler? = this.onAnimateStart, - onAnimateEnd: OnMarkerEventHandler? = this.onAnimateEnd, - ): MarkerState = - MarkerState( - id = id, // Keep marker id - position = position, - extra = extra, - icon = icon, - animation = animation, - zIndex = zIndex, - clickable = clickable ?: this.clickable, - draggable = draggable ?: this.draggable, - onClick = onClick, - onDragStart = onDragStart, - onDrag = onDrag, - onDragEnd = onDragEnd, - onAnimateStart = onAnimateStart, - onAnimateEnd = onAnimateEnd, - ) - - override fun equals(other: Any?): Boolean { - val otherState = (other as? MarkerState) ?: return false - return hashCode() == otherState.hashCode() - } - - override fun hashCode(): Int { - var result = extra?.hashCode() ?: 0 - result = 31 * result + clickable.hashCode() - result = 31 * result + draggable.hashCode() - result = 31 * result + currentPosition.value.latitude.hashCode() - result = 31 * result + currentPosition.value.longitude.hashCode() - result = 31 * result + currentPosition.value.altitude.hashCode() - result = 31 * result + (icon?.hashCode() ?: 0) - result = 31 * result + zIndex.hashCode() - return result - } - - fun fingerPrint(): MarkerFingerPrint = - MarkerFingerPrint( - this.id.hashCode(), - icon.hashCode(), - clickable.hashCode(), - draggable.hashCode(), - currentPosition.value.latitude.hashCode(), - currentPosition.value.longitude.hashCode(), - internalAnimation?.hashCode() ?: 1, - zIndex.hashCode(), - ) - - fun asFlow(): Flow = snapshotFlow { fingerPrint() }.distinctUntilChanged() -} - -data class MarkerFingerPrint( - val id: Int, - val icon: Int?, - val clickable: Int, - val draggable: Int, - val latitude: Int, - val longitude: Int, - val animation: Int?, - val zIndex: Int, -) -typealias OnMarkerEventHandler = (MarkerState) -> Unit - -data class BitmapIcon( - val bitmap: Bitmap, - val anchor: Offset, - val size: Size, -) { - fun toByteArray(): ByteArray { - val outputStream = ByteArrayOutputStream() - bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream) - return outputStream.toByteArray() - } -} +package com.mapconductor.core.marker + +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Size +import com.mapconductor.core.ComponentState +import com.mapconductor.core.StateMutationSignal +import com.mapconductor.core.features.GeoPointInterface +import java.io.ByteArrayOutputStream +import java.io.Serializable +import android.graphics.Bitmap + +// ------- Core Types ---------- +class MarkerState( + position: GeoPointInterface, + id: String? = null, + var extra: Serializable? = null, + icon: MarkerIconInterface? = null, + animation: MarkerAnimation? = null, + zIndex: Int? = null, + clickable: Boolean = true, + draggable: Boolean = false, + onClick: OnMarkerEventHandler? = null, + onDragStart: OnMarkerEventHandler? = null, + onDrag: OnMarkerEventHandler? = null, + onDragEnd: OnMarkerEventHandler? = null, + onAnimateStart: OnMarkerEventHandler? = null, + onAnimateEnd: OnMarkerEventHandler? = null, + onAdded: OnMarkerEventHandler? = null, +) : ComponentState { + override val id = + ( + id ?: markerId( + listOf( + position.hashCode(), + extra?.hashCode() ?: 0, + icon?.hashCode() ?: 0, + clickable.hashCode(), + draggable.hashCode(), + animation?.hashCode() ?: 0, + ), + ) + ).toString() + + private fun markerId(hashCodes: List): Int = + hashCodes.reduce { result, hashCode -> + 31 * result + hashCode + } + + /** + * Writes to the fields below are announced here rather than discovered by + * reading them all back. See [StateMutationSignal]. + */ + override val mutations = StateMutationSignal() + + private val currentIcon = mutations.notifying(icon) + + /** [iconRevision] の中身。URL の画像が届くたびに増える。 */ + internal val iconRevisionState = mutableIntStateOf(0) + + var icon: MarkerIconInterface? + get() = currentIcon.value + set(value) { + val changed = currentIcon.value != value + currentIcon.value = value + if (changed) redrawWhenImageLoaded(value) + } + var clickable by mutations.notifying(clickable) + var draggable by mutations.notifying(draggable) + var onClick by mutations.notifying(onClick) + var onDragStart by mutations.notifying(onDragStart) + var onDrag by mutations.notifying(onDrag) + var onDragEnd by mutations.notifying(onDragEnd) + var onAnimateStart by mutations.notifying(onAnimateStart) + var onAnimateEnd by mutations.notifying(onAnimateEnd) + + /** + * Called once each time this marker goes from not being on the map to being on it: + * after the map SDK's object for it has been created, or, when it is drawn in tiles, + * after the URL template of those tiles has been handed to the map as a raster layer + * (the tile images may still be loading then). Not called for an in-place change, + * nor when it moves between native drawing and tiles while staying on the map; + * called again if it is removed and added again. Clearing or destroying the map calls + * nothing. + * + * Runs on the main thread once the map has finished adding the overlays it was given. + * A callback that throws is logged and does not stop the other overlays' callbacks. + * + * Like `onClick`, it is not part of the id, fingerprint, equality or hash: replacing + * it redraws nothing. If the same state is shown on two maps, each map calls it. + */ + var onAdded: OnMarkerEventHandler? = onAdded + var zIndex by mutations.notifying(zIndex) + + private var internalAnimation by mutations.notifying(animation) + + init { + redrawWhenImageLoaded(icon) + } + + /** + * URL の画像がまだ届いていないアイコンなら、届いたときに描き直させる。 + * + * アイコンの見た目(hashCode)は画像が届いた時点で変わるが、[icon] 自体は書き換わらない + * ので、ここで知らせる。そのときもまだ同じアイコンを付けていれば、だけ。 + * 読み込みのスレッドから呼ばれるが、[StateMutationSignal.notifyMutated] はどのスレッドからでもよい。 + */ + private fun redrawWhenImageLoaded(icon: MarkerIconInterface?) { + val image = icon as? ImageIcon ?: return + image.whenImageLoaded { + if (currentIcon.value === image) { + iconRevisionState.intValue++ + mutations.notifyMutated() + } + } + } + + @Deprecated("Binary compatibility only; use the overload with onAdded.", level = DeprecationLevel.HIDDEN) + constructor( + position: GeoPointInterface, + id: String? = null, + extra: Serializable? = null, + icon: MarkerIconInterface? = null, + animation: MarkerAnimation? = null, + zIndex: Int? = null, + clickable: Boolean = true, + draggable: Boolean = false, + onClick: OnMarkerEventHandler? = null, + onDragStart: OnMarkerEventHandler? = null, + onDrag: OnMarkerEventHandler? = null, + onDragEnd: OnMarkerEventHandler? = null, + onAnimateStart: OnMarkerEventHandler? = null, + onAnimateEnd: OnMarkerEventHandler? = null, + ) : this( + position, + id, + extra, + icon, + animation, + zIndex, + clickable, + draggable, + onClick, + onDragStart, + onDrag, + onDragEnd, + onAnimateStart, + onAnimateEnd, + null, + ) + + fun animate(animation: MarkerAnimation?) { + internalAnimation = animation + } + + fun getAnimation(): MarkerAnimation? = internalAnimation + + private val currentPosition = mutations.notifying(position) + var position: GeoPointInterface + get() { + return currentPosition.value + } + set(value) { + currentPosition.value = value + } + + /** + * Copies this state, carrying every property over unless overridden. + * + * [animation] is copied like everything else. It used to be silently + * dropped — the parameter did not exist and the new instance was built + * without one — so `marker.copy(position = p)` on a bouncing marker + * returned a still one. Nothing about a copy implies "stop animating", and + * ios-sdk / react-sdk both carry it over. + */ + fun copy( + id: String? = this.id, + position: GeoPointInterface = this.position, + extra: Serializable? = this.extra, + icon: MarkerIconInterface? = this.icon, + animation: MarkerAnimation? = this.getAnimation(), + zIndex: Int? = this.zIndex, + clickable: Boolean? = this.clickable, + draggable: Boolean? = this.draggable, + onClick: OnMarkerEventHandler? = this.onClick, + onDragStart: OnMarkerEventHandler? = this.onDragStart, + onDrag: OnMarkerEventHandler? = this.onDrag, + onDragEnd: OnMarkerEventHandler? = this.onDragEnd, + onAnimateStart: OnMarkerEventHandler? = this.onAnimateStart, + onAnimateEnd: OnMarkerEventHandler? = this.onAnimateEnd, + onAdded: OnMarkerEventHandler? = this.onAdded, + ): MarkerState = + MarkerState( + id = id, // Keep marker id + position = position, + extra = extra, + icon = icon, + animation = animation, + zIndex = zIndex, + clickable = clickable ?: this.clickable, + draggable = draggable ?: this.draggable, + onClick = onClick, + onDragStart = onDragStart, + onDrag = onDrag, + onDragEnd = onDragEnd, + onAnimateStart = onAnimateStart, + onAnimateEnd = onAnimateEnd, + onAdded = onAdded, + ) + + @Deprecated("Binary compatibility only; use the overload with onAdded.", level = DeprecationLevel.HIDDEN) + fun copy( + id: String? = this.id, + position: GeoPointInterface = this.position, + extra: Serializable? = this.extra, + icon: MarkerIconInterface? = this.icon, + animation: MarkerAnimation? = this.getAnimation(), + zIndex: Int? = this.zIndex, + clickable: Boolean? = this.clickable, + draggable: Boolean? = this.draggable, + onClick: OnMarkerEventHandler? = this.onClick, + onDragStart: OnMarkerEventHandler? = this.onDragStart, + onDrag: OnMarkerEventHandler? = this.onDrag, + onDragEnd: OnMarkerEventHandler? = this.onDragEnd, + onAnimateStart: OnMarkerEventHandler? = this.onAnimateStart, + onAnimateEnd: OnMarkerEventHandler? = this.onAnimateEnd, + ): MarkerState = + copy( + id, + position, + extra, + icon, + animation, + zIndex, + clickable, + draggable, + onClick, + onDragStart, + onDrag, + onDragEnd, + onAnimateStart, + onAnimateEnd, + onAdded, + ) + + override fun equals(other: Any?): Boolean { + val otherState = (other as? MarkerState) ?: return false + return hashCode() == otherState.hashCode() + } + + override fun hashCode(): Int { + var result = extra?.hashCode() ?: 0 + result = 31 * result + clickable.hashCode() + result = 31 * result + draggable.hashCode() + result = 31 * result + currentPosition.value.latitude.hashCode() + result = 31 * result + currentPosition.value.longitude.hashCode() + result = 31 * result + currentPosition.value.altitude.hashCode() + result = 31 * result + (icon?.hashCode() ?: 0) + result = 31 * result + zIndex.hashCode() + return result + } + + fun fingerPrint(): MarkerFingerPrint = + MarkerFingerPrint( + this.id.hashCode(), + icon.hashCode(), + clickable.hashCode(), + draggable.hashCode(), + currentPosition.value.latitude.hashCode(), + currentPosition.value.longitude.hashCode(), + internalAnimation?.hashCode() ?: 1, + zIndex.hashCode(), + ) +} + +data class MarkerFingerPrint( + val id: Int, + val icon: Int?, + val clickable: Int, + val draggable: Int, + val latitude: Int, + val longitude: Int, + val animation: Int?, + val zIndex: Int, +) +typealias OnMarkerEventHandler = (MarkerState) -> Unit + +data class BitmapIcon( + val bitmap: Bitmap, + val anchor: Offset, + val size: Size, +) { + fun toByteArray(): ByteArray { + val outputStream = ByteArrayOutputStream() + bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream) + return outputStream.toByteArray() + } +} diff --git a/src/main/java/com/mapconductor/core/marker/MarkerCollector.kt b/src/main/java/com/mapconductor/core/marker/MarkerCollector.kt index 63cf26e..c614b0f 100644 --- a/src/main/java/com/mapconductor/core/marker/MarkerCollector.kt +++ b/src/main/java/com/mapconductor/core/marker/MarkerCollector.kt @@ -11,7 +11,6 @@ class MarkerCollector( updateDebounce: Duration = Settings.Default.composeEventDebounce, scope: CoroutineScope = CoroutineScope(Dispatchers.Main.immediate), ) : OverlayCollectorInterface by OverlayCollector( - fingerPrintOf = { it.fingerPrint() }, updateDebounce = updateDebounce, scope = scope, ) diff --git a/src/main/java/com/mapconductor/core/marker/MarkerDrawOrder.kt b/src/main/java/com/mapconductor/core/marker/MarkerDrawOrder.kt new file mode 100644 index 0000000..e263e89 --- /dev/null +++ b/src/main/java/com/mapconductor/core/marker/MarkerDrawOrder.kt @@ -0,0 +1,161 @@ +package com.mapconductor.core.marker + +import com.mapconductor.core.InternalMapConductorApi +import com.mapconductor.core.features.GeoPointInterface +import kotlin.math.PI +import kotlin.math.abs +import kotlin.math.cos +import kotlin.math.floor +import kotlin.math.ln +import kotlin.math.sin +import kotlin.math.sqrt + +/** + * マーカーの帯の中での描く順。どのドライバーもこれで並べる。 + * + * - 第 1 キーは `zIndex`(未指定は 0)。大きいほど手前。 + * - 同じ `zIndex` なら、**地図の向きに合わせた画面で下にあるほど**手前。 + * 画面上の高さも同じなら左ほど手前(北が上なら南ほど・西ほど手前)。 + * + * 2 つ目は Google Maps JS の既定(画面で下のマーカーが手前、回転するとその場で + * 入れ替わる)に合わせている。ただし Google は高さが同じとき後から足した方を + * 手前にするが、ここでは左を手前にして、追加した順には左右させない。 + * + * 返す値は `zIndex + 端数`。端数は [0, 0.5) に収めるので、`zIndex` の大小を + * 決してひっくり返さない。以前は未指定のときだけ `-緯度 × 10^6 - 経度` を + * 使っていたため、次の 2 つが起きていた。 + * + * - 北半球(東京で約 -3.57e7)では、Google Maps が明示の `zIndex = 1` を + * それより奥に描いた(大きすぎる値を正しく比べない。実機で確認)。 + * - 南半球では値が大きな正になり、明示の小さな `zIndex` を追い越した。 + * + * 値を小さく保つのはそのため。 + * + * 向きは [Frame] で渡す。省略すると北が上([Frame.NorthUp])。**タイルに焼き込む + * マーカーは常に北が上で並べる**(タイルは北が上で描くので、回転のたびに描き直す + * ことになるため)。 + */ +@InternalMapConductorApi +object MarkerDrawOrder { + /** 端数の上限。0.5 未満にして、隣の `zIndex` と重ならないようにする。 */ + private const val TIEBREAK_SPAN = 0.45 + + /** 左右の寄与。画面上の高さが同じときだけ効くよう、十分小さくする。 */ + private const val LEFT_WEIGHT = 1e-9 + + private const val MAX_MERCATOR_LATITUDE = 85.05112878 + + /** 並べ直しに値する向きの変化(度)。 */ + private const val HEADING_STEP = 0.5 + + /** 並べ直しに値する基準経度の変化(度)。ずれが効くのは基準の裏側(±180°)だけ。 */ + private const val ORIGIN_STEP = 90.0 + + /** + * 並べる向き。 + * + * @property headingDegrees カメラが向いている方位(heading。時計回り、度。90 なら + * 画面の上が東)。MapConductor の `bearing` とは符号が逆なので + * [com.mapconductor.core.map.CameraBearing.toNativeHeading] で直して渡す。 + * @property originLongitude 経度の折り返しの基準。カメラの中心の経度を渡すと、 + * 日付変更線をまたいで見ていても正しく並ぶ。 + */ + data class Frame( + val headingDegrees: Double = 0.0, + val originLongitude: Double = 0.0, + ) { + /** [other] から変わったとき、並べ直す必要があるか。 */ + fun differsEnoughFrom(other: Frame): Boolean = + angleBetween(headingDegrees, other.headingDegrees) >= HEADING_STEP || + angleBetween(originLongitude, other.originLongitude) >= ORIGIN_STEP + + companion object { + val NorthUp = Frame() + } + } + + /** + * 描く順の値。大きいほど手前。 + * + * Float にして渡す SDK(Google Maps)でも、`zIndex` が数百までなら数十メートルの + * 差を見分けられる。 + */ + fun of( + zIndex: Int?, + position: GeoPointInterface, + headingDegrees: Double = 0.0, + originLongitude: Double = 0.0, + ): Double = (zIndex ?: 0) + tiebreak(position, headingDegrees, originLongitude) + + fun of( + zIndex: Int?, + position: GeoPointInterface, + frame: Frame, + ): Double = of(zIndex, position, frame.headingDegrees, frame.originLongitude) + + /** + * 整数しか受けない SDK 向け(HERE の `drawOrder` など)。 + * + * `zIndex × [INT_STRIDE] + 端数を [INT_STRIDE] 段に刻んだ値`。`zIndex` は + * ±(Int.MAX / [INT_STRIDE]) の範囲に収めること。 + */ + fun ofInt( + zIndex: Int?, + position: GeoPointInterface, + headingDegrees: Double = 0.0, + originLongitude: Double = 0.0, + ): Int { + val primary = (zIndex ?: 0).coerceIn(-MAX_INT_Z_INDEX, MAX_INT_Z_INDEX) + val step = (tiebreak(position, headingDegrees, originLongitude) / TIEBREAK_SPAN * (INT_STRIDE - 1)).toInt() + return primary * INT_STRIDE + step + } + + fun ofInt( + zIndex: Int?, + position: GeoPointInterface, + frame: Frame, + ): Int = ofInt(zIndex, position, frame.headingDegrees, frame.originLongitude) + + /** [ofInt] で 1 つの `zIndex` に割り当てる段の数。赤道でおよそ 60 m 刻み。 */ + const val INT_STRIDE: Int = 1_000_000 + + /** [ofInt] が扱える `zIndex` の絶対値。 */ + const val MAX_INT_Z_INDEX: Int = Int.MAX_VALUE / INT_STRIDE - 1 + + private fun tiebreak( + position: GeoPointInterface, + headingDegrees: Double, + originLongitude: Double, + ): Double { + // Web Mercator の世界座標 [0, 1]。y は北が 0、南が 1。 + val latitude = position.latitude.coerceIn(-MAX_MERCATOR_LATITUDE, MAX_MERCATOR_LATITUDE) + val wx = (position.longitude + 180.0) / 360.0 + val sinLat = sin(latitude * PI / 180.0) + val wy = 0.5 - ln((1.0 + sinLat) / (1.0 - sinLat)) / (4.0 * PI) + // 基準からの差。経度は [-0.5, 0.5) に折り返す。 + val dx = wrap(wx - (originLongitude + 180.0) / 360.0) + val dy = wy - 0.5 + // 画面の下向き・右向きの成分(カメラは北から時計回りに heading だけ向いている)。 + val theta = headingDegrees * PI / 180.0 + val down = -dx * sin(theta) + dy * cos(theta) + val right = dx * cos(theta) + dy * sin(theta) + // どちらも [0, 1] に収める(|dx|, |dy| ≤ 0.5 なので回しても √2 / 2 以内)。 + val down01 = (0.5 + down / SQRT2).coerceIn(0.0, 1.0) + val left01 = (0.5 - right / SQRT2).coerceIn(0.0, 1.0) + val share = down01 * (1.0 - LEFT_WEIGHT) + left01 * LEFT_WEIGHT + // 0.5 に届かないよう、端の 1.0 は上限の少し手前に寄せる。 + return (TIEBREAK_SPAN * share).coerceAtMost(TIEBREAK_SPAN * (1.0 - 1e-12)) + } + + private val SQRT2 = sqrt(2.0) + + private fun wrap(value: Double): Double = value - floor(value + 0.5) + + private fun angleBetween( + a: Double, + b: Double, + ): Double { + val d = abs(((a - b) % 360.0 + 360.0) % 360.0) + return if (d > 180.0) 360.0 - d else d + } +} diff --git a/src/main/java/com/mapconductor/core/marker/MarkerDrawOrderTracker.kt b/src/main/java/com/mapconductor/core/marker/MarkerDrawOrderTracker.kt new file mode 100644 index 0000000..50886f5 --- /dev/null +++ b/src/main/java/com/mapconductor/core/marker/MarkerDrawOrderTracker.kt @@ -0,0 +1,95 @@ +package com.mapconductor.core.marker + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.snapshotFlow +import com.mapconductor.core.InternalMapConductorApi +import com.mapconductor.core.map.CameraBearing +import com.mapconductor.core.map.MapCameraPosition +import kotlin.time.Duration +import kotlin.time.Duration.Companion.milliseconds +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Job +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.collectLatest +import kotlinx.coroutines.launch + +/** + * 地図の向きに合わせてマーカーを並べ直してもらう側。 + * + * マーカーのコントローラが実装し、[com.mapconductor.core.controller.BaseMapViewController] + * が向きの変化を配る。 + */ +@InternalMapConductorApi +interface MarkerDrawOrderReceiver { + suspend fun onDrawOrderFrameChanged(frame: MarkerDrawOrder.Frame) +} + +/** + * カメラの向きを見て、[MarkerDrawOrder.Frame] が変わったら一度だけ知らせる。 + * + * 回している間は毎フレームのカメラが来るので、向きが [settle] のあいだ止まってから + * 知らせる(大量のマーカーを毎フレーム並べ直さない)。パンやズームでは前後関係が + * 変わらないので知らせない。 + */ +@InternalMapConductorApi +class MarkerDrawOrderTracker( + private val scope: CoroutineScope, + private val settle: Duration = 150.milliseconds, + private val onChanged: suspend (MarkerDrawOrder.Frame) -> Unit, +) { + /** 今マーカーを並べている向き。新しく足すマーカーもこれで並べる。 */ + @Volatile + var frame: MarkerDrawOrder.Frame = MarkerDrawOrder.Frame.NorthUp + private set + + private var target: MarkerDrawOrder.Frame = frame + private var pending: Job? = null + + fun onCameraChanged(camera: MapCameraPosition) { + val next = MarkerDrawOrder.Frame(CameraBearing.toNativeHeading(camera.bearing), camera.position.longitude) + synchronized(this) { + if (!next.differsEnoughFrom(target)) return + target = next + pending?.cancel() + pending = + scope.launch { + delay(settle) + frame = next + onChanged(next) + } + } + } +} + +/** + * Compose でマーカーを描くドライバー向けの [MarkerDrawOrderTracker]。 + * + * 後に置いたものほど上に描かれるので、`markers.sortedBy { MarkerDrawOrder.of(..., frame) }` + * の `frame` にこれを渡す。向きが変わって [settle] だけ止まったときだけ値が変わる + * (パン・ズームや回転の途中では組み直さない)。 + */ +@InternalMapConductorApi +@Composable +fun rememberMarkerDrawOrderFrame( + settle: Duration = 150.milliseconds, + camera: () -> MapCameraPosition, +): MarkerDrawOrder.Frame { + val frame = remember { mutableStateOf(MarkerDrawOrder.Frame.NorthUp) } + val latestCamera by rememberUpdatedState(camera) + LaunchedEffect(settle) { + snapshotFlow { + val c = latestCamera() + MarkerDrawOrder.Frame(CameraBearing.toNativeHeading(c.bearing), c.position.longitude) + }.collectLatest { next -> + if (!next.differsEnoughFrom(frame.value)) return@collectLatest + delay(settle) + frame.value = next + } + } + return frame.value +} diff --git a/src/main/java/com/mapconductor/core/marker/MarkerGrid.kt b/src/main/java/com/mapconductor/core/marker/MarkerGrid.kt new file mode 100644 index 0000000..6b0889e --- /dev/null +++ b/src/main/java/com/mapconductor/core/marker/MarkerGrid.kt @@ -0,0 +1,288 @@ +package com.mapconductor.core.marker + +import com.mapconductor.core.InternalMapConductorApi +import com.mapconductor.core.features.GeoPointInterface + +/** + * The cell arithmetic behind [MarkerGridIndex], with no marker in sight. + * + * Kept apart from the index because none of it depends on what a marker is: it + * is a way of naming a patch of the globe, and the conformance fixtures the + * three SDKs share test it on its own. + * + * ## The scheme + * + * The world starts as **two square cells** — the western and eastern halves, + * 180 degrees on a side — and each is halved in latitude and in longitude, + * repeatedly. The key records the half chosen each time, latitude bit above + * longitude bit, under the bit that says which hemisphere it started in. That + * makes **every prefix of a key a cell:** dropping the low `2n` bits names the + * cell `n` levels up, and all of its children share the prefix, so they form + * one run in a sorted array. A query picks the level that suits its box + * instead of paying the finest one. + * + * The first version packed `(latCell shl 20) or lonCell` at one fixed cell size + * of 0.005 degrees. That key sorts by row, so a cell is a contiguous run but a + * *block* of cells is not, and there was no way to ask a coarser question. + * + * ## Why two root cells and not one + * + * One root cell covering the whole globe is what cordova-plugin-googlemaps' + * `geomodel.js` uses, and it is what this started as. It makes every cell + * **twice as wide as it is tall**, because the same number of divisions covers + * 360 degrees of longitude and 180 of latitude. + * + * That costs real time. A query asks for cells no wider than some separation; + * with a 2:1 cell, satisfying the width over-resolves the height by a factor of + * two, so the query walks twice the cells and returns twice the markers it + * asked for. Measured on ios-sdk with Tokyo's 144,183 street trees at zoom 11, + * a tile returned 9,715 markers of which the caller kept 2,156, and the work + * that scales with that count — the walk, positioning each marker, and grouping + * them — was 44 ms of the tile's 52 ms. + * + * Splitting the root into two square halves removes the factor of two. The + * string form keeps its shape: a hemisphere digit followed by geocell + * characters over `0123456789abcdef`, one per 4x4 subdivision, and a prefix is + * still a cell. What it is no longer is byte-identical to `geomodel.js`. + * + * The three SDKs hold the key as a `Long`, an `Int64` and a `number`; the + * string is what their conformance fixtures compare, because it does not depend + * on that choice. + */ +@InternalMapConductorApi +internal object MarkerGrid { + /** + * Levels of 2x2 subdivision below the two root cells. + * + * 18 is the largest depth that still leaves room for the position: the key + * is `2 * 18 + 1 = 37` bits — the extra one is the hemisphere — and the + * position below it is 24, which is 61 of the 63 a `Long` has. It is also + * an even number of levels, so the string form packs into whole 4-bit + * characters with no ragged tail. + * + * A cell at the bottom is 0.000687 degrees on a side, about 76 m at the + * equator. The flat grid this replaced was 0.005 degrees. + */ + const val GRID_DEPTH = 18 + + /** + * Roughly how many cells across a box a query aims to walk. + * + * The level is chosen so the box covers about this many cells squared, + * which bounds the walk no matter how large the box is. That is what + * removed the old "past 4096 cells, scan every marker instead" escape: a + * world-sized box now asks a coarse level and reads roughly the markers it + * would have scanned anyway, without the cliff. + */ + private const val CELLS_ACROSS = 32.0 + + /** + * The most cells a query walks along either axis. + * + * Only bites on a box so flat or so narrow that its area says nothing about + * how many cells it crosses. + */ + private const val MAX_CELLS_PER_AXIS = 64.0 + + private const val ALPHABET = "0123456789abcdef" + + /** Degrees a cell spans, on either axis. Cells are square. */ + fun cellSize(level: Int): Double = 180.0 / (1L shl level) + + /** Rows of cells from pole to pole at [level]. */ + fun rows(level: Int): Long = 1L shl level + + /** + * Columns of cells around the globe at [level]. Twice the rows, because the + * world is twice as wide as it is tall and the cells are square. + */ + fun columns(level: Int): Long = 1L shl (level + 1) + + /** + * The coarsest level whose cells are no wider than [separation], or null if + * even the bottom level is coarser than that. + * + * Counted up rather than solved with a logarithm, because the three SDKs + * have to agree on the answer and they do not have the same `log2`. Java + * has none at all — Kotlin computes `ln(x) / ln(2)`, which is off by an ulp + * where the true answer is a whole number, and a `ceil` above it turns that + * ulp into a different level. Halving a double and comparing it is exact on + * all three. + */ + fun levelForSeparation(separation: Double): Int? { + if (!(separation > 0.0)) return null + var level = 0 + while (level <= GRID_DEPTH) { + if (cellSize(level) <= separation) return level + level++ + } + return null + } + + /** + * The level a bounds query walks, chosen so the box covers about + * [CELLS_ACROSS] squared cells. + * + * Counted up for the same reason as [levelForSeparation]. + * + * The area rule alone is not enough. A box with no height — a click box + * flattened by a degenerate projection, a bounds built from two points on + * the same parallel — has an area of nothing, which asks for the bottom + * level, which is a quarter of a million columns to walk. + * [MAX_CELLS_PER_AXIS] steps back up until neither axis is absurd. On a box + * of ordinary shape the area rule binds first and this does nothing. + */ + fun queryLevel( + latSpan: Double, + lonSpan: Double, + ): Int { + val area = maxOf(lonSpan, 1e-12) * maxOf(latSpan, 1e-12) + // cells at a level = area / cellSize^2, and cellSize = 180 / 2^level + val budget = CELLS_ACROSS * CELLS_ACROSS * 180.0 * 180.0 + var level = 0 + while (level < GRID_DEPTH && area * (1L shl (2 * (level + 1))).toDouble() <= budget) { + level++ + } + while (level > 0 && + ( + lonSpan / cellSize(level) > MAX_CELLS_PER_AXIS || + latSpan / cellSize(level) > MAX_CELLS_PER_AXIS + ) + ) { + level-- + } + return level + } + + /** + * How far east the box runs, from its west edge to its east one. + * + * A box crossing the antimeridian has its east corner west of its west one, + * and a padded box can run past ±180 outright. Normalising to a single + * eastward span removes both cases: everything downstream walks east from + * the west edge for this many degrees, and never compares two longitudes. + */ + fun eastwardSpan( + west: Double, + east: Double, + ): Double { + if (east - west >= 360.0) return 360.0 + return ((east - west) % 360.0 + 360.0) % 360.0 + } + + /** + * Where the column walk starts, packed with how many columns to walk. + * + * The end column is taken from `west + span`, not from the east corner. + * Taking it from the corner cannot work once column indices fold: the + * column holding 180 and the column holding -180 are the same one, so a box + * from -180.2 to 179.8 starts and ends on the same column and the walk + * covers one column out of the level's many. Nothing errors; the query + * simply answers for a thin slice of the world. + * + * The old row-major key did not have this hazard, because it indexed on + * unwrapped column numbers that kept growing eastward. Folding is what + * makes a Morton key a fixed width, so the walk has to carry the span + * itself. + * + * Returned as a pair rather than two calls so the two halves cannot drift. + */ + fun columnWalk( + west: Double, + span: Double, + level: Int, + ): Pair { + val total = columns(level) + val start = Math.floor((west + 180.0) / 360.0 * total).toLong() + val end = Math.floor((west + span + 180.0) / 360.0 * total).toLong() + // A full turn ends on the column it started on; walking both would + // return that column's markers twice. + return start to minOf(end - start + 1, total) + } + + fun latCell( + latitude: Double, + level: Int, + ): Long { + val count = rows(level) + val at = Math.floor((latitude + 90.0) / 180.0 * count).toLong() + return minOf(maxOf(at, 0L), count - 1) + } + + fun lonCell( + longitude: Double, + level: Int, + ): Long { + val count = columns(level) + return wrap(Math.floor((longitude + 180.0) / 360.0 * count).toLong(), level) + } + + fun wrap( + lonCell: Long, + level: Int, + ): Long = Math.floorMod(lonCell, columns(level)) + + fun mortonKeyFor(position: GeoPointInterface): Long = + morton( + latCell(position.latitude, GRID_DEPTH), + lonCell(position.longitude, GRID_DEPTH), + GRID_DEPTH, + ) + + /** + * Interleaves the two indices, latitude in the odd bits, under the bit that + * says which root cell they are in. + * + * Longitude carries one bit more than latitude — twice as many columns as + * rows — and that top bit is the hemisphere. It sits above the interleaved + * pairs rather than inside them, so dropping the low two bits still names + * the parent cell. + */ + fun morton( + latCell: Long, + lonCell: Long, + level: Int, + ): Long { + val hemisphere = lonCell shr level + val within = lonCell and ((1L shl level) - 1) + return (hemisphere shl (2 * level)) or (spread(latCell) shl 1) or spread(within) + } + + /** Spreads a value's bits apart, leaving a zero between each pair. */ + private fun spread(value: Long): Long { + var x = value and 0xFFFFFFFFL + x = (x or (x shl 16)) and 0x0000FFFF0000FFFFL + x = (x or (x shl 8)) and 0x00FF00FF00FF00FFL + x = (x or (x shl 4)) and 0x0F0F0F0F0F0F0F0FL + x = (x or (x shl 2)) and 0x3333333333333333L + x = (x or (x shl 1)) and 0x5555555555555555L + return x + } + + /** + * The cell's name as a string: a hemisphere digit, then one character per + * 4x4 subdivision over `0123456789abcdef`. + * + * Each character after the first is two levels of this grid, so a string of + * [characters] names the cell at level `2 * (characters - 1)`. Not used by + * the index itself — the key is the same information, and faster — but it is + * the form the three SDKs' conformance fixtures compare, because it does not + * depend on how a platform stores an integer. + */ + fun geocell( + latitude: Double, + longitude: Double, + characters: Int, + ): String { + val level = minOf(maxOf(characters - 1, 0) * 2, GRID_DEPTH) + val key = morton(latCell(latitude, level), lonCell(longitude, level), level) + val text = StringBuilder() + text.append(key shr (2 * level)) + var at = level * 2 - 4 + while (at >= 0) { + text.append(ALPHABET[((key shr at) and 0xF).toInt()]) + at -= 4 + } + return text.toString() + } +} diff --git a/src/main/java/com/mapconductor/core/marker/MarkerGridIndex.kt b/src/main/java/com/mapconductor/core/marker/MarkerGridIndex.kt new file mode 100644 index 0000000..d117743 --- /dev/null +++ b/src/main/java/com/mapconductor/core/marker/MarkerGridIndex.kt @@ -0,0 +1,515 @@ +package com.mapconductor.core.marker + +import com.mapconductor.core.InternalMapConductorApi +import com.mapconductor.core.features.GeoPointInterface +import com.mapconductor.core.features.GeoRectBounds +import java.util.Arrays + +/** + * A hierarchical lat/lng grid over the markers, held as one sorted primitive array. + * + * It replaced a hex-cell registry and its kd-tree, since removed. That index + * was built at a fixed zoom of 20, which puts a cell at about 12 cm — street + * trees are metres apart, so every marker landed in its own cell and the index + * grouped nothing. It cost a HexCell object and a String id per marker, a pair + * of concurrent maps and a kd-tree node each; on Tokyo's 144,183 street trees, + * building it aborted the process with a native out-of-memory. + * + * Here each marker is one Long: its cell key above its position in a snapshot. + * Building the index is an arithmetic pass and a primitive sort, measured at + * 41 ms for those same 144,183 markers on a Pixel 5a, in 1.15 MB. + * + * A bounds query walks the cells the box covers and binary-searches each one's + * run — 0.06 ms for a tile-sized box, against 1.9 ms to scan every marker. + * + * The key is a Morton code over a hierarchy of cells, described in [MarkerGrid]. + * What it buys the index is that a cell at *any* level is one contiguous run, + * so a query walks the level that suits its box rather than the finest one. The + * first version had a single fixed cell size of 0.005 degrees and had to fall + * back to scanning once a box touched more than 4,096 of them; choosing the + * level removes that cliff. + * + * The index owns no markers. It is handed the manager's collection and takes a + * snapshot when it rebuilds, so nothing here duplicates the map the manager + * already keeps — an id-to-slot map of its own cost several megabytes at this + * size, for information that already existed. + * + * ## Changes are applied, not rebuilt + * + * The first version threw the index away on every change, so a query after + * any change paid the full build. An app that swaps a few hundred markers on + * every pan paid it on every tap and every tile: on a Pixel 5a, 83 ms at + * 60,000 markers and 182 ms at 144,000, up to 780 ms, after 300 swaps. + * + * Now a marker that arrives takes the next slot and its entry waits in + * [pending]; the next query sorts only those and merges them into [packed] in + * one linear pass. A marker that leaves only empties its slot — queries skip + * empty slots, and the next merge drops their entries. Only when half the slots + * are empty, or the index lost track of a marker, does it rebuild from the + * manager's collection. + * + * Finding a leaving marker's entry needs no map either. Its entry is in the run + * of the cell its position falls in, found by binary search and matched by + * identity. The exception is a marker whose position was changed in place + * after it was filed — a drag does that — and for that one the slots are + * scanned, which is still far less than a rebuild. + */ +@InternalMapConductorApi +internal class MarkerGridIndex( + private val source: () -> Collection>, +) { + /** Slot -> marker. A marker that left leaves a null. */ + @Volatile + private var snapshot: Array?> = emptyArray() + + /** Sorted `(mortonKey shl INDEX_BITS) or slot`. */ + @Volatile + private var packed = LongArray(0) + + /** Entries for markers that arrived since the last merge, unsorted. */ + private var pending = LongArray(0) + private var pendingCount = 0 + + /** Slots handed out, live or empty. */ + private var slotCount = 0 + + /** Slots emptied by markers that left. */ + private var emptySlots = 0 + + @Volatile + private var dirty = true + + /** Whether the index currently holds a built snapshot. */ + val isBuilt: Boolean + get() = !dirty + + /** Roughly what the index costs: two longs a marker, key and reference. */ + fun estimatedBytes(): Long = packed.size * 8L + snapshot.size * 8L + pending.size * 8L + + /** Marks the index stale. The rebuild happens on the next query. */ + @Synchronized + fun invalidate() { + dirty = true + } + + /** Files a marker that was not in the index. */ + @Synchronized + fun add(entity: MarkerEntityInterface) { + // Until the first build, or while a rebuild is due, the rebuild reads the + // manager's collection and will see this marker there. + if (dirty) return + if (slotCount == MAX_SLOTS) { + dirty = true + return + } + if (slotCount == snapshot.size) snapshot = snapshot.copyOf(maxOf(16, slotCount * 2)) + val slot = slotCount++ + snapshot[slot] = entity + if (pendingCount == pending.size) pending = pending.copyOf(maxOf(16, pendingCount * 2)) + pending[pendingCount++] = (MarkerGrid.mortonKeyFor(entity.state.position) shl INDEX_BITS) or slot.toLong() + } + + /** Forgets a marker. */ + @Synchronized + fun remove(entity: MarkerEntityInterface) { + if (dirty) return + val slot = locate(entity) + if (slot < 0) { + // Not where it should be: the index lost track of it somewhere, so + // stop trusting it rather than return a marker that has gone. + dirty = true + return + } + snapshot[slot] = null + emptySlots++ + } + + /** + * [previous] is replaced by [entity] under the same id — the same object + * after a change, or a new one. + * + * Most updates leave the marker in its cell: an icon or a flag changed. Then + * only the reference in its slot is swapped, and nothing waits for a merge. + */ + @Synchronized + fun replace( + previous: MarkerEntityInterface, + entity: MarkerEntityInterface, + ) { + if (dirty) return + val slot = locateInCell(previous, MarkerGrid.mortonKeyFor(entity.state.position)) + if (slot >= 0) { + snapshot[slot] = entity + return + } + remove(previous) + add(entity) + } + + /** The slot holding [entity], or -1. */ + private fun locate(entity: MarkerEntityInterface): Int { + val slot = locateInCell(entity, MarkerGrid.mortonKeyFor(entity.state.position)) + if (slot >= 0) return slot + // Its position changed in place since it was filed, so its entry is in + // some other cell's run. Scan the slots. + val slots = snapshot + for (at in 0 until slotCount) { + if (slots[at] === entity) return at + } + return -1 + } + + /** The slot holding [entity] if it was filed under bottom-level [key], or -1. */ + private fun locateInCell( + entity: MarkerEntityInterface, + key: Long, + ): Int { + val slots = snapshot + for (at in 0 until pendingCount) { + val entry = pending[at] + if (entry ushr INDEX_BITS != key) continue + val slot = (entry and INDEX_MASK).toInt() + if (slots[slot] === entity) return slot + } + val entries = packed + val limit = (key + 1) shl INDEX_BITS + var at = lowerBound(entries, key shl INDEX_BITS) + while (at < entries.size && entries[at] < limit) { + val slot = (entries[at] and INDEX_MASK).toInt() + if (slots[slot] === entity) return slot + at++ + } + return -1 + } + + /** Markers whose position falls inside [bounds]. */ + fun inBounds(bounds: GeoRectBounds): List> { + val southWest = bounds.southWest ?: return emptyList() + val northEast = bounds.northEast ?: return emptyList() + + // A box crossing the antimeridian has its east corner west of its west + // one, and a padded box can run past ±180 outright. Both fold into a + // single eastward sweep from the west edge. + val lonSpan = MarkerGrid.eastwardSpan(southWest.longitude, northEast.longitude) + val level = MarkerGrid.queryLevel(northEast.latitude - southWest.latitude, lonSpan) + + val latFrom = MarkerGrid.latCell(southWest.latitude, level) + val latTo = MarkerGrid.latCell(northEast.latitude, level) + if (latTo < latFrom) return emptyList() + val (firstColumn, columnCount) = MarkerGrid.columnWalk(southWest.longitude, lonSpan, level) + + rebuildIfNeeded() + val found = ArrayList>() + for (latCell in latFrom..latTo) { + for (step in 0 until columnCount) { + val key = MarkerGrid.morton(latCell, MarkerGrid.wrap(firstColumn + step, level), level) + forEachInCell(key, level) { entity -> + if (bounds.contains(entity.state.position)) found.add(entity) + } + } + } + return found + } + + /** + * One marker for each cell the bounds touch. + * + * For a caller that is about to drop markers closer together than + * [minSeparationDegrees] anyway, visiting the ones it will drop is pure + * cost. At zoom 9 a street tree tile holds 141,221 markers and keeps 9,216; + * reading a position off an entity costs 0.72 microseconds, so merely + * looking at that set is 101 ms before anything is done with it. + * + * Walking cells instead visits the roughly 5,000 that hold anything, and + * each one is a binary search and a single entry taken from the end of its + * run. The level comes from the separation: the coarsest one whose cells + * are no wider than the caller asked for. + * + * ## Why the winner cannot depend on the bounds + * + * A cell's representative is the **last entry of its run, always** — not + * the last entry that falls inside the bounds. The difference is what a map + * made of tiles looks like at the seams. + * + * Tiles are rendered one at a time, each asking for its own box grown by + * the icon overhang. A cell straddling the boundary is asked about twice, + * by two different boxes. Choose the winner from what is inside the box and + * the two tiles choose **different markers:** one marker gets its left half + * drawn on the left tile and nothing on the right, so the icon is cut down + * the seam with no error anywhere. Measured on Tokyo's street trees, 74 + * markers at zoom 9 and 84 at zoom 10 were drawn by one tile and not by its + * neighbour. + * + * Choosing without looking at the box removes the disagreement: a marker + * whose icon reaches the next tile is inside that tile's grown box too, so + * that tile asks about the same cell and gets the same answer. + * + * A returned marker may therefore lie just outside [bounds], by less than + * one cell. The renderer clips it; what it must not do is filter the list + * back down to the box, because that would put the disagreement back. + * + * Returns null when the index cannot help: a separation finer than the + * bottom level would thin more than it asked for, and a box spanning more + * cells than [MAX_CELLS_PER_THINNED_QUERY] is cheaper to scan. + */ + fun inBoundsThinned( + bounds: GeoRectBounds, + minSeparationDegrees: Double, + ): List>? { + val level = MarkerGrid.levelForSeparation(minSeparationDegrees) ?: return null + val southWest = bounds.southWest ?: return null + val northEast = bounds.northEast ?: return null + + val lonSpan = MarkerGrid.eastwardSpan(southWest.longitude, northEast.longitude) + val latFrom = MarkerGrid.latCell(southWest.latitude, level) + val latTo = MarkerGrid.latCell(northEast.latitude, level) + if (latTo < latFrom) return emptyList() + val (firstColumn, columnCount) = MarkerGrid.columnWalk(southWest.longitude, lonSpan, level) + if ((latTo - latFrom + 1) * columnCount > MAX_CELLS_PER_THINNED_QUERY) return null + + rebuildIfNeeded() + val entries = packed + val slots = snapshot + val shift = INDEX_BITS + 2 * (MarkerGrid.GRID_DEPTH - level) + val found = ArrayList>() + for (latCell in latFrom..latTo) { + for (step in 0 until columnCount) { + val key = MarkerGrid.morton(latCell, MarkerGrid.wrap(firstColumn + step, level), level) + val at = lowerBound(entries, key shl shift) + if (at >= entries.size) continue + val limit = (key + 1) shl shift + if (entries[at] >= limit) continue + // The run's last live entry. No containment test anywhere: that + // is the whole point, and it is also why this is cheaper than + // the version that scanned every border cell. A marker that + // left empties its slot without moving the entries, so step + // back over those. + var last = at + while (last + 1 < entries.size && entries[last + 1] < limit) last++ + while (last >= at) { + val entity = slots[(entries[last] and INDEX_MASK).toInt()] + if (entity != null) { + found.add(entity) + break + } + last-- + } + } + } + return found + } + + /** + * The marker nearest [position], by squared degrees. + * + * Rings of cells are searched outward from the one holding the point. The + * stopping rule is a distance, not a ring count: a ring is a square, so a + * hit in one of its corners sits about 1.4 cells further out than a hit on + * its edge, and stopping a fixed ring after the first hit returns the wrong + * marker. Having finished ring r, everything still unsearched is at least r + * cells away, so the search ends once that already exceeds the best + * distance found. + */ + fun nearest(position: GeoPointInterface): MarkerEntityInterface? { + rebuildIfNeeded() + if (packed.isEmpty()) return null + + val level = NEAREST_LEVEL + val centreLat = MarkerGrid.latCell(position.latitude, level) + val centreLon = MarkerGrid.lonCell(position.longitude, level) + + var best: MarkerEntityInterface? = null + var bestDistance = Double.MAX_VALUE + var ring = 0L + + while (ring <= MAX_NEAREST_RINGS) { + forEachInRing(centreLat, centreLon, ring, level) { entity -> + val distance = squaredDegrees(entity, position) + if (distance < bestDistance) { + bestDistance = distance + best = entity + } + } + // A ring is a square: the nearest unsearched point is `ring` cells + // away on the shorter axis, which is latitude. + val reach = ring * MarkerGrid.cellSize(level) + if (best != null && reach * reach >= bestDistance) break + ring++ + } + + // Nothing within the rings searched: the set is sparse enough here that + // scanning is cheaper than widening further. + return best ?: source().minByOrNull { squaredDegrees(it, position) } + } + + private fun squaredDegrees( + entity: MarkerEntityInterface, + position: GeoPointInterface, + ): Double { + val deltaLat = entity.state.position.latitude - position.latitude + val deltaLon = entity.state.position.longitude - position.longitude + return deltaLat * deltaLat + deltaLon * deltaLon + } + + private inline fun forEachInRing( + centreLat: Long, + centreLon: Long, + ring: Long, + level: Int, + body: (MarkerEntityInterface) -> Unit, + ) { + // 行は極で打ち切る。折り返す経度と違い、緯度は 0..rows-1 の外に出たら + // そこにセルは無い。inline 関数なので、ローカル関数に切り出して body を + // 渡すことはできない -- 行の妥当性はここで直接見る。 + val rows = MarkerGrid.rows(level) + if (ring == 0L) { + if (centreLat in 0 until rows) { + forEachInCell(MarkerGrid.morton(centreLat, MarkerGrid.wrap(centreLon, level), level), level, body) + } + return + } + val south = centreLat - ring + val north = centreLat + ring + for (offset in -ring..ring) { + if (south in 0 until rows) { + forEachInCell(MarkerGrid.morton(south, MarkerGrid.wrap(centreLon + offset, level), level), level, body) + } + if (north in 0 until rows) { + forEachInCell(MarkerGrid.morton(north, MarkerGrid.wrap(centreLon + offset, level), level), level, body) + } + } + for (offset in (-ring + 1)..(ring - 1)) { + val row = centreLat + offset + if (row !in 0 until rows) continue + forEachInCell(MarkerGrid.morton(row, MarkerGrid.wrap(centreLon - ring, level), level), level, body) + forEachInCell(MarkerGrid.morton(row, MarkerGrid.wrap(centreLon + ring, level), level), level, body) + } + } + + /** + * Walks one cell at [level]. Its markers are the run whose keys share the + * cell's prefix, which is what interleaving the bits bought. + */ + private inline fun forEachInCell( + key: Long, + level: Int, + body: (MarkerEntityInterface) -> Unit, + ) { + val entries = packed + val slots = snapshot + val shift = INDEX_BITS + 2 * (MarkerGrid.GRID_DEPTH - level) + var at = lowerBound(entries, key shl shift) + val limit = (key + 1) shl shift + while (at < entries.size && entries[at] < limit) { + slots[(entries[at] and INDEX_MASK).toInt()]?.let(body) + at++ + } + } + + @Synchronized + private fun rebuildIfNeeded() { + if (!dirty && emptySlots > REBUILD_MIN_SLOTS && emptySlots * 2 > slotCount) dirty = true + if (dirty) { + rebuild() + return + } + if (pendingCount > 0) merge() + } + + private fun rebuild() { + val entities = source() + val taken = arrayOfNulls>(entities.size) + val keys = LongArray(entities.size) + var at = 0 + for (entity in entities) { + if (at == taken.size) break // grew while we were reading; the next query rebuilds + val position = entity.state.position + taken[at] = entity + keys[at] = (MarkerGrid.mortonKeyFor(position) shl INDEX_BITS) or at.toLong() + at++ + } + Arrays.sort(keys, 0, at) + snapshot = taken + packed = if (at == keys.size) keys else keys.copyOf(at) + slotCount = at + emptySlots = 0 + pending = LongArray(0) + pendingCount = 0 + dirty = false + } + + /** + * Folds the markers that arrived into [packed]: sort those alone, then one + * pass over both sorted runs. Entries whose slot was emptied are dropped on + * the way, from either side. + */ + private fun merge() { + Arrays.sort(pending, 0, pendingCount) + val slots = snapshot + val old = packed + val merged = LongArray(old.size + pendingCount) + var size = 0 + var i = 0 + var j = 0 + while (i < old.size || j < pendingCount) { + val takeOld = j >= pendingCount || (i < old.size && old[i] < pending[j]) + val entry = if (takeOld) old[i++] else pending[j++] + if (slots[(entry and INDEX_MASK).toInt()] != null) merged[size++] = entry + } + packed = if (size == merged.size) merged else merged.copyOf(size) + pendingCount = 0 + } + + private fun lowerBound( + entries: LongArray, + target: Long, + ): Int { + var low = 0 + var high = entries.size + while (low < high) { + val mid = (low + high) ushr 1 + if (entries[mid] < target) low = mid + 1 else high = mid + } + return low + } + + // 注釈の判定はクラス単位で、Companion は別のクラスファイルになる。 + // 外側に付けただけでは空のエントリが凍結サーフェスに残る。 + @InternalMapConductorApi + companion object { + /** + * The same budget for [inBoundsThinned], which earns far more per cell. + * + * A plain bounds query walking 20,000 cells is returning most of the + * markers anyway, so the walk buys nothing over a scan. A thinned query + * walking the same 20,000 returns one marker each instead of visiting + * 141,221, and each cell costs a binary search rather than a scan. + */ + private const val MAX_CELLS_PER_THINNED_QUERY = 1 shl 18 + + /** + * The level [nearest] walks its rings at, and the reach that buys. + * + * Level 15 is 0.0055 degrees on a side, matching the flat cell this + * index used to have, so 100 rings is about 45 km as before. + */ + private const val NEAREST_LEVEL = 15 + + /** Roughly 45 km of rings before giving up and scanning. */ + private const val MAX_NEAREST_RINGS = 100 + + // 24 bits of position, 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 + + /** Slots the index can hand out before it has to rebuild to renumber them. */ + private const val MAX_SLOTS = 1 shl INDEX_BITS + + /** + * Below this many empty slots a rebuild is never worth it. Above it, the + * index rebuilds once half its slots are empty: the dead entries cost a + * skip on every query, and the snapshot holds a slot for each. + */ + private const val REBUILD_MIN_SLOTS = 4096 + } +} diff --git a/src/main/java/com/mapconductor/core/marker/MarkerHitPick.kt b/src/main/java/com/mapconductor/core/marker/MarkerHitPick.kt new file mode 100644 index 0000000..e1216aa --- /dev/null +++ b/src/main/java/com/mapconductor/core/marker/MarkerHitPick.kt @@ -0,0 +1,163 @@ +package com.mapconductor.core.marker + +import androidx.compose.ui.geometry.Offset +import com.mapconductor.core.InternalMapConductorApi +import com.mapconductor.core.ResourceProvider +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.features.GeoPointInterface +import com.mapconductor.core.features.GeoRectBounds +import com.mapconductor.settings.Settings +import kotlin.math.hypot + +/** + * タップ点に当たるマーカーを候補の中から選ぶ(ドライバー実装点)。 + * + * 1 つのマーカーが当たるかどうかは [MarkerHitTest.hitsIcon]、どれを選ぶかはここ。 + * ios-sdk の `MarkerHitTest.pickIndex` / `pick`、react-sdk の `pickMarkerHit` と同じ規則。 + */ +@InternalMapConductorApi +object MarkerHitPick { + /** + * アンカー点を投影した画面座標と、そのアイコンの矩形(px)。[pickIndex] の入力。 + */ + @InternalMapConductorApi + class ScreenRect( + val anchorScreen: Offset, + val widthPx: Double, + val heightPx: Double, + val anchorX: Double, + val anchorY: Double, + ) + + /** + * タップ点に当たるマーカーを選ぶ規則(ios-sdk の `MarkerHitTest.pickIndex`、react-sdk の + * `pickMarkerIndex` と同じ)。 + * + * 1. アイコン(ラベル込み)の矩形そのものにタップ点が入っているものがあれば、その中で + * 画面上いちばん下にアンカーがあるもの(手前に描かれるもの)を選ぶ。近くに別のマーカーの + * 先端があっても、指の下に描かれているマーカーが勝つ。 + * 2. どの矩形にも入っていなければ、矩形 + [tolerancePx] に入るもののうち、アンカーが + * タップ点にいちばん近いものを選ぶ。 + */ + fun pickIndex( + touch: Offset, + rects: List, + tolerancePx: Double, + ): Int? { + var exact: Int? = null + var exactY = Double.NEGATIVE_INFINITY + var near: Int? = null + var nearDistance = Double.POSITIVE_INFINITY + rects.forEachIndexed { index, rect -> + val dx = (touch.x - rect.anchorScreen.x).toDouble() + val dy = (touch.y - rect.anchorScreen.y).toDouble() + if (MarkerHitTest.hitsIconRect(dx, dy, rect.widthPx, rect.heightPx, rect.anchorX, rect.anchorY, 0.0)) { + if (rect.anchorScreen.y > exactY) { + exact = index + exactY = rect.anchorScreen.y.toDouble() + } + } else if (exact == null && + MarkerHitTest.hitsIconRect(dx, dy, rect.widthPx, rect.heightPx, rect.anchorX, rect.anchorY, tolerancePx) + ) { + val distance = hypot(dx, dy) + if (distance < nearDistance) { + near = index + nearDistance = distance + } + } + } + return exact ?: near + } + + /** + * 候補を集める範囲。タップ点から画面上 [SEARCH_RADIUS_DP] 以内に先端があるマーカーを含む。 + * + * ラベルを横に置くとアイコンはピンより大きく広がるので、最寄りの 1 つだけでは足りない。 + * px → 度の換算は、タップ点の近くを投影して局所的に求める(回転していても各軸の長さは保たれる)。 + */ + fun searchBounds( + position: GeoPointInterface, + touchScreen: Offset, + project: (GeoPointInterface) -> Offset?, + density: Double = ResourceProvider.getDensity().toDouble(), + ): GeoRectBounds? { + // The scale round the tap, from points a little north and east of it. Some + // projections round to whole pixels (ArcGIS's 3D SceneView): zoomed out, 1e-4° + // is under a pixel and both points land on the tap, so widen the step until + // they move far enough to measure. + var epsilon = 1e-4 + var pxPerDegLat: Double + var pxPerDegLon: Double + while (true) { + val north = project(GeoPoint(position.latitude + epsilon, position.longitude)) ?: return null + val east = project(GeoPoint(position.latitude, position.longitude + epsilon)) ?: return null + val dLat = hypot((north.x - touchScreen.x).toDouble(), (north.y - touchScreen.y).toDouble()) + val dLon = hypot((east.x - touchScreen.x).toDouble(), (east.y - touchScreen.y).toDouble()) + pxPerDegLat = dLat / epsilon + pxPerDegLon = dLon / epsilon + if ((dLat >= MIN_MEASURED_PX && dLon >= MIN_MEASURED_PX) || epsilon >= MAX_EPSILON_DEG) break + epsilon *= 10 + } + if (pxPerDegLat <= 0.0 || pxPerDegLon <= 0.0) return null + val radiusPx = SEARCH_RADIUS_DP * density + val halfLat = radiusPx / pxPerDegLat + val halfLon = radiusPx / pxPerDegLon + return GeoRectBounds( + southWest = GeoPoint((position.latitude - halfLat).coerceAtLeast(-90.0), position.longitude - halfLon), + northEast = GeoPoint((position.latitude + halfLat).coerceAtMost(90.0), position.longitude + halfLon), + ) + } + + /** + * [candidates] の中からタップ点に当たるマーカーを [pickIndex] の規則で選ぶ。 + */ + fun > pick( + touchScreen: Offset, + candidates: List, + project: (GeoPointInterface) -> Offset?, + defaultIcon: MarkerIconInterface = DefaultMarkerIcon(), + density: Double = ResourceProvider.getDensity().toDouble(), + ): E? = pickBy(touchScreen, candidates, { it.state }, project, defaultIcon, density) + + /** [pick] の、候補が [MarkerState] 以外の型で渡ってくる版。 */ + fun pickBy( + touchScreen: Offset, + candidates: List, + stateOf: (T) -> MarkerState, + project: (GeoPointInterface) -> Offset?, + defaultIcon: MarkerIconInterface = DefaultMarkerIcon(), + density: Double = ResourceProvider.getDensity().toDouble(), + ): T? { + val projected = ArrayList(candidates.size) + val rects = ArrayList(candidates.size) + for (candidate in candidates) { + val state = stateOf(candidate) + val anchorScreen = project(state.position) ?: continue + val icon = state.icon ?: defaultIcon + val iconSizePx = icon.iconSize.value.toDouble() * icon.scale.toDouble() * density + val extent = MarkerIconExtent.ratio(icon) + projected += candidate + rects += + ScreenRect( + anchorScreen = anchorScreen, + widthPx = iconSizePx * extent.width, + heightPx = iconSizePx * extent.height, + anchorX = icon.anchor.x.toDouble(), + anchorY = icon.anchor.y.toDouble(), + ) + } + val tolerancePx = Settings.Default.tapTolerance.value.toDouble() * density + return pickIndex(touchScreen, rects, tolerancePx)?.let { projected[it] } + } + + /** + * 候補を探す半径(dp)。ラベルの長さの上限の目安で、これより遠くまで伸びたラベルの端は拾えない。 + */ + const val SEARCH_RADIUS_DP: Double = 256.0 + + /** The scale is measured over at least this many pixels (see [searchBounds]). */ + private const val MIN_MEASURED_PX = 4.0 + + /** The widest step tried when measuring the scale: a 1° step covers any zoom that shows markers. */ + private const val MAX_EPSILON_DEG = 1.0 +} diff --git a/src/main/java/com/mapconductor/core/marker/MarkerHitTest.kt b/src/main/java/com/mapconductor/core/marker/MarkerHitTest.kt index 27c05b0..119e2ab 100644 --- a/src/main/java/com/mapconductor/core/marker/MarkerHitTest.kt +++ b/src/main/java/com/mapconductor/core/marker/MarkerHitTest.kt @@ -1,6 +1,7 @@ package com.mapconductor.core.marker import androidx.compose.ui.geometry.Offset +import com.mapconductor.core.InternalMapConductorApi import com.mapconductor.core.ResourceProvider import com.mapconductor.settings.Settings @@ -28,9 +29,10 @@ object MarkerHitTest { * アンカーは「アイコン内のどこがマーカー位置に一致するか」を 0..1 で表す。例えば * ピン形状の既定アンカー `(0.5, 1.0)` なら、矩形はアンカー点から上方向へ広がる。 * - * アイコンは正方形のキャンバスに描かれる前提で、`iconSize`(dp)× `scale` を - * 画面密度でピクセルへ換算して使う。 + * `iconSize`(dp)× `scale` を画面密度でピクセルへ換算し、既定アイコンでラベルの分だけ + * ビットマップが広いときは [MarkerIconExtent] の倍率を掛けて使う。 */ + @OptIn(InternalMapConductorApi::class) fun hitsIcon( touchScreen: Offset, markerScreen: Offset, @@ -40,12 +42,13 @@ object MarkerHitTest { ): Boolean { val icon = state.icon ?: defaultIcon val iconSizePx = icon.iconSize.value.toDouble() * icon.scale.toDouble() * density + val extent = MarkerIconExtent.ratio(icon) return hitsIconRect( dx = (touchScreen.x - markerScreen.x).toDouble(), dy = (touchScreen.y - markerScreen.y).toDouble(), - iconWidthPx = iconSizePx, - iconHeightPx = iconSizePx, + iconWidthPx = iconSizePx * extent.width, + iconHeightPx = iconSizePx * extent.height, anchorX = icon.anchor.x.toDouble(), anchorY = icon.anchor.y.toDouble(), tolerancePx = diff --git a/src/main/java/com/mapconductor/core/marker/MarkerIconExtent.kt b/src/main/java/com/mapconductor/core/marker/MarkerIconExtent.kt new file mode 100644 index 0000000..f0b9aeb --- /dev/null +++ b/src/main/java/com/mapconductor/core/marker/MarkerIconExtent.kt @@ -0,0 +1,24 @@ +package com.mapconductor.core.marker + +import androidx.compose.ui.geometry.Size +import com.mapconductor.core.InternalMapConductorApi + +/** + * アイコンが画面上で占める矩形が、ピン本体(iconSize × scale の正方形)の何倍か。 + * `anchor` / `infoAnchor` はこの矩形に対する割合なので、当たり判定と吹き出しはこれを掛けて使う。 + * + * 既定アイコンと画像アイコンはラベルの分だけビットマップが広いことがあるのでその倍率を返し、 + * それ以外のアイコンは従来どおり正方形(1 × 1)として扱う。 + * react-sdk の `markerIconExtentPx`、ios-sdk の `MarkerIconMetrics` に対応する。 + */ +@InternalMapConductorApi +object MarkerIconExtent { + private val SQUARE = Size(1f, 1f) + + fun ratio(icon: MarkerIconInterface): Size = + when (icon) { + is AbstractDefaultIcon -> icon.extentRatio + is ImageIcon -> icon.extentRatio + else -> SQUARE + } +} diff --git a/src/main/java/com/mapconductor/core/marker/MarkerIconRevision.kt b/src/main/java/com/mapconductor/core/marker/MarkerIconRevision.kt new file mode 100644 index 0000000..dab03a5 --- /dev/null +++ b/src/main/java/com/mapconductor/core/marker/MarkerIconRevision.kt @@ -0,0 +1,17 @@ +package com.mapconductor.core.marker + +import com.mapconductor.core.InternalMapConductorApi + +/** + * [MarkerState.icon] の URL の画像が届くたびに増える数。Compose から読むと、そのとき描き直される。 + * + * URL の画像が届いても、アイコンは同じインスタンスのまま `hashCode` だけが変わるので、 + * `marker.icon` を読んでいるだけのコンポジションは走り直さない。マーカーをコンポーズの + * オーバーレイとして描くプロバイダは、これも読んで `remember` のキーにする。 + * + * [MarkerState.icon] の読み出し自体は Compose の状態を増やさない。タイルの描画スレッドや + * コントローラが 14 万回読むので、そこへ余計な読み取りを足さないため。 + */ +@InternalMapConductorApi +val MarkerState.iconRevision: Int + get() = iconRevisionState.intValue diff --git a/src/main/java/com/mapconductor/core/marker/MarkerIngestionEngine.kt b/src/main/java/com/mapconductor/core/marker/MarkerIngestionEngine.kt index 8af66c2..40c0160 100644 --- a/src/main/java/com/mapconductor/core/marker/MarkerIngestionEngine.kt +++ b/src/main/java/com/mapconductor/core/marker/MarkerIngestionEngine.kt @@ -1,203 +1,222 @@ -package com.mapconductor.core.marker - -import android.os.SystemClock -import android.util.Log - -/** - * Shared ingestion logic for marker controllers. - * - * This engine diffs incoming [MarkerState] lists against the current [MarkerManager] state, - * drives the [MarkerOverlayRendererInterface], and updates the [MarkerManager]. - * - * SDK-specific controllers can inject: - * - how to decide "tiled vs native" via [shouldTile] - * - where to keep tiled IDs via [tiledMarkerIds] - * - * The tile overlay itself (RasterLayer state, cache busting, etc.) remains controller-specific. - */ -object MarkerIngestionEngine { - data class Result( - val tiledDataChanged: Boolean, - val hasTiledMarkers: Boolean, - ) - - suspend fun ingest( - data: List, - markerManager: MarkerManager, - renderer: MarkerOverlayRendererInterface, - defaultMarkerIcon: BitmapIcon, - tilingEnabled: Boolean, - tiledMarkerIds: MutableSet, - shouldTile: (MarkerState) -> Boolean, - ): Result { - val startedAt = SystemClock.elapsedRealtime() - markerTrace("ingest start count=${data.size} tilingEnabled=$tilingEnabled") - val previousIds = - markerManager - .allEntities() - .asSequence() - .map { it.state.id } - .toMutableSet() - - val added = mutableListOf() - val updated = mutableListOf>() - val removedActualMarkers = mutableListOf>() - var tiledDataChanged = false - - data.forEach { state -> - val wantsTiled = tilingEnabled && shouldTile(state) - - if (previousIds.contains(state.id)) { - val prevEntity = markerManager.getEntity(state.id)!! - val wasTiled = tiledMarkerIds.contains(state.id) - - if (wantsTiled) { - // A marker that was already tiled and hasn't actually changed (e.g. the same - // full list was resent on an unrelated recompose) doesn't need to re-register - // with the manager or bust the tile cache — that would force every visible - // tile to be redrawn for a no-op update. - val unchanged = wasTiled && prevEntity.fingerPrint == state.fingerPrint() - if (!unchanged) { - if (!wasTiled) { - prevEntity.marker?.let { removedActualMarkers.add(prevEntity) } - tiledMarkerIds.add(state.id) - } - markerManager.updateEntity( - MarkerEntity( - marker = null, - state = state, - visible = prevEntity.visible, - isRendered = true, - tiling = true, - ), - ) - tiledDataChanged = true - } - } else { - if (wasTiled) { - tiledMarkerIds.remove(state.id) - tiledDataChanged = true - } - val markerIcon = state.icon?.toBitmapIcon() ?: defaultMarkerIcon - updated.add( - object : MarkerOverlayRendererInterface.ChangeParamsInterface { - override val current: MarkerEntityInterface = - MarkerEntity( - state = state, - marker = prevEntity.marker, - visible = prevEntity.visible, - isRendered = true, - tiling = wasTiled, - ) - override val bitmapIcon: BitmapIcon = markerIcon - override val prev: MarkerEntityInterface = prevEntity - }, - ) - } - previousIds.remove(state.id) - } else { - if (wantsTiled) { - tiledMarkerIds.add(state.id) - markerManager.registerEntity( - MarkerEntity( - marker = null, - state = state, - visible = true, - isRendered = true, - tiling = true, - ), - ) - tiledDataChanged = true - } else { - val markerIcon = state.icon?.toBitmapIcon() ?: defaultMarkerIcon - added.add( - object : MarkerOverlayRendererInterface.AddParamsInterface { - override val state: MarkerState = state - override val bitmapIcon: BitmapIcon = markerIcon - }, - ) - } - } - } - - markerTrace( - "diff complete input=${data.size} add=${added.size} update=${updated.size} " + - "remove=${removedActualMarkers.size} tiled=${tiledMarkerIds.size} " + - "elapsedMs=${SystemClock.elapsedRealtime() - startedAt}", - ) - - // Remove stale entities from the manager (non-suspending, fine-grained locks inside) - previousIds.forEach { remainId -> - markerManager.removeEntity(remainId)?.let { removedEntity -> - if (tiledMarkerIds.remove(remainId)) { - tiledDataChanged = true - } else { - removedEntity.marker?.let { removedActualMarkers.add(removedEntity) } - } - } - } - - if (removedActualMarkers.isNotEmpty()) { - renderer.onRemove(removedActualMarkers) - } - - if (added.isNotEmpty()) { - markerTrace("renderer onAdd start count=${added.size}") - val actualMarkers = renderer.onAdd(added) - markerTrace("renderer onAdd end count=${added.size}") - actualMarkers.forEachIndexed { index, actualMarker -> - actualMarker ?: return@forEachIndexed - val state = added[index].state - val entity = - MarkerEntity( - marker = actualMarker, - state = state, - visible = true, - isRendered = true, - ) - markerManager.registerEntity(entity) - state.getAnimation()?.let { renderer.onAnimate(entity) } - } - } - - if (updated.isNotEmpty()) { - markerTrace("renderer onChange start count=${updated.size}") - val actualMarkers = renderer.onChange(updated) - markerTrace("renderer onChange end count=${updated.size}") - actualMarkers.forEachIndexed { index, actualMarker -> - val params = updated[index] - markerManager.updateEntity( - MarkerEntity( - marker = actualMarker ?: params.prev.marker, - state = params.current.state, - visible = params.current.visible, - isRendered = true, - ), - ) - - val prevFinger = params.prev.fingerPrint - val currentFinger = params.current.fingerPrint - if (prevFinger.animation != currentFinger.animation) { - params.current.state.getAnimation()?.let { - markerManager.getEntity(params.current.state.id)?.let { entity -> renderer.onAnimate(entity) } - } - } - } - } - - markerTrace("renderer postProcess start") - renderer.onPostProcess() - markerTrace( - "ingest end count=${data.size} elapsedMs=${SystemClock.elapsedRealtime() - startedAt}", - ) - return Result(tiledDataChanged = tiledDataChanged, hasTiledMarkers = tiledMarkerIds.isNotEmpty()) - } - - private fun markerTrace(message: String) { - Log.d( - "MCMarkerTrace", - "[CoreSDK][Ingestion][t=${SystemClock.elapsedRealtime()}]" + - "[thread=${Thread.currentThread().name}] $message", - ) - } -} +package com.mapconductor.core.marker + +import android.os.SystemClock +import android.util.Log + +/** + * Shared ingestion logic for marker controllers. + * + * This engine diffs incoming [MarkerState] lists against the current [MarkerManager] state, + * drives the [MarkerOverlayRendererInterface], and updates the [MarkerManager]. + * + * SDK-specific controllers can inject: + * - how to decide "tiled vs native" via [shouldTile] + * - where to keep tiled IDs via [tiledMarkerIds] + * + * The tile overlay itself (RasterLayer state, cache busting, etc.) remains controller-specific. + */ +object MarkerIngestionEngine { + data class Result( + val tiledDataChanged: Boolean, + val hasTiledMarkers: Boolean, + ) + + suspend fun ingest( + data: List, + markerManager: MarkerManager, + renderer: MarkerOverlayRendererInterface, + defaultMarkerIcon: BitmapIcon, + tilingEnabled: Boolean, + tiledMarkerIds: MutableSet, + shouldTile: (MarkerState) -> Boolean, + ): Result { + val startedAt = SystemClock.elapsedRealtime() + markerTrace("ingest start count=${data.size} tilingEnabled=$tilingEnabled") + val previousIds = + markerManager + .allEntities() + .asSequence() + .map { it.state.id } + .toMutableSet() + + val added = mutableListOf() + val updated = mutableListOf>() + val removedActualMarkers = mutableListOf>() + var tiledDataChanged = false + + data.forEach { state -> + val wantsTiled = tilingEnabled && shouldTile(state) + + if (previousIds.contains(state.id)) { + val prevEntity = markerManager.getEntity(state.id)!! + val wasTiled = tiledMarkerIds.contains(state.id) + + if (wantsTiled) { + // A marker that was already tiled and hasn't actually changed (e.g. the same + // full list was resent on an unrelated recompose) doesn't need to re-register + // with the manager or bust the tile cache — that would force every visible + // tile to be redrawn for a no-op update. + val unchanged = wasTiled && prevEntity.fingerPrint == state.fingerPrint() + if (unchanged) { + // Nothing to redraw — but the caller may have handed us a *new* + // MarkerState instance with the same look and newer handlers. The + // id is a hash of the look and does not include them, and a click + // is dispatched from the entity's state, so an entity left holding + // the previous instance keeps calling the previous onClick. + // js-sdk-core does the same thing here; ios-sdk re-registers + // unconditionally and never had the hole. + if (prevEntity.state !== state) { + markerManager.updateEntity( + MarkerEntity( + marker = prevEntity.marker, + state = state, + visible = prevEntity.visible, + isRendered = prevEntity.isRendered, + tiling = true, + ), + ) + } + } else { + if (!wasTiled) { + prevEntity.marker?.let { removedActualMarkers.add(prevEntity) } + tiledMarkerIds.add(state.id) + } + markerManager.updateEntity( + MarkerEntity( + marker = null, + state = state, + visible = prevEntity.visible, + isRendered = true, + tiling = true, + ), + ) + tiledDataChanged = true + } + } else { + if (wasTiled) { + tiledMarkerIds.remove(state.id) + tiledDataChanged = true + } + val markerIcon = state.icon?.toBitmapIcon() ?: defaultMarkerIcon + updated.add( + object : MarkerOverlayRendererInterface.ChangeParamsInterface { + override val current: MarkerEntityInterface = + MarkerEntity( + state = state, + marker = prevEntity.marker, + visible = prevEntity.visible, + isRendered = true, + tiling = wasTiled, + ) + override val bitmapIcon: BitmapIcon = markerIcon + override val prev: MarkerEntityInterface = prevEntity + }, + ) + } + previousIds.remove(state.id) + } else { + if (wantsTiled) { + tiledMarkerIds.add(state.id) + markerManager.registerEntity( + MarkerEntity( + marker = null, + state = state, + visible = true, + isRendered = true, + tiling = true, + ), + ) + tiledDataChanged = true + } else { + val markerIcon = state.icon?.toBitmapIcon() ?: defaultMarkerIcon + added.add( + object : MarkerOverlayRendererInterface.AddParamsInterface { + override val state: MarkerState = state + override val bitmapIcon: BitmapIcon = markerIcon + }, + ) + } + } + } + + markerTrace( + "diff complete input=${data.size} add=${added.size} update=${updated.size} " + + "remove=${removedActualMarkers.size} tiled=${tiledMarkerIds.size} " + + "elapsedMs=${SystemClock.elapsedRealtime() - startedAt}", + ) + + // Remove stale entities from the manager (non-suspending, fine-grained locks inside) + previousIds.forEach { remainId -> + markerManager.removeEntity(remainId)?.let { removedEntity -> + if (tiledMarkerIds.remove(remainId)) { + tiledDataChanged = true + } else { + removedEntity.marker?.let { removedActualMarkers.add(removedEntity) } + } + } + } + + if (removedActualMarkers.isNotEmpty()) { + renderer.onRemove(removedActualMarkers) + } + + if (added.isNotEmpty()) { + markerTrace("renderer onAdd start count=${added.size}") + val actualMarkers = renderer.onAdd(added) + markerTrace("renderer onAdd end count=${added.size}") + actualMarkers.forEachIndexed { index, actualMarker -> + actualMarker ?: return@forEachIndexed + val state = added[index].state + val entity = + MarkerEntity( + marker = actualMarker, + state = state, + visible = true, + isRendered = true, + ) + markerManager.registerEntity(entity) + state.getAnimation()?.let { renderer.onAnimate(entity) } + } + } + + if (updated.isNotEmpty()) { + markerTrace("renderer onChange start count=${updated.size}") + val actualMarkers = renderer.onChange(updated) + markerTrace("renderer onChange end count=${updated.size}") + actualMarkers.forEachIndexed { index, actualMarker -> + val params = updated[index] + markerManager.updateEntity( + MarkerEntity( + marker = actualMarker ?: params.prev.marker, + state = params.current.state, + visible = params.current.visible, + isRendered = true, + ), + ) + + val prevFinger = params.prev.fingerPrint + val currentFinger = params.current.fingerPrint + if (prevFinger.animation != currentFinger.animation) { + params.current.state.getAnimation()?.let { + markerManager.getEntity(params.current.state.id)?.let { entity -> renderer.onAnimate(entity) } + } + } + } + } + + markerTrace("renderer postProcess start") + renderer.onPostProcess() + markerTrace( + "ingest end count=${data.size} elapsedMs=${SystemClock.elapsedRealtime() - startedAt}", + ) + return Result(tiledDataChanged = tiledDataChanged, hasTiledMarkers = tiledMarkerIds.isNotEmpty()) + } + + private fun markerTrace(message: String) { + Log.d( + "MCMarkerTrace", + "[CoreSDK][Ingestion][t=${SystemClock.elapsedRealtime()}]" + + "[thread=${Thread.currentThread().name}] $message", + ) + } +} diff --git a/src/main/java/com/mapconductor/core/marker/MarkerManager.kt b/src/main/java/com/mapconductor/core/marker/MarkerManager.kt index bc5848d..5075864 100644 --- a/src/main/java/com/mapconductor/core/marker/MarkerManager.kt +++ b/src/main/java/com/mapconductor/core/marker/MarkerManager.kt @@ -1,283 +1,254 @@ -package com.mapconductor.core.marker - -import com.mapconductor.core.features.GeoPointInterface -import com.mapconductor.core.geocell.HexCell -import com.mapconductor.core.geocell.HexCellRegistry -import com.mapconductor.core.geocell.HexGeocell -import com.mapconductor.core.geocell.HexGeocellInterface -import com.mapconductor.core.projection.Earth -import com.mapconductor.core.spherical.Spherical -import java.util.concurrent.ConcurrentHashMap -import java.util.concurrent.locks.ReentrantReadWriteLock -import kotlin.concurrent.read -import kotlin.concurrent.write -import android.util.Log - -/** - * Memory usage statistics for MarkerManager optimization - */ -data class MarkerManagerStats( - val entityCount: Int, - val hasSpatialIndex: Boolean, - val spatialIndexInitialized: Boolean, - val estimatedMemoryKB: Long, -) - -open class MarkerManager( - protected val geocell: HexGeocellInterface, - val minMarkerCount: Int, -) { - // Primary storage - single source of truth - private val entities = ConcurrentHashMap>() - - // Lazy-initialized spatial index only when needed - @Volatile - private var cellRegistry: HexCellRegistry? = null - - private val semaphore = ReentrantReadWriteLock() - private var writeLock: ReentrantReadWriteLock.WriteLock? = null - - @Volatile - private var isDestroyed = false - - fun lock() { - if (writeLock != null) return - writeLock = - semaphore.writeLock().also { - it.lock() - } - } - - fun unlock() { - writeLock?.unlock() - writeLock = null - } - - open fun getEntity(id: String): MarkerEntityInterface? { - if (!usable("getEntity")) return null - return entities.get(id) - } - - open fun hasEntity(id: String): Boolean { - if (!usable("hasEntity")) return false - return entities.containsKey(id) - } - - open fun removeEntity(id: String): MarkerEntityInterface? { - if (!usable("removeEntity")) return null - val removed = entities.remove(id) - if (removed != null) { - // Only update spatial index if it exists - cellRegistry?.removePoint(removed) - } - return removed - } - - open fun metersPerPixel( - position: GeoPointInterface, - zoom: Double, - pixels: Double, - tileSize: Int = 256, - ): Double { - // 純粋な計算で内部状態を触らないため、破棄後でも警告だけ出して計算を続ける。 - usable("metersPerPixel") - // Optimized calculation without native reflection calls - val pixelsAtZoom = tileSize * Math.pow(2.0, zoom) - return Earth.CIRCUMFERENCE_METERS / pixelsAtZoom * Math.cos(Math.toRadians(position.latitude)) * pixels - } - - open fun findNearest(position: GeoPointInterface): MarkerEntityInterface? { - if (!usable("findNearest")) return null - - if (entities.size > minMarkerCount) { // Use spatial index for larger datasets - val registry = ensureCellRegistry() // must be called outside read lock to avoid write-lock upgrade deadlock - semaphore.read { - val nearestCell = registry.findNearest(position) - nearestCell?.let { cell -> - // Find the nearest entity within the nearest cell - return registry - .getEntryIDsByHexCell(cell) - ?.mapNotNull { id -> entities[id] } - ?.minByOrNull { entity -> - val deltaLatitude = entity.state.position.latitude - position.latitude - val deltaLongitude = entity.state.position.longitude - position.longitude - deltaLatitude * deltaLatitude + deltaLongitude * deltaLongitude - } - } - } - } - // Brute force search for small datasets - return bruteForceNearest(position) - } - - private fun bruteForceNearest(position: GeoPointInterface): MarkerEntityInterface? { - semaphore.read { - return entities.values.minByOrNull { entity -> - val dx = entity.state.position.latitude - position.latitude - val dy = entity.state.position.longitude - position.longitude - dx * dx + dy * dy - } - } - } - - open fun findByIdPrefix(prefix: String): List { - if (!usable("findByIdPrefix")) return emptyList() - semaphore.read { - return cellRegistry?.findByIdPrefix(prefix) ?: emptyList() - } - } - - open fun registerEntity(entity: MarkerEntityInterface) { - if (!usable("registerEntity")) return - semaphore.write { - entities[entity.state.id] = entity - // Only update spatial index if it exists - cellRegistry?.setPoint(entity) - } - } - - /** - * Lazy-initialize the spatial index only when spatial operations are needed. - * Double-checked locking: the registry is assigned only after it is fully populated, - * preventing concurrent callers from observing an empty non-null registry. - */ - private fun ensureCellRegistry(): HexCellRegistry { - cellRegistry?.let { return it } - return semaphore.write { - cellRegistry ?: run { - val registry = HexCellRegistry(geocell = geocell, zoom = 20.0) - entities.values.forEach { entity -> registry.setPoint(entity) } - cellRegistry = registry - registry - } - } - } - - open fun updateEntity(entity: MarkerEntityInterface) { - if (!usable("updateEntity")) return - semaphore.write { - entities[entity.state.id] = entity - // Only update spatial index if it exists - cellRegistry?.setPoint(entity) - } - } - - open fun allEntities(): List> { - if (!usable("allEntities")) return emptyList() - semaphore.read { - return entities.values.toList() - } - } - - /** - * Get memory usage statistics for debugging and optimization - */ - fun getMemoryStats(): MarkerManagerStats { - usable("getMemoryStats") - return MarkerManagerStats( - entityCount = entities.size, - hasSpatialIndex = cellRegistry != null, - spatialIndexInitialized = cellRegistry != null, - estimatedMemoryKB = estimateMemoryUsage() / 1024, - ) - } - - private fun estimateMemoryUsage(): Long { - // Rough estimation in bytes - val entityMapOverhead = entities.size * 64L // Map entry overhead + string key - val entityObjects = entities.size * 200L // Rough entity size - val spatialIndexSize = if (cellRegistry != null) entities.size * 100L else 0L // Cell registry overhead - return entityMapOverhead + entityObjects + spatialIndexSize - } - - open fun clear() { - if (!usable("clear")) return - entities.clear() - cellRegistry?.clear() - } - - fun findMarkersInBounds( - bounds: com.mapconductor.core.features.GeoRectBounds, - ): List> { - if (!usable("findMarkersInBounds")) return emptyList() - if (bounds.isEmpty) return emptyList() - - // For spatial queries, ensure the cell registry is initialized. - // `bounds.isEmpty` above already rules out a null corner, so the !! was - // safe — but it read as if it might not be, and `center` is a computed - // property that rebuilt the point on every access. Binding both up front - // states the precondition once and matches ios-sdk's `if count > n, - // let center = ..., let northEast = ...` shape. - val center = bounds.center - val northEast = bounds.northEast - // Only use spatial index for larger datasets. - if (entities.size > minMarkerCount && center != null && northEast != null) { - val registry = ensureCellRegistry() - semaphore.read { - val distance = Spherical.computeDistanceBetween(center, northEast) - val hexCells = registry.findWithinRadiusWithDistance(center, distance) - val entryIDs: List = - hexCells - .map { registry.getEntryIDsByHexCell(it.cell) } - .mapNotNull { it } - .flatMap { it.toList() } - return entryIDs.mapNotNull { getEntity(it) } - } - } - - // Brute force filtering - simple and efficient for small to medium datasets - return entities.values.filter { entity -> - bounds.contains(entity.state.position) - } - } - - /** - * Properly destroy resources when switching map providers - * IMPORTANT: Call this when disposing of the MarkerManager - */ - open fun destroy() { - if (!isDestroyed) { - semaphore.write { - isDestroyed = true - entities.clear() - cellRegistry?.clear() - cellRegistry = null - } - } - } - - /** - * 破棄後のアクセスかどうかを返す。破棄後なら警告ログを出して `false` を返す。 - * - * 以前は `IllegalStateException` を投げていたが、プロバイダ切り替えやビュー破棄の際に - * 実行中の非同期処理(Combine/Flow の配送や進行中のレンダラ往復)が destroy 直後に - * 到着するのは正常な競合であり、そこでクラッシュさせる理由がない。 - * destroy() は全状態をクリアするので、破棄後の操作は空状態への no-op で足りる。 - * ios-sdk / react-sdk と同じ「ログを出して無視する」セマンティクスに揃えた - * (react-sdk の `console.warn(... ignored)` と同じく、書き込み系も実行しない)。 - */ - private fun usable(operation: String): Boolean { - if (isDestroyed) { - Log.w(TAG, "MarkerManager.$operation called after destroy (ignored)") - return false - } - return true - } - - protected open fun finalize() { - destroy() - } - - companion object { - private const val TAG = "MapConductor" - - fun defaultManager( - geocell: HexGeocellInterface? = null, - minMarkerCount: Int = 2000, - ): MarkerManager = - MarkerManager( - geocell = geocell ?: HexGeocell.defaultGeocell(), - minMarkerCount = minMarkerCount, - ) - } -} +package com.mapconductor.core.marker + +import com.mapconductor.core.features.GeoPointInterface +import com.mapconductor.core.geocell.HexGeocell +import com.mapconductor.core.geocell.HexGeocellInterface +import com.mapconductor.core.projection.Earth +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.locks.ReentrantReadWriteLock +import kotlin.concurrent.read +import kotlin.concurrent.write +import android.util.Log + +/** + * Memory usage statistics for MarkerManager optimization + */ +data class MarkerManagerStats( + val entityCount: Int, + val hasSpatialIndex: Boolean, + val spatialIndexInitialized: Boolean, + val estimatedMemoryKB: Long, +) + +open class MarkerManager( + protected val geocell: HexGeocellInterface, + val minMarkerCount: Int, +) { + // Primary storage - single source of truth + private val entities = ConcurrentHashMap>() + + /** + * The spatial index the per-tile paths use. A uniform lat/lng grid rather + * than hex cells; see [MarkerGridIndex] for why. + */ + private val gridIndex = MarkerGridIndex { entities.values } + + private val semaphore = ReentrantReadWriteLock() + private var writeLock: ReentrantReadWriteLock.WriteLock? = null + + @Volatile + private var isDestroyed = false + + fun lock() { + if (writeLock != null) return + writeLock = + semaphore.writeLock().also { + it.lock() + } + } + + fun unlock() { + writeLock?.unlock() + writeLock = null + } + + open fun getEntity(id: String): MarkerEntityInterface? { + if (!usable("getEntity")) return null + return entities.get(id) + } + + open fun hasEntity(id: String): Boolean { + if (!usable("hasEntity")) return false + return entities.containsKey(id) + } + + open fun removeEntity(id: String): MarkerEntityInterface? { + if (!usable("removeEntity")) return null + val removed = entities.remove(id) + if (removed != null) { + gridIndex.remove(removed) + } + return removed + } + + open fun metersPerPixel( + position: GeoPointInterface, + zoom: Double, + pixels: Double, + tileSize: Int = 256, + ): Double { + // 純粋な計算で内部状態を触らないため、破棄後でも警告だけ出して計算を続ける。 + usable("metersPerPixel") + // Optimized calculation without native reflection calls + val pixelsAtZoom = tileSize * Math.pow(2.0, zoom) + return Earth.CIRCUMFERENCE_METERS / pixelsAtZoom * Math.cos(Math.toRadians(position.latitude)) * pixels + } + + open fun findNearest(position: GeoPointInterface): MarkerEntityInterface? { + if (!usable("findNearest")) return null + + if (entities.size > minMarkerCount) { + semaphore.read { return gridIndex.nearest(position) } + } + // Below the threshold the grid cannot narrow anything down worth the + // rings, so scan. + return bruteForceNearest(position) + } + + private fun bruteForceNearest(position: GeoPointInterface): MarkerEntityInterface? { + semaphore.read { + return entities.values.minByOrNull { entity -> + val dx = entity.state.position.latitude - position.latitude + val dy = entity.state.position.longitude - position.longitude + dx * dx + dy * dy + } + } + } + + open fun registerEntity(entity: MarkerEntityInterface) { + if (!usable("registerEntity")) return + semaphore.write { + file(entities.put(entity.state.id, entity), entity) + } + } + + open fun updateEntity(entity: MarkerEntityInterface) { + if (!usable("updateEntity")) return + semaphore.write { + // A marker that moved changes which cell it belongs to. + file(entities.put(entity.state.id, entity), entity) + } + } + + /** Tells the index that [entity] took the place of [previous], if there was one. */ + private fun file( + previous: MarkerEntityInterface?, + entity: MarkerEntityInterface, + ) { + if (previous == null) gridIndex.add(entity) else gridIndex.replace(previous, entity) + } + + open fun allEntities(): List> { + if (!usable("allEntities")) return emptyList() + semaphore.read { + return entities.values.toList() + } + } + + /** + * Markers in [bounds], where the caller is going to drop anything closer + * together than [minSeparationDegrees] regardless. + * + * The index can then answer from its cells rather than from its markers, + * which is the difference between visiting 141,221 street trees and + * visiting the 5,000 cells that hold them. It falls back to the full query + * whenever it cannot honour the separation, so the caller still has to + * apply its own rule to the result — this only promises not to return + * markers it was told are interchangeable. + */ + fun findMarkersInBounds( + bounds: com.mapconductor.core.features.GeoRectBounds, + minSeparationDegrees: Double, + ): List> { + if (!usable("findMarkersInBounds")) return emptyList() + if (bounds.isEmpty) return emptyList() + if (entities.size > minMarkerCount) { + semaphore.read { + gridIndex.inBoundsThinned(bounds, minSeparationDegrees)?.let { return it } + } + } + return findMarkersInBounds(bounds) + } + + /** + * Get memory usage statistics for debugging and optimization + */ + fun getMemoryStats(): MarkerManagerStats { + usable("getMemoryStats") + return MarkerManagerStats( + entityCount = entities.size, + hasSpatialIndex = true, + spatialIndexInitialized = gridIndex.isBuilt, + estimatedMemoryKB = estimateMemoryUsage() / 1024, + ) + } + + private fun estimateMemoryUsage(): Long { + // Rough estimation in bytes + val entityMapOverhead = entities.size * 64L // Map entry overhead + string key + val entityObjects = entities.size * 200L // Rough entity size + val spatialIndexSize = gridIndex.estimatedBytes() + return entityMapOverhead + entityObjects + spatialIndexSize + } + + open fun clear() { + if (!usable("clear")) return + entities.clear() + gridIndex.invalidate() + } + + fun findMarkersInBounds( + bounds: com.mapconductor.core.features.GeoRectBounds, + ): List> { + if (!usable("findMarkersInBounds")) return emptyList() + if (bounds.isEmpty) return emptyList() + + // Only use the spatial index for larger datasets. + if (entities.size > minMarkerCount) { + semaphore.read { return gridIndex.inBounds(bounds) } + } + + // Brute force filtering - simple and efficient for small to medium datasets + return entities.values.filter { entity -> + bounds.contains(entity.state.position) + } + } + + /** + * Properly destroy resources when switching map providers + * IMPORTANT: Call this when disposing of the MarkerManager + */ + open fun destroy() { + if (!isDestroyed) { + semaphore.write { + isDestroyed = true + entities.clear() + } + } + } + + /** + * 破棄後のアクセスかどうかを返す。破棄後なら警告ログを出して `false` を返す。 + * + * 以前は `IllegalStateException` を投げていたが、プロバイダ切り替えやビュー破棄の際に + * 実行中の非同期処理(Combine/Flow の配送や進行中のレンダラ往復)が destroy 直後に + * 到着するのは正常な競合であり、そこでクラッシュさせる理由がない。 + * destroy() は全状態をクリアするので、破棄後の操作は空状態への no-op で足りる。 + * ios-sdk / react-sdk と同じ「ログを出して無視する」セマンティクスに揃えた + * (react-sdk の `console.warn(... ignored)` と同じく、書き込み系も実行しない)。 + */ + private fun usable(operation: String): Boolean { + if (isDestroyed) { + Log.w(TAG, "MarkerManager.$operation called after destroy (ignored)") + return false + } + return true + } + + protected open fun finalize() { + destroy() + } + + companion object { + private const val TAG = "MapConductor" + + fun defaultManager( + geocell: HexGeocellInterface? = null, + minMarkerCount: Int = 2000, + ): MarkerManager = + MarkerManager( + geocell = geocell ?: HexGeocell.defaultGeocell(), + minMarkerCount = minMarkerCount, + ) + } +} diff --git a/src/main/java/com/mapconductor/core/marker/MarkerOverlay.kt b/src/main/java/com/mapconductor/core/marker/MarkerOverlay.kt index a9c3261..1e75ecf 100644 --- a/src/main/java/com/mapconductor/core/marker/MarkerOverlay.kt +++ b/src/main/java/com/mapconductor/core/marker/MarkerOverlay.kt @@ -1,5 +1,6 @@ package com.mapconductor.core.marker +import com.mapconductor.core.OverlayAddedTracker import com.mapconductor.core.controller.MapViewControllerInterface import com.mapconductor.core.map.MapOverlayInterface import kotlinx.coroutines.flow.StateFlow @@ -7,12 +8,16 @@ import kotlinx.coroutines.flow.StateFlow class MarkerOverlay( override val flow: StateFlow>, ) : MapOverlayInterface { + /** Calls [MarkerState.onAdded] once the map has the state. See [OverlayAddedTracker]. */ + private val added = OverlayAddedTracker { it.onAdded } + override suspend fun render( data: MutableMap, controller: MapViewControllerInterface, ) { - (controller as? MarkerCapableInterface)?.let { markerController -> - markerController.compositionMarkers(data.values.toList()) - } + val capable = controller as? MarkerCapableInterface ?: return + val states = data.values.toList() + capable.compositionMarkers(states) + added.synced(controller, states, capable::hasMarker) } } diff --git a/src/main/java/com/mapconductor/core/marker/MarkerOverlayRendererInterface.kt b/src/main/java/com/mapconductor/core/marker/MarkerOverlayRendererInterface.kt index a4701dc..d74e387 100644 --- a/src/main/java/com/mapconductor/core/marker/MarkerOverlayRendererInterface.kt +++ b/src/main/java/com/mapconductor/core/marker/MarkerOverlayRendererInterface.kt @@ -51,4 +51,16 @@ interface MarkerOverlayRendererInterface { * ドラッグ層を持つプロバイダがここで層を描き直す。 */ fun onDragPositionChanged(position: GeoPointInterface) = Unit + + /** + * 地図が回って、同じ zIndex のマーカーを並べる向きが変わった。 + * + * [frame] を覚えておき、以後のマーカーも [MarkerDrawOrder] にこれを渡して並べる。 + * [entities] は今ある全マーカー。ネイティブの描く順を付け直す。**既定は何もしない** + * (北が上の順のまま)。 + */ + suspend fun onDrawOrderFrameChanged( + frame: MarkerDrawOrder.Frame, + entities: List>, + ) = Unit } diff --git a/src/main/java/com/mapconductor/core/marker/MarkerTileLabel.kt b/src/main/java/com/mapconductor/core/marker/MarkerTileLabel.kt new file mode 100644 index 0000000..1d97f19 --- /dev/null +++ b/src/main/java/com/mapconductor/core/marker/MarkerTileLabel.kt @@ -0,0 +1,372 @@ +package com.mapconductor.core.marker + +import androidx.compose.ui.unit.TextUnit +import androidx.compose.ui.unit.TextUnitType +import com.mapconductor.core.InternalMapConductorApi +import com.mapconductor.core.ResourceProvider +import java.text.BreakIterator +import kotlin.math.ceil +import kotlin.math.max +import kotlin.math.min +import kotlin.math.roundToInt +import android.graphics.Canvas +import android.graphics.Paint +import android.graphics.Typeface + +/** + * タイルに描くとき、アイコン本体とは別に描くラベル。 + * + * ## なぜ分けるか + * + * ラベルを焼き込んだビットマップは、文字列と置き場所の組の数だけ要る。 + * 街路樹のように「樹種 × 向き」でラベルを付け替えると、そのたびに画像を作ることになる。 + * 本体(点やピン)だけを焼き込み、文字はタイルを描くときに直接描けば、画像は本体の種類だけで済む。 + * + * ネイティブマーカーとして描くときは、従来どおり焼き込んだビットマップ(`toBitmapIcon()`)を使う。 + * どちらも配置は [IconLabelLayout] の同じ計算から出す。ios-sdk の `MarkerTileLabel` と同じ。 + * + * 長さはすべてアイコンのビットマップの px(`BitmapIcon.size` と同じ単位)。タイルではさらに描画倍率を掛ける。 + */ +@InternalMapConductorApi +internal class MarkerTileLabel( + val text: String, + val textSizePx: Float, + val typeface: Typeface, + val textColor: Int, + val strokeColor: Int, + val outlinePx: Float, + /** ラベルの中心の、アンカー点からのずれ。 */ + val centerOffsetX: Float, + val centerOffsetY: Float, + /** 縁取り込みの大きさ。 */ + val width: Float, + val height: Float, + val vertical: Boolean, +) { + /** + * アンカー点 ([anchorX], [anchorY]) を基準に、[scale] 倍で描く。 + * + * 書き出し位置は整数の画素に揃える。タイルの原点も整数の画素なので、 + * 境界をまたぐラベルは両側のタイルが同じ画素から描き、継ぎ目で字が割れない。 + */ + fun draw( + canvas: Canvas, + anchorX: Float, + anchorY: Float, + scale: Float, + ) { + LabelTypesetter.draw( + canvas = canvas, + text = text, + centerX = anchorX + centerOffsetX * scale, + centerY = anchorY + centerOffsetY * scale, + textSizePx = textSizePx * scale, + typeface = typeface, + textColor = textColor, + strokeColor = strokeColor, + outlinePx = outlinePx * scale, + vertical = vertical, + alignToPixel = true, + ) + } +} + +/** + * 本体とラベルを分けて渡せるアイコンなら、その 2 つ。それ以外は null。 + * + * タイル描画は本体を描き、ラベルをタイルに直接描く。どちらも焼き込みのビットマップを作らずに + * 得られるので、ラベル付きのアイコンを大量に作っても、ネイティブマーカーとして描かれない限り + * 画像は増えない。型で振り分けるのは [MarkerIconExtent] と同じで、アプリ向けの公開 API に + * 実装点を出さないため。 + */ +@InternalMapConductorApi +internal fun MarkerIconInterface.tileParts(): Pair? = + when (this) { + is AbstractDefaultIcon -> tileBody to tileLabel + is ImageIcon -> tileBody to tileLabel + else -> null + } + +/** + * ラベル付きのアイコンのはみ出し量(アンカーからいちばん遠い辺まで、ビットマップの px)の、 + * プロセス全体での最大。 + * + * ラベル付きのアイコンは作った時点で配置を計算するので、ここへ記録する。タイル描画は、 + * 隣のタイルからはみ出してくるラベルを取りこぼさないよう、この値で探す範囲を広げる + * ([MarkerTileRenderer])。マーカーに付ける前にアイコンは作られるので、タイルが描き直される + * 時点ではもう記録されている。 + * + * 小さくはならない。大きなラベルを一度作ると、以後は少し広めに探す。ios-sdk と同じ。 + */ +@InternalMapConductorApi +internal object LabelledIconExtent { + @Volatile + var maxPx: Double = 0.0 + private set + + fun note( + width: Float, + height: Float, + anchorX: Float, + anchorY: Float, + ) { + val extent = + maxOf( + max(width * anchorX, width * (1f - anchorX)), + max(height * anchorY, height * (1f - anchorY)), + ).toDouble() + synchronized(this) { + if (extent > maxPx) maxPx = extent + } + } +} + +/** + * ラベルの文字の測り方と描き方。焼き込み([AbstractDefaultIcon] / [ImageIcon])とタイル + * ([MarkerTileLabel])の両方がここを通るので、どちらで描いても同じ字面になる。 + * + * ## 縦書き + * + * `labelWritingMode` は CSS の `writing-mode` と同じ書き方で、`vertical-rl` / `vertical-lr` を + * 縦書きとして扱う(1 行しかないので左右の違いは出ない)。それ以外は横書き。 + * + * Canvas には縦組みの機能が無いので、OpenType の縦書き用字形(`vert`)を有効にして、 + * 1 文字ずつ 1em の升に積む。長音の「ー」は縦棒に、小書きの「ョ」は縦書きの位置になる + * (ios-sdk は CoreText の縦組みで同じ字面を出す)。横の通りに沿って並ぶ街路樹のように、 + * 横書きでは幅を取りすぎて並ばないラベルに使う。 + */ +@InternalMapConductorApi +internal object LabelTypesetter { + const val HORIZONTAL: String = "horizontal-tb" + + /** ラベルの文字の大きさ(px)。sp と em は文字の拡大設定に従い、それ以外は dp として読む。 */ + fun textSizePx(textUnit: TextUnit): Float = + when (textUnit.type) { + TextUnitType.Sp -> ResourceProvider.spToPx(textUnit.value.toDouble()).toFloat() + TextUnitType.Em -> ResourceProvider.spToPx(16.0 * textUnit.value).toFloat() + else -> ResourceProvider.dpToPx(textUnit.value.toDouble()).toFloat() + } + + /** 縁取りの太さ(アイコンの拡大率を考慮、最小 2px)。 */ + fun outlinePx(iconScale: Float): Float = max(ResourceProvider.dpToPxForBitmap(1f * iconScale).toFloat(), 2f) + + fun isVertical(writingMode: String): Boolean { + val mode = writingMode.trim().lowercase() + return mode == "vertical-rl" || mode == "vertical-lr" + } + + /** + * 縁取り込みの大きさ。[contentWidth] は縁取りを除いた字面の幅(横書きは文字列の幅、 + * 縦書きは列の幅)で、ラベルをピンに重ねるときのビットマップの幅に使う。 + */ + @InternalMapConductorApi + class Metrics( + val width: Float, + val height: Float, + val contentWidth: Float, + ) + + fun measure( + text: String, + textSizePx: Float, + typeface: Typeface, + outlinePx: Float, + vertical: Boolean, + ): Metrics { + val paint = textPaint(textSizePx, typeface, 0, vertical) + if (!vertical) { + val width = paint.measureText(text) + val fm = paint.fontMetrics + return Metrics(width + outlinePx * 2f, fm.descent - fm.ascent + outlinePx * 2f, width) + } + val glyphs = graphemes(text) + var column = 0f + for (glyph in glyphs) column = max(column, paint.measureText(glyph)) + column = ceil(max(column, textSizePx * VERTICAL_COLUMN_MIN_EM)) + return Metrics(column + outlinePx * 2f, glyphs.size * textSizePx + outlinePx * 2f, column) + } + + /** 中心 ([centerX], [centerY]) に描く。縁取りを先に、塗りを後に重ねる。 */ + fun draw( + canvas: Canvas, + text: String, + centerX: Float, + centerY: Float, + textSizePx: Float, + typeface: Typeface, + textColor: Int, + strokeColor: Int, + outlinePx: Float, + vertical: Boolean, + alignToPixel: Boolean, + ) { + val fill = textPaint(textSizePx, typeface, textColor, vertical) + val outline = + Paint(fill).apply { + style = Paint.Style.STROKE + strokeWidth = outlinePx + color = strokeColor + strokeJoin = Paint.Join.ROUND + strokeCap = Paint.Cap.ROUND + } + val fm = fill.fontMetrics + + fun align(value: Float): Float = if (alignToPixel) value.roundToInt().toFloat() else value + + if (!vertical) { + val width = fill.measureText(text) + val baseline = align(centerY + (fm.descent - fm.ascent) / 2f - fm.descent) + // 中央揃えで描くので、左端を画素に揃えてから中央へ戻す。 + val x = align(centerX - width / 2f) + width / 2f + canvas.drawText(text, x, baseline, outline) + canvas.drawText(text, x, baseline, fill) + return + } + + val glyphs = graphemes(text) + val em = textSizePx + val x = align(centerX) + val top = align(centerY - glyphs.size * em / 2f) + // 1em の升の中央に字面の中央が来るベースライン。 + val baselineInCell = em / 2f - (fm.ascent + fm.descent) / 2f + for ((index, glyph) in glyphs.withIndex()) { + val baseline = top + index * em + baselineInCell + canvas.drawText(glyph, x, baseline, outline) + canvas.drawText(glyph, x, baseline, fill) + } + } + + private fun textPaint( + textSizePx: Float, + typeface: Typeface, + color: Int, + vertical: Boolean, + ): Paint = + Paint().apply { + this.color = color + this.textSize = textSizePx + textAlign = Paint.Align.CENTER + this.typeface = typeface + isAntiAlias = true + isSubpixelText = true + if (vertical) fontFeatureSettings = "'vert' 1" + } + + /** 書記素(見た目の 1 文字)ごとに分ける。結合文字やサロゲートペアを割らない。 */ + private fun graphemes(text: String): List { + val iterator = BreakIterator.getCharacterInstance() + iterator.setText(text) + val result = ArrayList(text.length) + var start = iterator.first() + var end = iterator.next() + while (end != BreakIterator.DONE) { + result.add(text.substring(start, end)) + start = end + end = iterator.next() + } + return result + } + + /** 縦書きの列の幅の下限(em)。細い字だけの列でも、隣の列や点と間を空ける。 */ + private const val VERTICAL_COLUMN_MIN_EM = 1f +} + +/** + * アイコンのビットマップの中での、本体とラベルの配置。すべて px。 + * + * 既定のピンと画像アイコンで共通の計算。react-sdk の `computeIconLabelLayout`、 + * ios-sdk の `DefaultIconLayout` と同じ。 + */ +@InternalMapConductorApi +internal object IconLabelLayout { + @InternalMapConductorApi + class Result( + val bitmapWidth: Int, + val bitmapHeight: Int, + val markerOffsetX: Float, + val markerOffsetY: Float, + val labelCenterX: Float, + val labelCenterY: Float, + ) + + /** + * @param markerSize 本体の正方形の一辺。 + * @param bodyLeft 〜 [bodyBottom] ラベルを避けて置く、本体の描かれている範囲(本体の左上が原点)。 + * @param centerY `center center` のときのラベルの縦位置。 + * @param sideCenterY 左右に置き、縦を指定しないときのラベルの縦位置。 + * @param label ラベルの寸法。無ければ本体だけ。 + */ + fun compute( + markerSize: Int, + bodyLeft: Float, + bodyRight: Float, + bodyTop: Float, + bodyBottom: Float, + centerY: Float, + sideCenterY: Float, + label: LabelTypesetter.Metrics?, + outlinePx: Float, + labelPosition: String, + ): Result { + val size = markerSize.toFloat() + if (label == null) { + return Result(markerSize, markerSize, 0f, 0f, size / 2f, centerY) + } + val padding = size * 0.1f // 左右に5%ずつの余白 + val labelWidth = label.width + val labelHeight = label.height + val (h, v) = AbstractDefaultIcon.parseLabelPosition(labelPosition) + val gap = max(outlinePx, size * 0.05f) + + // 本体の左上を原点とした座標でラベルの中心を決める。 + val cx = + when { + h < 0 -> bodyLeft - gap - labelWidth / 2f + h > 0 -> bodyRight + gap + labelWidth / 2f + else -> size / 2f + } + val cy = + if (h != 0) { + // 横に置くときは、縦は本体の上端・指定の中心・下端に揃える。 + when { + v < 0 -> bodyTop + labelHeight / 2f + v > 0 -> bodyBottom - labelHeight / 2f + else -> sideCenterY + } + } else { + // 中央列の top / bottom は本体と重ならないよう上下の外側に置く。 + when { + v < 0 -> bodyTop - gap - labelHeight / 2f + v > 0 -> bodyBottom + gap + labelHeight / 2f + else -> centerY + } + } + + val bitmapWidth: Int + val markerOffsetX: Float + if (h == 0) { + // 中央なら従来どおり(出力を変えない)。 + bitmapWidth = max(size, label.contentWidth + padding).toInt() + markerOffsetX = (bitmapWidth - markerSize) / 2f + } else { + val minX = min(0f, cx - labelWidth / 2f - padding / 2f) + val maxX = max(size, cx + labelWidth / 2f + padding / 2f) + bitmapWidth = ceil(maxX - minX).toInt() + markerOffsetX = -minX + } + + val minY = min(0f, cy - labelHeight / 2f) + val maxY = max(size, cy + labelHeight / 2f) + val markerOffsetY = ceil(-minY) + val bitmapHeight = (markerOffsetY + ceil(maxY)).toInt() + + return Result( + bitmapWidth = bitmapWidth, + bitmapHeight = bitmapHeight, + markerOffsetX = markerOffsetX, + markerOffsetY = markerOffsetY, + labelCenterX = markerOffsetX + cx, + labelCenterY = markerOffsetY + cy, + ) + } +} diff --git a/src/main/java/com/mapconductor/core/marker/MarkerTileRenderer.kt b/src/main/java/com/mapconductor/core/marker/MarkerTileRenderer.kt index 5074bb8..d03abd0 100644 --- a/src/main/java/com/mapconductor/core/marker/MarkerTileRenderer.kt +++ b/src/main/java/com/mapconductor/core/marker/MarkerTileRenderer.kt @@ -6,6 +6,8 @@ import androidx.core.graphics.createBitmap import com.mapconductor.core.ResourceProvider import com.mapconductor.core.features.GeoPoint import com.mapconductor.core.features.GeoRectBounds +import com.mapconductor.core.tileserver.ScratchPool +import com.mapconductor.core.tileserver.TilePngEncoder import com.mapconductor.core.tileserver.TileProviderInterface import com.mapconductor.core.tileserver.TileRequest import java.io.ByteArrayOutputStream @@ -24,7 +26,6 @@ import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.graphics.Rect -import android.graphics.RectF import android.util.LruCache data class PointD( @@ -54,10 +55,31 @@ class MarkerTileRenderer( private val debugTileOverlay: Boolean = false, private val iconScaleCallback: ((MarkerState, Int) -> Double)? = null, val extraIconScale: Double = 1.0, + /** See [MarkerTilingOptions.declutterPx]. Zero draws every marker. */ + private val declutterPx: Int = 0, + /** + * カメラのズームを四捨五入したズーム。null なら頼まれたタイルのズームのまま描く。 + * + * 地図 SDK がどのズームのタイルを出すかは SDK ごとに違う。MapLibre 系・Mapbox・HERE・ + * ArcGIS はカメラのズームを四捨五入したズームのタイルを出すが、Google Maps と + * OpenMobileMaps は切り捨てたズームのタイルを出す。ズーム 17.75 なら前者は z18 を + * 0.84 倍、後者は z17 を 1.68 倍に伸ばして出すので、同じ大きさで描いたマーカーと + * ラベルが 2 倍違って見える(Pixel 5a で実測)。 + * + * これを渡すと、ほかのズームのタイルを頼まれても、四捨五入したズームのタイルと同じ + * 大きさに見えるように描く。切り捨てる SDK で z17 を頼まれたときカメラが 17.75 なら、 + * z18 で描く大きさの半分で描く。値が変わったらタイルの描き直しが要る + * (内側の描き置きはここで捨てるが、地図 SDK の側のキャッシュは呼び出し側が捨てる)。 + */ + private val displayTileZoom: (() -> Int?)? = null, ) : TileProviderInterface { @Volatile private var cacheVersion: Int = 0 + /** 前のタイルを描いたときの [displayTileZoom]。変わったら描き置きを捨てる。 */ + @Volatile + private var lastDisplayZoom: Int? = null + private val tileCache: LruCache = object : LruCache(cacheSizeBytes) { override fun sizeOf( @@ -159,6 +181,79 @@ class MarkerTileRenderer( private val defaultIcon = DefaultMarkerIcon() + /** + * Largest icon half-extent any tile has needed so far, in px. + * + * Seeds the padding used to widen a tile's marker query. Starts from the + * default icon's own extent rather than a guess: the guess was 32dp, real + * icons are larger, and every tile therefore paid a second query and a + * second prepare. + * + * Volatile rather than synchronised: renderTile runs concurrently, and a + * torn read costs at most one extra pass on one tile, which is what the + * field exists to avoid in the first place. + */ + @Volatile + private var observedHalfExtentPx: Double = + defaultIcon.toBitmapIcon().let { icon -> + val width = icon.size.width.toDouble() * extraIconScale + val height = icon.size.height.toDouble() * extraIconScale + val anchorX = icon.anchor.x.toDouble() + val anchorY = icon.anchor.y.toDouble() + maxOf( + max(kotlin.math.abs(width * anchorX), kotlin.math.abs(width * (1.0 - anchorX))), + max(kotlin.math.abs(height * anchorY), kotlin.math.abs(height * (1.0 - anchorY))), + ) + } + + /** + * ズームごとの、アイコンに掛かった倍率の最大(`iconScaleCallback` × [extraIconScale])。 + * [LabelledIconExtent] の px(アイコンのビットマップの px)をタイルの px へ直すのに使う。 + */ + private val maxScaleByZoom = HashMap() + + /** + * 倍率をまだ見ていないズームで `iconScaleCallback` に渡す見本。どこかのズームで描いた + * マーカーを 1 つ覚えておく。一斉に描き直すとき、そのズームの最初のタイルたちは + * 倍率を誰も記録していないので、これが無いと育っていない値で探すことになる。 + */ + private var sampleState: MarkerState? = null + + /** + * 探す範囲に使う、はみ出し量(px)。 + * + * [observedHalfExtentPx] は「これまでに描いたタイルで見た最大」なので、ラベルを付けた + * 直後に全タイルが一斉に描き直されると、まだ育っていない値で探すタイルが出る。 + * そのタイルに自分のマーカーが無ければ空として返し、2 回目の探索もしないので、 + * 隣から**はみ出してくるラベルが境目で切れる**。ラベル付きのアイコンは作った時点で + * はみ出し量を [LabelledIconExtent] に記録しているので、それも使う。 + * 全マーカーを数え直す方法は、14.4 万本で 1 回あたり秒単位になるので採らない(ios-sdk で実測)。 + */ + private fun queryHalfExtentPx( + zoom: Int, + contentScale: Double, + ): Double { + val scale: Double? = + synchronized(maxScaleByZoom) { + maxScaleByZoom[zoom] ?: sampleState?.let { sample -> + (iconScaleCallback?.invoke(sample, zoom) ?: 1.0).coerceAtLeast(0.0) * extraIconScale + } + } + if (scale == null) return observedHalfExtentPx + return max(observedHalfExtentPx, LabelledIconExtent.maxPx * scale * contentScale) + } + + private fun noteScale( + scale: Double, + zoom: Int, + state: MarkerState, + ) { + synchronized(maxScaleByZoom) { + if (scale > (maxScaleByZoom[zoom] ?: 0.0)) maxScaleByZoom[zoom] = scale + if (sampleState == null) sampleState = state + } + } + override fun renderTile(request: TileRequest): ByteArray? { val zoomInt = request.z val worldTileCount = 1 shl zoomInt @@ -166,6 +261,19 @@ class MarkerTileRenderer( val normalizedX = normalizeTileX(request.x, worldTileCount) val tileYInt = request.y + // [displayTileZoom] のズームのタイルと同じ大きさに見せる。地図はこのタイルを + // 2^(カメラ - zoomInt) 倍で出すので、中身を 2^(zoomInt - displayZoom) 倍で描けば、 + // 見た目は 2^(カメラ - displayZoom) 倍になり、四捨五入する SDK と揃う。 + // アイコンの倍率もそのズームで問い合わせる。 + val displayZoom = displayTileZoom?.invoke() + if (displayZoom != lastDisplayZoom) { + lastDisplayZoom = displayZoom + invalidate() + } + val scaleZoom = displayZoom ?: zoomInt + val contentScale = 2.0.pow(zoomInt - scaleZoom) + val declutterCellPx = declutterPx * contentScale + val cacheVersionSnapshot = cacheVersion val cacheKey = tileCacheKey( @@ -204,6 +312,9 @@ class MarkerTileRenderer( val drawW: Float, val drawH: Float, val anchor: Offset, + /** 本体とは別に、本体をすべて描いたあとで描く文字。 */ + val label: MarkerTileLabel?, + val scale: Float, ) fun prepareMarkers(entities: List>): Pair, Double> { @@ -211,7 +322,11 @@ class MarkerTileRenderer( val prepared = ArrayList(entities.size) for (entity in entities) { val stateIcon = entity.state.icon - val icon = stateIcon?.toBitmapIcon() ?: defaultIcon.toBitmapIcon() + // 本体とラベルを分けて渡せるアイコンは、ラベルを焼き込んだ画像を作らせない。 + // 本体だけを焼き込み、文字はタイルに直接描く([MarkerTileLabel])。 + val parts = stateIcon?.tileParts() + val icon = parts?.first ?: stateIcon?.toBitmapIcon() ?: defaultIcon.toBitmapIcon() + val label = parts?.second val pos = entity.state.position val tilePoint = geoToTilePoint(pos.longitude, pos.latitude, zoomInt) val centerNorm = @@ -220,11 +335,13 @@ class MarkerTileRenderer( y = tilePoint.y - tileY, ) val callbackScale = - (iconScaleCallback?.invoke(entity.state, zoomInt) ?: 1.0) + (iconScaleCallback?.invoke(entity.state, scaleZoom) ?: 1.0) .coerceAtLeast(0.0) // icon.size already includes MarkerIconInterface.scale (baked into the // bitmap by toBitmapIcon), so it must not be applied again here. - val scale = (callbackScale * extraIconScale).coerceAtLeast(0.0) + val zoomScale = (callbackScale * extraIconScale).coerceAtLeast(0.0) + noteScale(zoomScale, scaleZoom, entity.state) + val scale = zoomScale * contentScale val drawW = (icon.size.width.toDouble() * scale).coerceAtLeast(1.0) val drawH = (icon.size.height.toDouble() * scale).coerceAtLeast(1.0) val anchorX = icon.anchor.x.toDouble() @@ -234,12 +351,19 @@ class MarkerTileRenderer( kotlin.math.abs(drawW * anchorX), kotlin.math.abs(drawW * (1.0 - anchorX)), ) - val halfExtentY = + var halfExtentY = max( kotlin.math.abs(drawH * anchorY), kotlin.math.abs(drawH * (1.0 - anchorY)), ) - maxHalfExtentPx = max(maxHalfExtentPx, max(halfExtentX, halfExtentY)) + var halfExtent = max(halfExtentX, halfExtentY) + if (label != null) { + // ラベルもはみ出しに数える。境界をまたぐ文字を隣のタイルも描くため。 + halfExtentY = (kotlin.math.abs(label.centerOffsetY) + label.height / 2f) * scale + val labelX = (kotlin.math.abs(label.centerOffsetX) + label.width / 2f) * scale + halfExtent = maxOf(halfExtent, labelX, halfExtentY) + } + maxHalfExtentPx = max(maxHalfExtentPx, halfExtent) prepared.add( PreparedMarker( bitmap = icon.bitmap, @@ -247,6 +371,8 @@ class MarkerTileRenderer( drawW = drawW.toFloat(), drawH = drawH.toFloat(), anchor = icon.anchor, + label = label, + scale = scale.toFloat(), ), ) } @@ -255,7 +381,16 @@ class MarkerTileRenderer( fun queryByHalfExtentPx(halfExtentPx: Double): List> { val span = bounds.toSpan() ?: GeoPoint(0.0, 0.0) - val padNorm = (halfExtentPx / tilePx).coerceAtLeast(0.0) + // A whole declutter cell beyond the icon overhang. + // + // The overhang alone is enough to draw the tile, but not enough to + // decide it: a declutter cell straddling the edge would have some of + // its markers inside the query and some outside, and the tile next + // door would see a different part of the same cell. Both would keep + // a marker and the two would not be the same one, which is an icon + // cut at the seam. Growing by the cell as well means every cell that + // reaches this tile is here in full, so both tiles see all of it. + val padNorm = ((halfExtentPx + declutterCellPx) / tilePx).coerceAtLeast(0.0) val latPad = span.latitude * padNorm val lonPad = span.longitude * padNorm val extended = bounds.expandedByDegrees(latPad, lonPad) @@ -268,12 +403,47 @@ class MarkerTileRenderer( // // maptiler / longdo のようにタイル専用の manager を別に持つプロバイダでは // 全 entity が tiling = true なので、この絞り込みは何もしない。 - return markerManager.findMarkersInBounds(extended).filter { it.tiling } + // Decluttering is about to keep one marker per cell of that many + // pixels, so markers closer together than a cell are + // interchangeable and the index may hand back whichever it likes. + // Saying so is what lets it answer from its cells instead of + // reading every marker: at zoom 9 that is the 5,000 cells holding + // Tokyo's street trees rather than all 141,221 of them, and reading + // a position off an entity alone costs 0.72 microseconds. The index + // falls back to the full query when its own cells are too coarse to + // honour the separation, so the pass below still has to apply the + // real rule. + // From the tile's own span, not the grown one. ios-sdk and react-sdk + // both take it from the tile, and the two now differ by more than + // they used to: the query grew by a declutter cell on every side to + // keep the seams intact, so measuring the separation off `extended` + // would ask for a coarser cell here than there. + val separationDegrees = + if (declutterPx > 0) { + max(span.latitude, span.longitude) * declutterCellPx / tilePx + } else { + 0.0 + } + val found = + if (separationDegrees > 0.0) { + markerManager.findMarkersInBounds(extended, separationDegrees) + } else { + markerManager.findMarkersInBounds(extended) + } + // 後に描いたものが上に残る(間引きでも各マス目の最後が勝つ)。描く順を + // [MarkerDrawOrder] にそろえる: zIndex が大きいほど、同じなら南・西ほど上。 + // 索引の列挙順に任せると、ネイティブのマーカーと前後が食い違う。 + return found.filter { it.tiling }.sortedBy { MarkerDrawOrder.of(it.state.zIndex, it.state.position) } } // First query uses a conservative padding (in dp) so we capture markers slightly outside // the tile that can overlap its edges. - val assumedHalfExtentPx = ResourceProvider.dpToPxForBitmap(32.0) // assume up to 32dp icons + // Start from the largest extent any tile has actually needed rather than + // from a fixed 32dp guess. The guess was smaller than the real icons on + // every tile measured, so the "conservative first pass" never paid off + // and query+prepare simply ran twice for every tile. Widening it as + // soon as one tile knows better costs one extra pass in total. + val assumedHalfExtentPx = queryHalfExtentPx(scaleZoom, contentScale) var entities = queryByHalfExtentPx(assumedHalfExtentPx) @@ -297,6 +467,7 @@ class MarkerTileRenderer( var prepared = result0.first var maxHalfExtentPx = result0.second if (maxHalfExtentPx > assumedHalfExtentPx + 1.0) { + observedHalfExtentPx = maxHalfExtentPx entities = queryByHalfExtentPx(maxHalfExtentPx) val result2 = prepareMarkers(entities) prepared = result2.first @@ -325,6 +496,7 @@ class MarkerTileRenderer( .ceil(maxHalfExtentPx + 2.0) .toInt() .coerceAtLeast(2) + val dstRect = Rect() val offscreenSize = tilePxInt + paddingPx * 2 val offscreenBitmap = acquireBitmap(offscreenSize) offscreenBitmap.eraseColor(Color.TRANSPARENT) @@ -342,19 +514,155 @@ class MarkerTileRenderer( ) } - for (m in prepared) { + // Where each marker lands, and which icon it draws. Markers that + // agree on all of it sit exactly on top of one another. + val placements = LongArray(prepared.size) + val groups = LongArray(prepared.size) + val icons = arrayOfNulls(prepared.size) + val declutter = declutterPx > 0 + val cell = declutterCellPx.coerceAtLeast(contentScale) + // The cell the tile's own corner falls in. Subtracting it keeps the + // group numbers inside the 20 bits [cellKeyOf] packs them into, + // without moving the grid: two tiles still agree about which markers + // share a cell, which is the only thing the grouping is asked for. + val baseCellX = Math.floor(tileX * tilePx / cell) + val baseCellY = Math.floor(tileY * tilePx / cell) + for ((index, m) in prepared.withIndex()) { val centerX = (m.centerNorm.x * tilePx) + paddingPx.toDouble() val centerY = (m.centerNorm.y * tilePx) + paddingPx.toDouble() - val anchorX = m.anchor.x.toDouble() - val anchorY = m.anchor.y.toDouble() - val dst = - RectF( - (centerX - m.drawW * anchorX).toFloat(), - (centerY - m.drawH * anchorY).toFloat(), - (centerX + m.drawW * (1.0 - anchorX)).toFloat(), - (centerY + m.drawH * (1.0 - anchorY)).toFloat(), + // Whole pixels, deliberately. The destination comes out of a + // projection, so it lands on a fraction of a pixel almost every + // time, and a filtered blit to a non-integer rectangle costs + // about twenty times an aligned one: 20k markers measured at + // 4270 ms unaligned against 203 ms aligned on a Pixel 5a. + // Rounding moves a pin by at most half a pixel, which is not + // visible at icon scale, and when the icon is drawn at its + // natural size this also turns the blit into a straight copy. + val left = Math.round(centerX - m.drawW * m.anchor.x.toDouble()).toInt() + val top = Math.round(centerY - m.drawH * m.anchor.y.toDouble()).toInt() + val width = Math.round(m.drawW.toDouble()).toInt().coerceAtLeast(1) + val height = Math.round(m.drawH.toDouble()).toInt().coerceAtLeast(1) + // Packed rather than a data class: one Long per marker instead + // of 20k short-lived objects for the GC to sweep up. + placements[index] = + (left.toLong() and 0xFFFF shl 48) or + (top.toLong() and 0xFFFF shl 32) or + (width.toLong() and 0xFFFF shl 16) or + (height.toLong() and 0xFFFF) + icons[index] = m.bitmap + // The declutter cell is anchored to the world, not to this tile. + // + // `centerNorm` is the position within this tile, so a cell keyed + // off it moves with the tile: the same ground lands in a + // different cell on the tile next door, the two tiles keep + // different markers, and a marker drawn on one and dropped on + // the other is **cut at the seam.** Adding the tile's own + // coordinate back gives the world tile coordinate the projection + // produced, which is the same number whichever tile is asking. + groups[index] = + if (!declutter) { + placements[index] + } else { + cellKeyOf( + (Math.floor((m.centerNorm.x + tileX) * tilePx / cell) - baseCellX).toLong(), + (Math.floor((m.centerNorm.y + tileY) * tilePx / cell) - baseCellY).toLong(), + ) + } + } + + // One survivor per group of markers that cover each other. What + // counts as a group depends on the mode, but the pass is the same + // one either way — a second pass over 144k markers costs more than + // the drawing it saves. + // + // - default: the exact same rectangle drawn with the exact same + // icon. Those are invisible whatever happens, so dropping them + // cannot change the tile. Markers sharing a rectangle but not an + // icon are all kept: a different icon may be transparent where + // the one above it is not. + // + // - declutterPx > 0: everything landing in the same cell of that + // size. Markers a few pixels apart overlap almost completely, + // and thinning them is a judgement about the map rather than a + // free optimisation — hence opt-in. + // + // The last of each group wins, which is what painter's order would + // have left visible. + + // Sort the complete group keys separately from marker indices. + // Packing an index under a 64-bit placement discards its upper bits + // (the x coordinate and part of y), merging unrelated rectangles. + // Each tile would then keep a different marker at its boundary. + val sortedGroups = groups.copyOf() + java.util.Arrays.sort(sortedGroups) + val lastInGroup = IntArray(sortedGroups.size) { -1 } + val mixedIcons = BooleanArray(sortedGroups.size) + // ラベル付きを先に残す。ラベルは利用者が「この点の名前を見せたい」と選んだもので、 + // 同じマス目の点のどれかと入れ替えてよいものではない。ラベル付きどうしは世界座標 + // (worldY 優先、次に worldX)で決める。列挙順はタイルごとに違うので、順番で決めると + // 隣のタイルと別の勝者を選び、境界でラベルが割れる。 + val labelledWinner = IntArray(sortedGroups.size) { -1 } + + fun worldKey(index: Int): Double { + val m = prepared[index] + return (m.centerNorm.y + tileY) * tilePx * 1_048_576.0 + (m.centerNorm.x + tileX) * tilePx + } + for (index in prepared.indices) { + val groupIndex = java.util.Arrays.binarySearch(sortedGroups, groups[index]) + val previous = lastInGroup[groupIndex] + if (previous >= 0 && + ( + icons[previous] !== icons[index] || + prepared[previous].label != null || + prepared[index].label != null ) - canvas.drawBitmap(m.bitmap, null, dst, bmpPaint) + ) { + // 本体が同じでも文字が違えば重ねたまま描く(間引きなしのとき)。 + mixedIcons[groupIndex] = true + } + lastInGroup[groupIndex] = index + if (prepared[index].label != null) { + val winner = labelledWinner[groupIndex] + if (winner < 0 || worldKey(index) > worldKey(winner)) labelledWinner[groupIndex] = index + } + } + val draw = BooleanArray(prepared.size) + for (index in prepared.indices) { + val groupIndex = java.util.Arrays.binarySearch(sortedGroups, groups[index]) + draw[index] = + if (declutter && labelledWinner[groupIndex] >= 0) { + labelledWinner[groupIndex] == index + } else { + lastInGroup[groupIndex] == index || (!declutter && mixedIcons[groupIndex]) + } + } + + for (index in prepared.indices) { + if (!draw[index]) continue + val icon = icons[index] ?: continue + val packed = placements[index] + // Sign-extended: a marker overhanging the tile's top or left + // edge has a negative origin, and masking it back to 16 bits + // unsigned would move it to the far side of the tile. + val left = (packed shr 48).toShort().toInt() + val top = (packed shr 32).toShort().toInt() + val width = (packed shr 16 and 0xFFFF).toInt() + val height = (packed and 0xFFFF).toInt() + dstRect.set(left, top, left + width, top + height) + canvas.drawBitmap(icon, null, dstRect, bmpPaint) + } + + // 文字は本体をすべて描いたあと。ほかの点の下に字が隠れない。 + for (index in prepared.indices) { + if (!draw[index]) continue + val m = prepared[index] + val label = m.label ?: continue + label.draw( + canvas = canvas, + anchorX = (m.centerNorm.x * tilePx + paddingPx).toFloat(), + anchorY = (m.centerNorm.y * tilePx + paddingPx).toFloat(), + scale = m.scale, + ) } } @@ -382,28 +690,36 @@ class MarkerTileRenderer( // ByteArrayOutputStream starts at 32 bytes and doubles its backing array on every // compress() call until it reaches the tile's steady-state size (often hundreds of KB // for dense tiles), so a new instance per call re-triggers that regrowth every time. - // Keeping one per thread (reset, not recreated, before each use) lets the backing - // array settle at its steady-state size and be reused across tiles. - private val tileByteStream = - ThreadLocal.withInitial { ByteArrayOutputStream(16 * 1024) } + // Keeping a few (reset, not recreated, before each use) lets the backing array + // settle at its steady-state size and be reused across tiles. A pool, not one per + // thread: map SDK threads that outlive their map would keep theirs (ScratchPool). + private val tileByteStreams = ScratchPool() private fun bitmapToByteArray(bitmap: Bitmap): ByteArray { - // ThreadLocal.get() is a Java generic method, so Kotlin sees its return type as - // nullable even though withInitial() guarantees a value; !! is safe here. - val outputStream = tileByteStream.get()!! - outputStream.reset() - bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream) - // toByteArray() still copies out a right-sized array: callers cache this array or - // hand it to a socket write, both of which need a stable array that isn't mutated - // by the next renderTile() call on this thread. - return outputStream.toByteArray() + // Rust first: it is 4-6x faster than Bitmap.compress on the tiles this + // renderer produces, and compress is what dominates a tile once the + // drawing is aligned. Null means the native path was unavailable or + // declined the bitmap, and the platform encoder takes over. + TilePngEncoder.encode(bitmap)?.let { return it } + + val outputStream = tileByteStreams.acquire() ?: ByteArrayOutputStream(16 * 1024) + try { + outputStream.reset() + bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream) + // toByteArray() still copies out a right-sized array: callers cache this array or + // hand it to a socket write, both of which need a stable array that isn't mutated + // by the next renderTile() call. + return outputStream.toByteArray() + } finally { + tileByteStreams.release(outputStream) + } } private fun acquireBitmap(size: Int): Bitmap { val safeSize = size.coerceAtLeast(1) synchronized(bitmapPoolLock) { val bucket = bitmapPool[safeSize] - while (bucket != null && bucket.isNotEmpty()) { + while (!bucket.isNullOrEmpty()) { val candidate = bucket.removeFirst() bitmapPoolCount = (bitmapPoolCount - 1).coerceAtLeast(0) if (!candidate.isRecycled && candidate.width == safeSize && candidate.height == safeSize) { @@ -491,6 +807,15 @@ class MarkerTileRenderer( } private companion object { + private const val CELL_BITS = 20 + private const val CELL_ORIGIN = 1L shl (CELL_BITS - 1) + + /** Offset so a marker above or left of the tile still keys positive. */ + private fun cellKeyOf( + cx: Long, + cy: Long, + ): Long = ((cx + CELL_ORIGIN) shl CELL_BITS) or (cy + CELL_ORIGIN) + private const val MAX_MERCATOR_LAT = 85.05112878 } } diff --git a/src/main/java/com/mapconductor/core/marker/MarkerTilingOptions.kt b/src/main/java/com/mapconductor/core/marker/MarkerTilingOptions.kt index bf8799e..d2a4408 100644 --- a/src/main/java/com/mapconductor/core/marker/MarkerTilingOptions.kt +++ b/src/main/java/com/mapconductor/core/marker/MarkerTilingOptions.kt @@ -24,6 +24,21 @@ data class MarkerTilingOptions( * `effectiveScale = (markerState.icon?.scale ?: 1.0) * (iconScaleCallback?.invoke(markerState, zoom) ?: 1.0)` */ val iconScaleCallback: ((MarkerState, Int) -> Double)? = null, + /** + * Collapse markers that land within this many pixels of one already drawn. + * + * Off by default, because it changes what the map shows. The renderer + * always drops markers hidden *exactly* behind another — same rectangle, + * same icon — since that is invisible either way. This is the other kind: + * markers a few pixels apart overlap almost completely, and thinning them + * is a judgement about the map rather than a free optimisation. + * + * A sensible value is the icon's own size, so what survives never overlaps + * by more than half. On a dense dataset the saving is large: Tokyo's + * 144,183 street trees draw in a fraction of the time, because a city + * block's worth of trees becomes the handful you could actually distinguish. + */ + val declutterPx: Int = 0, ) { /** * ビューポート内のマーカーが少ないとき、タイルをやめてネイティブマーカーで描くための設定。 diff --git a/src/main/java/com/mapconductor/core/marker/StrategyMarkerController.kt b/src/main/java/com/mapconductor/core/marker/StrategyMarkerController.kt index da18b40..1f41182 100644 --- a/src/main/java/com/mapconductor/core/marker/StrategyMarkerController.kt +++ b/src/main/java/com/mapconductor/core/marker/StrategyMarkerController.kt @@ -1,5 +1,6 @@ package com.mapconductor.core.marker +import com.mapconductor.core.InternalMapConductorApi import com.mapconductor.core.controller.OnCameraChangeReceiverInterface import com.mapconductor.core.controller.OverlayHit import com.mapconductor.core.controller.OverlayKind @@ -18,7 +19,8 @@ class StrategyMarkerController( MarkerEntityInterface, >, OnCameraChangeReceiverInterface, - MarkerEventHostInterface { + MarkerEventHostInterface, + MarkerDrawOrderReceiver { override val markerManager: MarkerManager = strategy.markerManager override val zIndex: Int = 10 private var mapCameraPosition: MapCameraPosition? = null @@ -104,22 +106,36 @@ class StrategyMarkerController( } } + /** + * 他の 5 種類・[AbstractMarkerController] の clear() と同じく + * 「onRemove(全部) → 空にする → onPostProcess」の順に呼ぶ。 + * + * 以前は strategy.clear() で manager を空にするだけだった。GL 系の描画担当は + * onRemove では地図に触らず onPostProcess で manager から描き直すので、 + * 呼ばないと clear() の後もマーカーが地図に残る。onRemove はアイコン等の + * 描画側の資源を返すため。空にするのは strategy.clear() のままにして、 + * ストラテジ固有の後片付け(クラスタの状態など)を保つ。 + * add / update と同じ permit の中で行い、ストラテジの処理と交錯させない。 + */ override suspend fun clear() { - strategy.clear() + semaphore.withPermit { + val entities = markerManager.allEntities() + if (entities.isNotEmpty()) renderer.onRemove(entities) + strategy.clear() + // 最初のカメラ待ちで保留していたものも消す。残すと次のカメラで描かれてしまう。 + pendingStates = null + renderer.onPostProcess() + } } override fun getEntity(id: String): MarkerEntityInterface? = strategy.markerManager.getEntity(id) + @OptIn(InternalMapConductorApi::class) override fun find(position: GeoPointInterface): MarkerEntityInterface? { - val nearest = strategy.markerManager.findNearest(position) ?: return null - val touchScreen = renderer.holder.toScreenOffset(position) ?: return null - val markerScreen = renderer.holder.toScreenOffset(nearest.state.position) ?: return null - - return if (MarkerHitTest.hitsIcon(touchScreen, markerScreen, nearest.state)) { - nearest - } else { - null - } + val holder = renderer.holder + val touchScreen = holder.toScreenOffset(position) ?: return null + val bounds = MarkerHitPick.searchBounds(position, touchScreen, holder::toScreenOffset) ?: return null + return MarkerHitPick.pick(touchScreen, strategy.markerManager.findMarkersInBounds(bounds), holder::toScreenOffset) } override suspend fun onCameraChanged(mapCameraPosition: MapCameraPosition) { @@ -133,6 +149,10 @@ class StrategyMarkerController( add(pending) } + override suspend fun onDrawOrderFrameChanged(frame: MarkerDrawOrder.Frame) { + semaphore.withPermit { renderer.onDrawOrderFrameChanged(frame, markerManager.allEntities()) } + } + override fun destroy() { strategy.clear() } diff --git a/src/main/java/com/mapconductor/core/polygon/Polygon.kt b/src/main/java/com/mapconductor/core/polygon/Polygon.kt index 4c4c27d..2c2cd7c 100644 --- a/src/main/java/com/mapconductor/core/polygon/Polygon.kt +++ b/src/main/java/com/mapconductor/core/polygon/Polygon.kt @@ -1,167 +1,269 @@ -package com.mapconductor.core.polygon - -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.setValue -import androidx.compose.runtime.snapshotFlow -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.unit.Dp -import androidx.compose.ui.unit.dp -import com.mapconductor.core.ComponentState -import com.mapconductor.core.features.GeoPointInterface -import java.io.Serializable -import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.flow.distinctUntilChanged - -class PolygonState( - points: List, - holes: List> = emptyList(), - id: String? = null, - strokeColor: Color = Color.Black, - strokeWidth: Dp = 2.dp, - fillColor: Color = Color.Transparent, - geodesic: Boolean = false, - clickable: Boolean = true, - zIndex: Int = 0, - extra: Serializable? = null, - onClick: OnPolygonEventHandler? = null, -) : ComponentState { - override val id = - ( - id ?: polygonId( - listOf( - listHashCode(points), - nestedListHashCode(holes), - strokeColor.hashCode(), - strokeWidth.hashCode(), - fillColor.hashCode(), - geodesic.hashCode(), - clickable.hashCode(), - extra?.hashCode() ?: 0, - ), - ) - ).toString() - var strokeColor by mutableStateOf(strokeColor) - var strokeWidth by mutableStateOf(strokeWidth) - var fillColor by mutableStateOf(fillColor) - var geodesic by mutableStateOf(geodesic) - - /** - * タップを受け取るか。`false` ならこのポリゴンはタップに対して透過し、 - * 下のオーバーレイ(無ければ地図クリック)へイベントが流れる。 - * - * 判定はコアの [com.mapconductor.core.polygon.PolygonManager.find] が行うため、 - * どのプロバイダでも同じ挙動になる。描画には影響しないので [fingerPrint] には - * 含めない(含めると値を変えるたびにオーバーレイが作り直される)。 - */ - var clickable by mutableStateOf(clickable) - var zIndex by mutableStateOf(zIndex) - var points by mutableStateOf>(points) - var holes by mutableStateOf>>(holes) - var extra by mutableStateOf(extra) - var onClick by mutableStateOf(onClick) - - private fun polygonId(hashCodes: List): Int = - hashCodes.reduce { result, hashCode -> - 31 * result + hashCode - } - - override fun equals(other: Any?): Boolean { - val otherState = (other as? PolygonState) ?: return false - return hashCode() == otherState.hashCode() - } - - override fun hashCode(): Int { - var result = extra?.hashCode() ?: 0 - result = 31 * result + this@PolygonState.strokeColor.hashCode() - result = 31 * result + this@PolygonState.strokeWidth.hashCode() - result = 31 * result + this@PolygonState.fillColor.hashCode() - result = 31 * result + geodesic.hashCode() - result = 31 * result + clickable.hashCode() - result = 31 * result + zIndex.hashCode() - result = 31 * result + points.hashCode() - result = 31 * result + holes.hashCode() - return result - } - - private fun listHashCode(list: List): Int { - var result = 0 - list.forEach { - result = 31 * result + it.hashCode() - } - return result - } - - private fun nestedListHashCode(list: List>): Int { - var result = 0 - list.forEach { inner -> - result = 31 * result + listHashCode(inner) - } - return result - } - - fun fingerPrint(): PolygonFingerPrint = - PolygonFingerPrint( - id = this.id.hashCode(), - strokeColor = this@PolygonState.strokeColor.hashCode(), - strokeWidth = this@PolygonState.strokeWidth.hashCode(), - fillColor = this@PolygonState.fillColor.hashCode(), - geodesic = geodesic.hashCode(), - zIndex = zIndex, - points = listHashCode(points), - holes = nestedListHashCode(holes), - extra = extra?.hashCode() ?: 0, - ) - - fun copy( - points: List = this.points, - holes: List> = this.holes, - id: String? = this.id, - strokeColor: Color = this.strokeColor, - strokeWidth: Dp = this.strokeWidth, - fillColor: Color = this.fillColor, - geodesic: Boolean = this.geodesic, - clickable: Boolean = this.clickable, - zIndex: Int = this.zIndex, - extra: Serializable? = this.extra, - onClick: OnPolygonEventHandler? = this.onClick, - ): PolygonState = - PolygonState( - points = points, - holes = holes, - id = id, - strokeColor = strokeColor, - strokeWidth = strokeWidth, - fillColor = fillColor, - geodesic = geodesic, - clickable = clickable, - zIndex = zIndex, - extra = extra, - onClick = onClick, - ) - - fun asFlow(): Flow = snapshotFlow { fingerPrint() }.distinctUntilChanged() -} - -data class PolygonFingerPrint( - val id: Int, - val strokeColor: Int, - val strokeWidth: Int, - val fillColor: Int, - val geodesic: Int, - val zIndex: Int, - val points: Int, - val holes: Int, - val extra: Int, -) - -class PolygonEvent( - val state: PolygonState, - clicked: GeoPointInterface, -) { - // 生成時に wrap して [-180,180] / [-90,90] に正規化する(日付変更線対策)。 - // 正規化をここ(イベント型=出口)に一元化することで、どの配送経路でも wrap 漏れが起きない。 - val clicked: GeoPointInterface = clicked.wrap() -} - -typealias OnPolygonEventHandler = (PolygonEvent) -> Unit +package com.mapconductor.core.polygon + +import androidx.compose.runtime.getValue +import androidx.compose.runtime.setValue +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import com.mapconductor.core.ComponentState +import com.mapconductor.core.StateMutationSignal +import com.mapconductor.core.features.GeoPointInterface +import java.io.Serializable + +class PolygonState( + points: List, + holes: List> = emptyList(), + id: String? = null, + strokeColor: Color = Color.Black, + strokeWidth: Dp = 1.dp, + fillColor: Color = Color.Transparent, + geodesic: Boolean = false, + clickable: Boolean = true, + zIndex: Int = 0, + extra: Serializable? = null, + onClick: OnPolygonEventHandler? = null, + onAdded: OnPolygonAddedHandler? = null, +) : ComponentState { + override val id = + ( + id ?: polygonId( + listOf( + listHashCode(points), + nestedListHashCode(holes), + strokeColor.hashCode(), + strokeWidth.hashCode(), + fillColor.hashCode(), + geodesic.hashCode(), + clickable.hashCode(), + extra?.hashCode() ?: 0, + ), + ) + ).toString() + + /** + * Writes to the fields below are announced here rather than discovered by + * reading them all back. See [StateMutationSignal]. + */ + override val mutations = StateMutationSignal() + + var strokeColor by mutations.notifying(strokeColor) + var strokeWidth by mutations.notifying(strokeWidth) + var fillColor by mutations.notifying(fillColor) + var geodesic by mutations.notifying(geodesic) + + /** + * タップを受け取るか。`false` ならこのポリゴンはタップに対して透過し、 + * 下のオーバーレイ(無ければ地図クリック)へイベントが流れる。 + * + * 判定はコアの [com.mapconductor.core.polygon.PolygonManager.find] が行うため、 + * どのプロバイダでも同じ挙動になる。描画には影響しないので [fingerPrint] には + * 含めない(含めると値を変えるたびにオーバーレイが作り直される)。 + */ + var clickable by mutations.notifying(clickable) + var zIndex by mutations.notifying(zIndex) + + /** + * 外周の頂点。 + * + * state が見ているのはこのプロパティへの代入だけ。渡したリストをその場で書き換えても + * 描き直されない(`mutableStateListOf` を渡して `add` / `set` する使い方は効かない)。 + * 形を変えるときは新しいリストを代入する: + * + * ``` + * polygonState.points = polygonState.points.toMutableList().apply { this[i] = moved } + * ``` + * + * 内容の等しいリストの代入は無視される。その場で書き換えた同じリストを代入し直しても、 + * 前の値と同じものなので何も起きない。 + */ + var points by mutations.notifying>(points) + + /** + * 穴(内周)の頂点。[points] と同じく、変えるときは新しいリストを代入する。 + * 内側のリストをその場で書き換えても描き直されない。 + */ + var holes by mutations.notifying>>(holes) + var extra by mutations.notifying(extra) + var onClick by mutations.notifying(onClick) + + /** + * Called once each time this polygon goes from not being on the map to being on it: + * after the map SDK's object for it has been created, or, when it is drawn in tiles, + * after the URL template of those tiles has been handed to the map as a raster layer + * (the tile images may still be loading then). Not called for an in-place change, + * nor when it moves between native drawing and tiles while staying on the map; + * called again if it is removed and added again. Clearing or destroying the map calls + * nothing. + * + * Runs on the main thread once the map has finished adding the overlays it was given. + * A callback that throws is logged and does not stop the other overlays' callbacks. + * + * Like `onClick`, it is not part of the id, fingerprint, equality or hash: replacing + * it redraws nothing. If the same state is shown on two maps, each map calls it. + */ + var onAdded: OnPolygonAddedHandler? = onAdded + + @Deprecated("Binary compatibility only; use the overload with onAdded.", level = DeprecationLevel.HIDDEN) + constructor( + points: List, + holes: List> = emptyList(), + id: String? = null, + strokeColor: Color = Color.Black, + strokeWidth: Dp = 1.dp, + fillColor: Color = Color.Transparent, + geodesic: Boolean = false, + clickable: Boolean = true, + zIndex: Int = 0, + extra: Serializable? = null, + onClick: OnPolygonEventHandler? = null, + ) : this( + points, + holes, + id, + strokeColor, + strokeWidth, + fillColor, + geodesic, + clickable, + zIndex, + extra, + onClick, + null, + ) + + private fun polygonId(hashCodes: List): Int = + hashCodes.reduce { result, hashCode -> + 31 * result + hashCode + } + + override fun equals(other: Any?): Boolean { + val otherState = (other as? PolygonState) ?: return false + return hashCode() == otherState.hashCode() + } + + override fun hashCode(): Int { + var result = extra?.hashCode() ?: 0 + result = 31 * result + this@PolygonState.strokeColor.hashCode() + result = 31 * result + this@PolygonState.strokeWidth.hashCode() + result = 31 * result + this@PolygonState.fillColor.hashCode() + result = 31 * result + geodesic.hashCode() + result = 31 * result + clickable.hashCode() + result = 31 * result + zIndex.hashCode() + result = 31 * result + points.hashCode() + result = 31 * result + holes.hashCode() + return result + } + + private fun listHashCode(list: List): Int { + var result = 0 + list.forEach { + result = 31 * result + it.hashCode() + } + return result + } + + private fun nestedListHashCode(list: List>): Int { + var result = 0 + list.forEach { inner -> + result = 31 * result + listHashCode(inner) + } + return result + } + + fun fingerPrint(): PolygonFingerPrint = + PolygonFingerPrint( + id = this.id.hashCode(), + strokeColor = this@PolygonState.strokeColor.hashCode(), + strokeWidth = this@PolygonState.strokeWidth.hashCode(), + fillColor = this@PolygonState.fillColor.hashCode(), + geodesic = geodesic.hashCode(), + zIndex = zIndex, + points = listHashCode(points), + holes = nestedListHashCode(holes), + extra = extra?.hashCode() ?: 0, + ) + + fun copy( + points: List = this.points, + holes: List> = this.holes, + id: String? = this.id, + strokeColor: Color = this.strokeColor, + strokeWidth: Dp = this.strokeWidth, + fillColor: Color = this.fillColor, + geodesic: Boolean = this.geodesic, + clickable: Boolean = this.clickable, + zIndex: Int = this.zIndex, + extra: Serializable? = this.extra, + onClick: OnPolygonEventHandler? = this.onClick, + onAdded: OnPolygonAddedHandler? = this.onAdded, + ): PolygonState = + PolygonState( + points = points, + holes = holes, + id = id, + strokeColor = strokeColor, + strokeWidth = strokeWidth, + fillColor = fillColor, + geodesic = geodesic, + clickable = clickable, + zIndex = zIndex, + extra = extra, + onClick = onClick, + onAdded = onAdded, + ) + + @Deprecated("Binary compatibility only; use the overload with onAdded.", level = DeprecationLevel.HIDDEN) + fun copy( + points: List = this.points, + holes: List> = this.holes, + id: String? = this.id, + strokeColor: Color = this.strokeColor, + strokeWidth: Dp = this.strokeWidth, + fillColor: Color = this.fillColor, + geodesic: Boolean = this.geodesic, + clickable: Boolean = this.clickable, + zIndex: Int = this.zIndex, + extra: Serializable? = this.extra, + onClick: OnPolygonEventHandler? = this.onClick, + ): PolygonState = + copy( + points, + holes, + id, + strokeColor, + strokeWidth, + fillColor, + geodesic, + clickable, + zIndex, + extra, + onClick, + onAdded, + ) +} + +data class PolygonFingerPrint( + val id: Int, + val strokeColor: Int, + val strokeWidth: Int, + val fillColor: Int, + val geodesic: Int, + val zIndex: Int, + val points: Int, + val holes: Int, + val extra: Int, +) + +class PolygonEvent( + val state: PolygonState, + clicked: GeoPointInterface, +) { + // 生成時に wrap して [-180,180] / [-90,90] に正規化する(日付変更線対策)。 + // 正規化をここ(イベント型=出口)に一元化することで、どの配送経路でも wrap 漏れが起きない。 + val clicked: GeoPointInterface = clicked.wrap() +} + +typealias OnPolygonEventHandler = (PolygonEvent) -> Unit + +/** Receives the state whose polygon was just added to the map. See [PolygonState.onAdded]. */ +typealias OnPolygonAddedHandler = (PolygonState) -> Unit diff --git a/src/main/java/com/mapconductor/core/polygon/PolygonController.kt b/src/main/java/com/mapconductor/core/polygon/PolygonController.kt index 96eb44f..dc6edf8 100644 --- a/src/main/java/com/mapconductor/core/polygon/PolygonController.kt +++ b/src/main/java/com/mapconductor/core/polygon/PolygonController.kt @@ -4,8 +4,10 @@ import com.mapconductor.core.controller.OverlayHit import com.mapconductor.core.controller.OverlayKind import com.mapconductor.core.controller.SlottedOverlayController import com.mapconductor.core.features.GeoPointInterface +import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.sync.Semaphore import kotlinx.coroutines.sync.withPermit +import kotlinx.coroutines.withContext abstract class PolygonController( val polygonManager: PolygonManagerInterface, @@ -19,6 +21,15 @@ abstract class PolygonController( var clickListener: OnPolygonEventHandler? = null + /** + * Set by a provider that can show polygon tiles (see [PolygonTiler]). + * Polygons it tiles stay in [polygonManager], for taps, with no native + * overlay: their entity's `polygon` is null and the renderer never sees + * them. + */ + var tiler: PolygonTiler? = null + private var tiledIds: Set = emptySet() + fun dispatchClick(event: PolygonEvent) { // 配送座標の wrap は PolygonEvent の生成時に一元化済み。 event.state.onClick?.invoke(event) @@ -27,15 +38,26 @@ abstract class PolygonController( override suspend fun add(data: List) { semaphore.withPermit { + val wasTiled = tiledIds + val tiled = tiler?.route(data) ?: emptySet() + tiledIds = tiled + val native = if (tiled.isEmpty()) data else data.filter { it.id !in tiled } val modifiedEntities = mutableListOf>() - val previous = polygonManager.allEntities().map { it.state.id }.toMutableSet() + // Native handles remain authoritative after a cancelled transition: + // route() may already have switched the IDs to tiles before removal finishes. + val previous = + polygonManager + .allEntities() + .filter { it.polygon != null } + .mapTo(mutableSetOf()) { it.state.id } val added = mutableListOf() val updated = mutableListOf>() val removed = mutableListOf>() - data.forEach { state -> + native.forEach { state -> if (previous.contains(state.id)) { - val prevEntity = polygonManager.getEntity(state.id)!! + // Gone only if destroy() cleared the manager meanwhile; nothing left to update. + val prevEntity = polygonManager.getEntity(state.id) ?: return@withPermit if (state.fingerPrint() == prevEntity.fingerPrint) { // 描画結果が不変なら renderer を呼ばず最新の state だけ採用する(react-sdk と同じ)。 polygonManager.registerEntity(PolygonEntity(state = state, polygon = prevEntity.polygon)) @@ -110,13 +132,68 @@ abstract class PolygonController( } } + // Tiled polygons: kept for taps, nothing native. Those that left + // the tiles and the list are forgotten; those that left the tiles + // for native drawing were added above. + if (wasTiled.isNotEmpty()) { + val nativeIds = native.mapTo(HashSet()) { it.id } + for (id in wasTiled) { + if (id !in tiled && id !in nativeIds) polygonManager.removeEntity(id) + } + } + if (tiled.isNotEmpty()) { + val tiledStates = tiler!!.tiledStates() + withContext(Dispatchers.Default) { + for (state in tiledStates) { + polygonManager.registerEntity(PolygonEntity(polygon = inTiles(), state = state)) + } + } + } + renderer.onPostProcess() } } + /** What a tiled polygon's entity holds instead of a native polygon. */ + @Suppress("UNCHECKED_CAST") + private fun inTiles(): ActualPolygon = null as ActualPolygon + override suspend fun update(state: PolygonState) { semaphore.withPermit { val prevEntity = polygonManager.getEntity(state.id) ?: return + if (state.id in tiledIds) { + if (PolygonTileSet.canTile(state)) { + if (state.zIndex != prevEntity.fingerPrint.zIndex) { + tiler?.reorder(state) + } else { + tiler?.update(state) + } + polygonManager.registerEntity(PolygonEntity(polygon = prevEntity.polygon, state = state)) + return + } + // No longer drawable in a tile (geodesic, half the world wide, or + // under 3 points): the map SDK draws it from now on. Still on the + // map, so this is not an add. Whether the rest stay in tiles is + // left to the next add(), which decides tiling for the whole list. + tiledIds = tiledIds - state.id + tiler?.remove(state.id) + val polygons = + renderer.onAdd( + listOf( + object : PolygonOverlayRendererInterface.AddParamsInterface { + override val state: PolygonState = state + }, + ), + ) + val polygon = polygons.firstOrNull() + if (polygon != null) { + polygonManager.registerEntity(PolygonEntity(polygon = polygon, state = state)) + } else { + polygonManager.removeEntity(state.id) + } + renderer.onPostProcess() + return + } val currentFinger = state.fingerPrint() val prevFinger = prevEntity.fingerPrint if (currentFinger == prevFinger) { @@ -151,9 +228,15 @@ abstract class PolygonController( override suspend fun clear() { semaphore.withPermit { - val entities: List> = polygonManager.allEntities() + tiledIds = emptySet() + tiler?.clear() + val entities: List> = + polygonManager.allEntities().filter { it.polygon != null } renderer.onRemove(entities) + // manager を空にしてから onPostProcess を呼ぶ。GL 系の描画担当は remove では何もせず、 + // onPostProcess で manager の全部を描き直すので、逆の順だと clear() 後も地図に残る。 polygonManager.clear() + renderer.onPostProcess() } } @@ -162,7 +245,12 @@ abstract class PolygonController( .find(position) override fun destroy() { - // No native resources to clean up for polygons + // The tile server outlives the map; without this its route keeps every + // tiled polygon (and the renderer's copies of them) alive. + tiler?.dispose() + // A destroyed controller can still be referenced (by its map controller, + // or a state that has not let go yet); without this it keeps every entity. + polygonManager.clear() } override fun has(id: String): Boolean = polygonManager.hasEntity(id) diff --git a/src/main/java/com/mapconductor/core/polygon/PolygonHoleUnion.kt b/src/main/java/com/mapconductor/core/polygon/PolygonHoleUnion.kt index 35d6245..13b1e99 100644 --- a/src/main/java/com/mapconductor/core/polygon/PolygonHoleUnion.kt +++ b/src/main/java/com/mapconductor/core/polygon/PolygonHoleUnion.kt @@ -5,9 +5,12 @@ import com.mapconductor.core.features.GeoPointInterface import kotlin.math.PI import kotlin.math.abs import kotlin.math.atan2 +import kotlin.math.ceil +import kotlin.math.floor import kotlin.math.hypot import kotlin.math.min import kotlin.math.roundToLong +import kotlin.math.sqrt /** * 重なり合う穴リング同士を平面(経度緯度)座標系で結合する。外部ジオメトリライブラリ非依存。 @@ -31,6 +34,17 @@ fun unionHoleRings(holes: List>): List 0.0 }) return holes + return holes.mapIndexed { i, hole -> if (signedArea(rings[i]) > 0.0) hole.asReversed() else hole } + } val merged = unionRings(rings) if (merged.isEmpty()) return holes @@ -71,6 +85,9 @@ private const val Q = 1e-9 // フィーチャースケール座標での平行・共線・線分上判定の許容誤差。 private const val EPS = 1e-12 +// 中点からこれより近い部分辺はその中点を通っている(度。Q よりはるかに小さい)。 +private const val ON_EDGE = 1e-12 + private fun unionRings(rings: List>): List> { // 全リングの有向辺(閉じたものとして扱う)。 val edges = mutableListOf() @@ -87,9 +104,127 @@ private fun unionRings(rings: List>): List> { return traceRings(boundary) } +// intersectionPoints が線分の外接矩形の外まで拾う距離(度)。共線判定は直線から EPS / |seg| までの +// 辺を受け入れ、sqrt(EPS) = 1e-6 より短い線分はそこで除かれるので、高々 2e-6。 +private const val MEET_PAD = 4e-6 + +// 部分辺の中点から左右の標本点までの距離の上限の 2 倍(度)。 +private const val CLEARANCE_CAP = 2e-5 + +/** + * 辺を外接矩形で一様格子に登録し、探索をすべての辺ではなく矩形の近くの辺だけに絞る。 + * 辺の矩形が触れるすべてのセルに登録するので、矩形が触れるセルを全部見れば、 + * その矩形と出会い得る辺はすべて見つかる。 + */ +private class EdgeGrid( + edges: List, + pad: Double, +) { + private val side: Int + private val minX: Double + private val minY: Double + private val cellW: Double + private val cellH: Double + private val cells = HashMap() + private val seen = IntArray(edges.size) + private var stamp = 0 + + init { + var x0 = Double.POSITIVE_INFINITY + var y0 = Double.POSITIVE_INFINITY + var x1 = Double.NEGATIVE_INFINITY + var y1 = Double.NEGATIVE_INFINITY + for (e in edges) { + x0 = minOf(x0, e.a.x, e.b.x) + x1 = maxOf(x1, e.a.x, e.b.x) + y0 = minOf(y0, e.a.y, e.b.y) + y1 = maxOf(y1, e.a.y, e.b.y) + } + side = ceil(sqrt(edges.size.toDouble())).toInt().coerceIn(1, 1024) + minX = x0 + minY = y0 + cellW = ((x1 - x0) / side).let { if (it > 0.0) it else 1.0 } + cellH = ((y1 - y0) / side).let { if (it > 0.0) it else 1.0 } + for (i in edges.indices) { + val e = edges[i] + forCells( + minOf(e.a.x, e.b.x) - pad, + minOf(e.a.y, e.b.y) - pad, + maxOf(e.a.x, e.b.x) + pad, + maxOf(e.a.y, e.b.y) + pad, + ) { key -> cells.getOrPut(key) { IntArrayList() }.add(i) } + } + } + + /** 矩形が触れるセルに登録された辺の番号。各辺 1 回、順序は不定。 */ + fun near( + minX: Double, + minY: Double, + maxX: Double, + maxY: Double, + out: IntArrayList, + ): IntArrayList { + out.clear() + val current = ++stamp + forCells(minX, minY, maxX, maxY) { key -> + val bucket = cells[key] ?: return@forCells + for (k in 0 until bucket.size) { + val i = bucket[k] + if (seen[i] == current) continue + seen[i] = current + out.add(i) + } + } + return out + } + + private inline fun forCells( + minX: Double, + minY: Double, + maxX: Double, + maxY: Double, + visit: (Int) -> Unit, + ) { + val cx0 = cell(minX, this.minX, cellW) + val cx1 = cell(maxX, this.minX, cellW) + val cy0 = cell(minY, this.minY, cellH) + val cy1 = cell(maxY, this.minY, cellH) + for (cx in cx0..cx1) { + for (cy in cy0..cy1) visit(cx * side + cy) + } + } + + private fun cell( + v: Double, + min: Double, + size: Double, + ): Int = floor((v - min) / size).coerceIn(0.0, (side - 1).toDouble()).toInt() +} + +/** 箱詰めしない Int の可変長配列。 */ +private class IntArrayList { + private var items = IntArray(4) + var size = 0 + private set + + operator fun get(index: Int): Int = items[index] + + fun add(value: Int) { + if (size == items.size) items = items.copyOf(size * 2) + items[size++] = value + } + + fun clear() { + size = 0 + } +} + /** 各辺を、他の辺が交差・接触する全ての点で分割する。 */ private fun splitEdges(edges: List): List { val result = mutableListOf() + // この辺の矩形から MEET_PAD 以内に矩形が来る辺だけが、この辺と出会い得る。 + val grid = EdgeGrid(edges, MEET_PAD) + val near = IntArrayList() for (i in edges.indices) { val seg = edges[i] val dir = sub(seg.b, seg.a) @@ -105,7 +240,15 @@ private fun splitEdges(edges: List): List { } add(seg.a) add(seg.b) - for (j in edges.indices) { + grid.near( + minOf(seg.a.x, seg.b.x) - MEET_PAD, + minOf(seg.a.y, seg.b.y) - MEET_PAD, + maxOf(seg.a.x, seg.b.x) + MEET_PAD, + maxOf(seg.a.y, seg.b.y) + MEET_PAD, + near, + ) + for (k in 0 until near.size) { + val j = near[k] if (i == j) continue for (p in intersectionPoints(seg, edges[j])) add(p) } @@ -133,6 +276,9 @@ private fun classifyBoundary( ): List { val out = mutableListOf() val seen = HashSet>() + val grid = EdgeGrid(subEdges, 0.0) + val near = IntArrayList() + val ringsBounds = rings.map(::ringBounds) for (seg in subEdges) { val dir = sub(seg.b, seg.a) val len = hypot(dir.x, dir.y) @@ -140,12 +286,15 @@ private fun classifyBoundary( val mid = add2(seg.a, scale(dir, 0.5)) // 単位左法線。中点の左右すぐ横でカバレッジを標本化する。分割後は他の辺が - // この部分辺の内部を横切らないため、微小オフセットはこの辺が隔てる 2 セル内に収まる。 + // この部分辺の内部を横切らないため、最寄りの他の辺までの距離より短いオフセットなら + // この辺が隔てる 2 セル内に収まる。固定オフセットでは収まらない: 別の穴がそれより + // 近くを通る(1e-5 度離れた 2 つの穴)と標本点がその穴に入り、辺が両側とも内部に + // 見えて落とされ、繋ぎ直したリングが穴を横切る。 val nx = -dir.y / len val ny = dir.x / len - val off = min(len * 0.25, 1e-5) - val leftInside = coverage(Vec(mid.x + nx * off, mid.y + ny * off), rings) > 0 - val rightInside = coverage(Vec(mid.x - nx * off, mid.y - ny * off), rings) > 0 + val off = min(len * 0.25, 0.5 * clearance(mid, CLEARANCE_CAP, subEdges, grid, near)) + val leftInside = coverage(Vec(mid.x + nx * off, mid.y + ny * off), rings, ringsBounds) > 0 + val rightInside = coverage(Vec(mid.x - nx * off, mid.y - ny * off), rings, ringsBounds) > 0 if (leftInside == rightInside) continue // 両側とも内部、または両側とも外部 // 内部が左側に来る向きへ揃える。 @@ -158,6 +307,46 @@ private fun classifyBoundary( return out } +/** + * `point`(部分辺の中点)から、それを通らない最寄りの部分辺までの距離。`cap` より近いものが + * 無ければ `cap`。その部分辺自身と、他のリングから来た同じ部分辺は中点を通るので除く。 + * 点のまわり `cap` の矩形の近くに登録された部分辺だけを調べる。`cap` より近いものはその中にある。 + */ +private fun clearance( + point: Vec, + cap: Double, + subEdges: List, + grid: EdgeGrid, + near: IntArrayList, +): Double { + var best = cap + grid.near(point.x - cap, point.y - cap, point.x + cap, point.y + cap, near) + for (k in 0 until near.size) { + val e = subEdges[near[k]] + if (minOf(e.a.x, e.b.x) > point.x + best || + maxOf(e.a.x, e.b.x) < point.x - best || + minOf(e.a.y, e.b.y) > point.y + best || + maxOf(e.a.y, e.b.y) < point.y - best + ) { + continue + } + val d = distanceToSegment(point, e) + if (d > ON_EDGE && d < best) best = d + } + return best +} + +private fun distanceToSegment( + p: Vec, + e: Edge, +): Double { + val d = sub(e.b, e.a) + val lenSq = dot(d, d) + val t = if (lenSq > 0.0) clamp01(dot(sub(p, e.a), d) / lenSq) else 0.0 + val q = add2(e.a, scale(d, t)) + return hypot(p.x - q.x, p.y - q.y) +} + /** 有向境界辺を連結して閉リングにする。 */ private fun traceRings(edges: List): List> { val byStart = HashMap>() @@ -213,6 +402,54 @@ private fun nextEdge( return best } +/** + * True when no two rings cross, touch or nest. Edges are filed in an [EdgeGrid] + * and each is tested only against the edges near it, so the cost grows with the + * edge count rather than its square. Same as js-sdk-core's `holesAreDisjoint`. + */ +private fun holesAreDisjoint(rings: List>): Boolean { + val boxes = rings.map(::ringBounds) + // A ring inside another: one of its vertices is inside it. + for (i in rings.indices) { + val p = rings[i][0] + for (j in rings.indices) { + if (i == j) continue + val b = boxes[j] + if (p.x >= b[0] && p.x <= b[2] && p.y >= b[1] && p.y <= b[3] && pointInRing(p, rings[j])) { + return false + } + } + } + + val edges = ArrayList() + val edgeRing = IntArrayList() + for ((r, ring) in rings.withIndex()) { + for (i in ring.indices) { + edges.add(Edge(ring[i], ring[(i + 1) % ring.size])) + edgeRing.add(r) + } + } + // Only an edge whose box comes within MEET_PAD of another's can meet it. + val grid = EdgeGrid(edges, MEET_PAD) + val near = IntArrayList() + for (i in edges.indices) { + val seg = edges[i] + grid.near( + minOf(seg.a.x, seg.b.x) - MEET_PAD, + minOf(seg.a.y, seg.b.y) - MEET_PAD, + maxOf(seg.a.x, seg.b.x) + MEET_PAD, + maxOf(seg.a.y, seg.b.y) + MEET_PAD, + near, + ) + for (k in 0 until near.size) { + val j = near[k] + if (j <= i || edgeRing[j] == edgeRing[i]) continue + if (intersectionPoints(seg, edges[j]).isNotEmpty()) return false + } + } + return true +} + /** 線分 `other` が線分 `seg` と出会う点(交差・T 字接触・共線重複の端点)。 */ private fun intersectionPoints( seg: Edge, @@ -250,11 +487,23 @@ private fun intersectionPoints( return listOf(add2(seg.a, scale(r, clamp01(t)))) } -/** 点を内部に含むリングの数。 */ +/** + * 点を内部に含むリングの数。緯度の範囲が点の緯度をまたがないリングには pointInRing が数える辺が + * 無いので飛ばす。 + */ private fun coverage( point: Vec, rings: List>, -): Int = rings.count { pointInRing(point, it) } + bounds: List, +): Int { + var count = 0 + for (i in rings.indices) { + val b = bounds[i] + if (point.y < b[1] || point.y >= b[3]) continue + if (pointInRing(point, rings[i])) count++ + } + return count +} /** 偶奇規則のレイキャスティングによる点包含判定(巻き方向に依存しない)。 */ private fun pointInRing( @@ -307,6 +556,21 @@ private fun toRing( return if (points.size >= 3) points else null } +/** リングの外接矩形 [minX, minY, maxX, maxY]。 */ +private fun ringBounds(ring: List): DoubleArray { + var minX = Double.POSITIVE_INFINITY + var minY = Double.POSITIVE_INFINITY + var maxX = Double.NEGATIVE_INFINITY + var maxY = Double.NEGATIVE_INFINITY + for (p in ring) { + if (p.x < minX) minX = p.x + if (p.x > maxX) maxX = p.x + if (p.y < minY) minY = p.y + if (p.y > maxY) maxY = p.y + } + return doubleArrayOf(minX, minY, maxX, maxY) +} + private fun signedArea(ring: List): Double { var area = 0.0 for (i in ring.indices) { diff --git a/src/main/java/com/mapconductor/core/polygon/PolygonManager.kt b/src/main/java/com/mapconductor/core/polygon/PolygonManager.kt index 90d0617..9d87e0c 100644 --- a/src/main/java/com/mapconductor/core/polygon/PolygonManager.kt +++ b/src/main/java/com/mapconductor/core/polygon/PolygonManager.kt @@ -1,13 +1,11 @@ package com.mapconductor.core.polygon import com.mapconductor.core.features.GeoPointInterface +import com.mapconductor.core.geometry.densifyPolygonRing import com.mapconductor.core.normalizeLng -import com.mapconductor.core.spherical.WGS84Geodesic import java.util.concurrent.ConcurrentHashMap -import kotlin.math.abs import kotlin.math.max import kotlin.math.min -import kotlin.math.sqrt interface PolygonManagerInterface { fun registerEntity(entity: PolygonEntityInterface) @@ -60,7 +58,7 @@ class PolygonManager : PolygonManagerInterface { // Densify edges to better approximate geodesic/linear edges val ring = try { - if (state.geodesic) WGS84Geodesic.createInterpolatePoints(basePoints) else basePoints + if (state.geodesic) densifyPolygonRing(basePoints, geodesic = true) else basePoints } catch (_: Exception) { basePoints } @@ -77,7 +75,7 @@ class PolygonManager : PolygonManagerInterface { if (hole.size < 3) continue val holeRing = try { - if (state.geodesic) WGS84Geodesic.createInterpolatePoints(hole) else hole + if (state.geodesic) densifyPolygonRing(hole, geodesic = true) else hole } catch (_: Exception) { hole } @@ -164,13 +162,17 @@ class PolygonManager : PolygonManagerInterface { by: Double, eps: Double, ): Boolean { + // 線分までの距離が eps(度)以内なら辺上とみなす。 + // 以前は外積と内積を eps と直接比べていた。内積は度の 2 乗なので、 + // `(p-a)·(p-b) <= 1e-6` は「辺の中点から約 0.001°(~100 m)以内」を意味し、 + // 短い辺を持つ建物ほど、離れたタップを辺上として拾っていた。 val dx = bx - ax val dy = by - ay - val cross = dx * (py - ay) - dy * (px - ax) - val segLen = sqrt(dx * dx + dy * dy) - if (abs(cross) > eps * max(1.0, segLen)) return false - val dot = (px - ax) * (px - bx) + (py - ay) * (py - by) - return dot <= eps * max(1.0, segLen) + val lenSq = dx * dx + dy * dy + val t = if (lenSq > 0.0) (((px - ax) * dx + (py - ay) * dy) / lenSq).coerceIn(0.0, 1.0) else 0.0 + val ex = px - (ax + t * dx) + val ey = py - (ay + t * dy) + return ex * ex + ey * ey <= eps * eps } private fun unwrapLongitudesAround( diff --git a/src/main/java/com/mapconductor/core/polygon/PolygonOverlay.kt b/src/main/java/com/mapconductor/core/polygon/PolygonOverlay.kt index adf1fb0..665c5e8 100644 --- a/src/main/java/com/mapconductor/core/polygon/PolygonOverlay.kt +++ b/src/main/java/com/mapconductor/core/polygon/PolygonOverlay.kt @@ -1,5 +1,6 @@ package com.mapconductor.core.polygon +import com.mapconductor.core.OverlayAddedTracker import com.mapconductor.core.controller.MapViewControllerInterface import com.mapconductor.core.map.MapOverlayInterface import kotlinx.coroutines.flow.StateFlow @@ -7,10 +8,16 @@ import kotlinx.coroutines.flow.StateFlow class PolygonOverlay( override val flow: StateFlow>, ) : MapOverlayInterface { + /** Calls [PolygonState.onAdded] once the map has the state. See [OverlayAddedTracker]. */ + private val added = OverlayAddedTracker { it.onAdded } + override suspend fun render( data: MutableMap, controller: MapViewControllerInterface, ) { - (controller as? PolygonCapableInterface)?.compositionPolygons(data.values.toList()) + val capable = controller as? PolygonCapableInterface ?: return + val states = data.values.toList() + capable.compositionPolygons(states) + added.synced(controller, states, capable::hasPolygon) } } diff --git a/src/main/java/com/mapconductor/core/polygon/PolygonTileGeometry.kt b/src/main/java/com/mapconductor/core/polygon/PolygonTileGeometry.kt new file mode 100644 index 0000000..c0290a1 --- /dev/null +++ b/src/main/java/com/mapconductor/core/polygon/PolygonTileGeometry.kt @@ -0,0 +1,330 @@ +package com.mapconductor.core.polygon + +import androidx.compose.ui.graphics.toArgb +import com.mapconductor.core.features.GeoPointInterface +import com.mapconductor.core.shapetile.ShapeGridIndex +import kotlin.math.PI +import kotlin.math.abs +import kotlin.math.floor +import kotlin.math.hypot +import kotlin.math.ln +import kotlin.math.max +import kotlin.math.min +import kotlin.math.sin + +// The geometry of polygon tiles, without any drawing: the same steps as the +// "Polygon tiles" section of js-sdk-core's tile-sw.js, so the three platforms +// draw the same pixels from the same polygons. +// +// Polygons become Web Mercator coordinates in [0, 1], with the outline wound +// one way and the holes the other, so a nonzero fill leaves out the union of +// the holes without computing it. +// +// Each zoom gets its own simplified copy of a polygon, built the first time a +// tile at that zoom needs it: vertices snapped to that zoom's pixel grid, +// repeats dropped, Douglas-Peucker at half a pixel, and a polygon smaller than +// a pixel drawn as one pixel. Taps never see any of this -- they are resolved +// against the original shapes in PolygonManager. + +/** Cells of the polygon index, in Web Mercator units: one z12 tile. */ +internal const val POLYGON_CELL = 1.0 / 4096.0 + +/** A polygon covering more cells than this is kept in a list every query checks. */ +internal const val POLYGON_MAX_CELLS = 256 + +internal const val DP_TOLERANCE_PX = 0.5 + +/** + * Below this size on screen a polygon's outline is left out: a 1 px line round + * a 3 px parcel is the whole parcel, and a city of them zoomed out turns into + * the outline colour. + */ +internal const val MIN_OUTLINED_PX = 4.0 + +private const val MAX_LATITUDE = 85.05112878 + +/** + * One polygon as the tiles draw it. + * + * [rings] are Web Mercator `[x0, y0, x1, y1, ...]` in [0, 1], the outline + * first and wound positive, every hole after it wound negative. [strokeWidth] + * is in dp, the unit of [PolygonState.strokeWidth]. + */ +internal class TilePolygon( + val rings: Array, + /** minX, minY, maxX, maxY of the outline. */ + val bbox: DoubleArray, + val fill: Int, + val stroke: Int, + val strokeWidth: Float, +) { + val fillVisible: Boolean get() = isVisibleColor(fill) + val strokeVisible: Boolean get() = strokeWidth > 0f && isVisibleColor(stroke) + + fun sameBox(other: TilePolygon): Boolean = bbox.contentEquals(other.bbox) + + companion object { + /** Null when the outline has fewer than three points. */ + fun from(state: PolygonState): TilePolygon? { + val rings = ArrayList(1 + state.holes.size) + val all = listOf(state.points) + state.holes + for ((r, points) in all.withIndex()) { + var ring = toMercatorRing(points) + if (ring.size < 6) { + if (r == 0) return null + continue + } + // Outline positive, holes negative: opposite windings under nonzero. + val area = signedArea(ring) + if ((r == 0 && area < 0) || (r > 0 && area > 0)) ring = reversedRing(ring) + rings.add(ring) + } + val outer = rings[0] + var minX = Double.POSITIVE_INFINITY + var minY = Double.POSITIVE_INFINITY + var maxX = Double.NEGATIVE_INFINITY + var maxY = Double.NEGATIVE_INFINITY + var i = 0 + while (i < outer.size) { + minX = min(minX, outer[i]) + maxX = max(maxX, outer[i]) + minY = min(minY, outer[i + 1]) + maxY = max(maxY, outer[i + 1]) + i += 2 + } + return TilePolygon( + rings = rings.toTypedArray(), + bbox = doubleArrayOf(minX, minY, maxX, maxY), + fill = state.fillColor.toArgb(), + stroke = state.strokeColor.toArgb(), + strokeWidth = state.strokeWidth.value, + ) + } + } +} + +internal fun isVisibleColor(argb: Int): Boolean = (argb ushr 24) != 0 + +internal fun toMercatorRing(points: List): DoubleArray { + val ring = DoubleArray(points.size * 2) + for ((i, p) in points.withIndex()) { + val lat = p.latitude.coerceIn(-MAX_LATITUDE, MAX_LATITUDE) + val s = sin(lat * PI / 180.0) + ring[i * 2] = (p.longitude + 180.0) / 360.0 + ring[i * 2 + 1] = 0.5 - ln((1 + s) / (1 - s)) / (4 * PI) + } + return ring +} + +internal fun signedArea(ring: DoubleArray): Double { + var area = 0.0 + val n = ring.size / 2 + var j = n - 1 + for (i in 0 until n) { + area += ring[j * 2] * ring[i * 2 + 1] - ring[i * 2] * ring[j * 2 + 1] + j = i + } + return area / 2 +} + +internal fun reversedRing(ring: DoubleArray): DoubleArray { + val n = ring.size / 2 + val out = DoubleArray(ring.size) + for (i in 0 until n) { + out[i * 2] = ring[(n - 1 - i) * 2] + out[i * 2 + 1] = ring[(n - 1 - i) * 2 + 1] + } + return out +} + +/** + * The polygon index: polygons by the grid cells their bounding box covers. + * The grid itself is [ShapeGridIndex], shared with the polyline tiles. + */ +internal class PolygonGridIndex( + private val cells: HashMap, + private val large: IntArray, +) { + private var grid = ShapeGridIndex(cells, large) + + /** + * The polygons whose bounding box meets the given box, each once, in + * ascending index order -- which is draw order. + */ + fun query( + polygons: Array, + minX: Double, + minY: Double, + maxX: Double, + maxY: Double, + ): IntArray = grid.query({ polygons[it]?.bbox }, minX, minY, maxX, maxY) + + companion object { + fun build(polygons: Array): PolygonGridIndex { + val grid = ShapeGridIndex.build(polygons.size) { polygons[it]?.bbox } + return PolygonGridIndex(grid.cells, grid.large).apply { this.grid = grid } + } + } +} + +/** What one polygon looks like at one zoom. */ +internal sealed class TileShape { + /** World-pixel rings at the zoom, `[x0, y0, ...]`, outline first. */ + class Rings( + val rings: Array, + val outlined: Boolean, + ) : TileShape() + + /** A polygon under a pixel, drawn as the pixel at [x], [y]. */ + class Dot( + val x: Double, + val y: Double, + ) : TileShape() +} + +/** + * The polygon as drawn at a zoom whose world is [scale] pixels wide: rings of + * world-pixel points, a dot for a polygon under a pixel, never nothing. + */ +internal fun simplifyPolygon( + p: TilePolygon, + scale: Double, +): TileShape { + val w = (p.bbox[2] - p.bbox[0]) * scale + val h = (p.bbox[3] - p.bbox[1]) * scale + if (w < 1 && h < 1) { + return TileShape.Dot( + floor(((p.bbox[0] + p.bbox[2]) / 2) * scale), + floor(((p.bbox[1] + p.bbox[3]) / 2) * scale), + ) + } + val outer = + simplifyRing(p.rings[0], scale) + ?: return TileShape.Dot( + jsRound(((p.bbox[0] + p.bbox[2]) / 2) * scale), + jsRound(((p.bbox[1] + p.bbox[3]) / 2) * scale), + ) + val rings = ArrayList(p.rings.size) + rings.add(outer) + for (r in 1 until p.rings.size) { + simplifyRing(p.rings[r], scale)?.let(rings::add) + } + return TileShape.Rings(rings.toTypedArray(), outlined = max(w, h) >= MIN_OUTLINED_PX) +} + +/** Snapped to the pixel grid, repeats dropped, Douglas-Peucker; null under three points. */ +internal fun simplifyRing( + ring: DoubleArray, + scale: Double, +): DoubleArray? { + val snapped = DoubleArray(ring.size) + var n = 0 + var px = Double.NaN + var py = Double.NaN + var i = 0 + while (i < ring.size) { + val x = jsRound(ring[i] * scale) + val y = jsRound(ring[i + 1] * scale) + i += 2 + if (x == px && y == py) continue + snapped[n++] = x + snapped[n++] = y + px = x + py = y + } + val simplified = douglasPeucker(snapped, n / 2, DP_TOLERANCE_PX) + return if (simplified.size >= 6) simplified else null +} + +/** `Math.round` as JavaScript has it (halves go up), so pixels land where tile-sw.js puts them. */ +private fun jsRound(v: Double): Double = floor(v + 0.5) + +/** Douglas-Peucker on the first [n] points of [points]; returns the kept points. */ +internal fun douglasPeucker( + points: DoubleArray, + n: Int, + tolerance: Double, +): DoubleArray { + if (n < 3) return points.copyOf(n * 2) + val keep = BooleanArray(n) + keep[0] = true + keep[n - 1] = true + val stack = IntList() + stack.add(0) + stack.add(n - 1) + while (stack.size > 0) { + val b = stack.pop() + val a = stack.pop() + val ax = points[a * 2] + val ay = points[a * 2 + 1] + val dx = points[b * 2] - ax + val dy = points[b * 2 + 1] - ay + val len = hypot(dx, dy) + var best = -1.0 + var bestIndex = -1 + for (i in a + 1 until b) { + val px = points[i * 2] + val py = points[i * 2 + 1] + val d = if (len != 0.0) abs(dy * (px - ax) - dx * (py - ay)) / len else hypot(px - ax, py - ay) + if (d > best) { + best = d + bestIndex = i + } + } + if (best > tolerance) { + keep[bestIndex] = true + stack.add(a) + stack.add(bestIndex) + stack.add(bestIndex) + stack.add(b) + } + } + var kept = 0 + for (k in keep) if (k) kept++ + val out = DoubleArray(kept * 2) + var o = 0 + for (i in 0 until n) { + if (keep[i]) { + out[o++] = points[i * 2] + out[o++] = points[i * 2 + 1] + } + } + return out +} + +/** Total vertices across outlines and holes. */ +internal fun vertexCountOf(states: List): Int { + var n = 0 + for (s in states) { + n += s.points.size + for (h in s.holes) n += h.size + } + return n +} + +/** A growable int array, so indexes do not box every polygon index. */ +internal class IntList( + capacity: Int = 8, +) { + private var data = IntArray(capacity) + var size = 0 + private set + + fun add(v: Int) { + if (size == data.size) data = data.copyOf(max(8, size * 2)) + data[size++] = v + } + + fun pop(): Int = data[--size] + + fun toArray(): IntArray = data.copyOf(size) + + fun toSortedDistinctArray(): IntArray { + if (size == 0) return IntArray(0) + val a = data.copyOf(size) + a.sort() + var n = 1 + for (i in 1 until a.size) if (a[i] != a[n - 1]) a[n++] = a[i] + return if (n == a.size) a else a.copyOf(n) + } +} diff --git a/src/main/java/com/mapconductor/core/polygon/PolygonTileRenderer.kt b/src/main/java/com/mapconductor/core/polygon/PolygonTileRenderer.kt new file mode 100644 index 0000000..3424ca4 --- /dev/null +++ b/src/main/java/com/mapconductor/core/polygon/PolygonTileRenderer.kt @@ -0,0 +1,177 @@ +package com.mapconductor.core.polygon + +import com.mapconductor.core.InternalMapConductorApi +import com.mapconductor.core.ResourceProvider +import com.mapconductor.core.shapetile.GlShapeScene +import com.mapconductor.core.shapetile.ShapeTileRenderer +import com.mapconductor.core.shapetile.toTilePixels +import com.mapconductor.core.tileserver.TileProviderInterface +import com.mapconductor.core.tileserver.TileRequest +import android.graphics.Bitmap +import android.graphics.Canvas +import android.graphics.Path + +/** + * Draws a set of polygons into raster tiles: the counterpart of the polygon + * part of js-sdk-core's tile-sw.js "Shape tiles", served by + * [com.mapconductor.core.tileserver.LocalTileServer]. + * + * The tiles themselves (index, per-zoom simplification, cache, invalidation, + * scratch bitmaps, encoding, cancellation) are [ShapeTileRenderer]'s, shared + * with the polyline tiles; this is how a polygon is drawn in one: filled + * nonzero, the outline only stroked (never the holes), a polygon under + * [MIN_OUTLINED_PX] without its outline, and one under a pixel as the pixel. + * + * Geometry is in tile units (a tile is [tileSize] wide whatever its pixels); + * a tile is drawn [pixelScale] pixels per unit, so a stroke of 1 dp is one + * unit wide, as on the web where it is one CSS pixel. + */ +internal class PolygonTileRenderer( + val tileSize: Int = 256, + cacheSizeBytes: Int = DEFAULT_CACHE_BYTES, + pixelScale: () -> Float = { ResourceProvider.getDensity() }, +) : TileProviderInterface { + /** The shared renderer this one draws with; what the tile server is given. */ + internal val shapes: ShapeTileRenderer = + ShapeTileRenderer(tileSize, cacheSizeBytes, pixelScale, PolygonTilePainter) { TileRenderCancelled() } + + /** Replaces every polygon. Draw order is list order. */ + fun setPolygons(polygons: List) = shapes.setItems(polygons) + + /** + * Replaces the polygons at the given indexes. Only the tiles that + * overlapped one of them, before or after, are drawn again. + */ + fun update(updates: List>) = shapes.update(updates) + + fun clear() = shapes.clear() + + override fun renderTile(request: TileRequest): ByteArray? = shapes.renderTile(request) + + override fun renderTile( + request: TileRequest, + isCancelled: () -> Boolean, + ): ByteArray? = shapes.renderTile(request, isCancelled) + + /** The tile as a bitmap, or null when nothing of any polygon is in it. For tests. */ + fun renderBitmap( + x: Int, + y: Int, + z: Int, + pixelRatio: Int = 1, + ): Bitmap? = shapes.renderBitmap(x, y, z, pixelRatio) + + /** Thrown when the map stops wanting a tile mid-draw: a failure it may retry, never an empty tile. */ + class TileRenderCancelled : Exception("polygon tile no longer wanted") + + companion object { + const val DEFAULT_CACHE_BYTES = ShapeTileRenderer.DEFAULT_CACHE_BYTES + } +} + +/** How a polygon is drawn in a shape tile. */ +@InternalMapConductorApi +internal object PolygonTilePainter : ShapeTileRenderer.Painter { + override fun bbox(item: TilePolygon): DoubleArray = item.bbox + + override fun strokeWidth(item: TilePolygon): Float = if (item.strokeVisible) item.strokeWidth else 0f + + override fun simplify( + item: TilePolygon, + scale: Double, + ): Any = simplifyPolygon(item, scale) + + override fun draw( + canvas: Canvas, + item: TilePolygon, + shape: Any, + originX: Double, + originY: Double, + r: Float, + paints: ShapeTileRenderer.Paints, + ): Boolean { + val fillVisible = item.fillVisible + var drew = false + when (shape) { + is TileShape.Dot -> { + if (!fillVisible && !item.strokeVisible) return false + paints.dot.color = if (fillVisible) item.fill else item.stroke + val left = ((shape.x - originX) * r).toFloat() + val top = ((shape.y - originY) * r).toFloat() + canvas.drawRect(left, top, left + r, top + r, paints.dot) + drew = true + } + is TileShape.Rings -> { + val path = paints.path + if (fillVisible) { + path.rewind() + path.fillType = Path.FillType.WINDING + for (ring in shape.rings) addRing(path, ring, originX, originY, r) + paints.fill.color = item.fill + canvas.drawPath(path, paints.fill) + drew = true + } + if (item.strokeVisible && shape.outlined) { + // Outline only, as the map SDKs draw it. + path.rewind() + addRing(path, shape.rings[0], originX, originY, r) + paints.stroke.color = item.stroke + paints.stroke.strokeWidth = item.strokeWidth * r + canvas.drawPath(path, paints.stroke) + drew = true + } + } + } + return drew + } + + override val drawsOnGpu: Boolean get() = ShapeTileRenderer.gpuPolygonsAndLines + + override fun record( + scene: GlShapeScene, + item: TilePolygon, + shape: Any, + originX: Double, + originY: Double, + r: Float, + ): Boolean { + val fillVisible = item.fillVisible + when (shape) { + is TileShape.Dot -> { + if (!fillVisible && !item.strokeVisible) return false + val left = ((shape.x - originX) * r).toFloat() + val top = ((shape.y - originY) * r).toFloat() + scene.addCircle(left, top, r, r, if (fillVisible) item.fill else item.stroke, 0, kind = 1) + return true + } + is TileShape.Rings -> { + val outlined = item.strokeVisible && shape.outlined + if (!fillVisible && !outlined) return false + scene.addPolygon( + shape.rings.map { toTilePixels(it, originX, originY, r) }, + fill = if (fillVisible) item.fill else 0, + outline = if (outlined) item.stroke else 0, + strokeWidth = item.strokeWidth * r, + ) + return true + } + } + return false + } + + private fun addRing( + path: Path, + ring: DoubleArray, + originX: Double, + originY: Double, + r: Float, + ) { + path.moveTo(((ring[0] - originX) * r).toFloat(), ((ring[1] - originY) * r).toFloat()) + var i = 2 + while (i < ring.size) { + path.lineTo(((ring[i] - originX) * r).toFloat(), ((ring[i + 1] - originY) * r).toFloat()) + i += 2 + } + path.close() + } +} diff --git a/src/main/java/com/mapconductor/core/polygon/PolygonTileSet.kt b/src/main/java/com/mapconductor/core/polygon/PolygonTileSet.kt new file mode 100644 index 0000000..15f8417 --- /dev/null +++ b/src/main/java/com/mapconductor/core/polygon/PolygonTileSet.kt @@ -0,0 +1,101 @@ +package com.mapconductor.core.polygon + +import com.mapconductor.core.shapetile.ShapeTileSet +import com.mapconductor.core.tileserver.LocalTileServer +import com.mapconductor.core.tileserver.TileServerRegistry +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob + +/** + * The polygons of one map that are drawn as raster tiles, and their route on + * the local tile server. + * + * Provider-independent: a provider decides which polygons to tile + * ([PolygonTilingOptions.shouldUseTiles], [canTile]), hands them to + * [setPolygons], and shows the returned URL template as a raster layer. + * In-place changes go through [update]; each one ends in a new template (the + * version in it is what makes the map ask again), reported to + * [onTemplateChanged]. Tiles the change did not touch are still cached by the + * renderer and come back without being drawn again. + * + * The route, its version and the coalescing of changes are + * [ShapeTileSet]'s, shared with [com.mapconductor.core.polyline.PolylineTileSet]. + * + * Same shape as js-sdk-core's `PolygonTileSet`. The web draws in its tile + * service worker and hands the polygons over as Encoded Polylines; here the + * server is in the process, so the renderer reads the states directly. + */ +class PolygonTileSet( + server: LocalTileServer = TileServerRegistry.get(), + scope: CoroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Default), +) { + internal val shapes: ShapeTileSet = + ShapeTileSet( + routePrefix = "polygons", + server = server, + scope = scope, + renderer = PolygonTileRenderer(TILE_SIZE).shapes, + idOf = { it.id }, + zIndexOf = { it.zIndex }, + toTile = TilePolygon::from, + ) + + val routeId: String get() = shapes.routeId + + /** Called with the new template after an [update]. */ + var onTemplateChanged: (suspend (String) -> Unit)? + get() = shapes.onTemplateChanged + set(value) { + shapes.onTemplateChanged = value + } + + val tileSize: Int get() = TILE_SIZE + + /** + * Registers [states] (replacing whatever was registered) and returns the + * URL template of their tiles. + */ + suspend fun setPolygons(states: List): String = shapes.setShapes(states) + + fun has(id: String): Boolean = shapes.has(id) + + /** + * One polygon changed in place. A change of zIndex reorders the list and + * needs [setPolygons] instead; everything else is applied here. + */ + fun update(state: PolygonState) = shapes.update(state) + + /** + * Takes one polygon out of the tiles. Its slot in the renderer's list is + * left empty, so the others keep their indices and only the tiles it was + * in are drawn again. + */ + fun remove(id: String) = shapes.remove(id) + + fun template(): String = shapes.template() + + fun dispose() = shapes.dispose() + + companion object { + private const val TILE_SIZE = 256 + + /** + * Whether a polygon can be drawn in a tile. Geodesic edges are curves + * the tile does not trace, and a ring spanning half the world or more + * crosses the antimeridian; the map SDK draws both. + */ + fun canTile(state: PolygonState): Boolean { + if (state.geodesic || state.points.size < 3) return false + var min = Double.POSITIVE_INFINITY + var max = Double.NEGATIVE_INFINITY + for (p in state.points) { + if (p.longitude < min) min = p.longitude + if (p.longitude > max) max = p.longitude + } + return max - min < 180 + } + + fun vertexCount(states: List): Int = vertexCountOf(states) + } +} diff --git a/src/main/java/com/mapconductor/core/polygon/PolygonTiler.kt b/src/main/java/com/mapconductor/core/polygon/PolygonTiler.kt new file mode 100644 index 0000000..ef060e8 --- /dev/null +++ b/src/main/java/com/mapconductor/core/polygon/PolygonTiler.kt @@ -0,0 +1,82 @@ +package com.mapconductor.core.polygon + +import com.mapconductor.core.raster.RasterLayerSource +import com.mapconductor.core.raster.RasterLayerState +import com.mapconductor.core.shapetile.ShapeTiler + +/** The id of the raster layer that shows tiled polygons. */ +const val POLYGON_TILE_LAYER_ID: String = "mc-polygon-tiles" + +/** The raster layer state for tiled polygons at [template]. */ +fun polygonTileRasterLayerState( + template: String, + tileSize: Int = 256, +): RasterLayerState = + RasterLayerState( + id = POLYGON_TILE_LAYER_ID, + source = RasterLayerSource.UrlTemplate(template = template, tileSize = tileSize), + ) + +/** + * Decides which of a map's polygons are drawn as tiles, keeps them registered + * with the local tile server, and tells the provider where the tiles are. + * + * Every provider's polygon controller uses it the same way: + * 1. [route] with the full list on every composition. It returns the ids now + * in tiles; the controller keeps those in its [PolygonManager] (taps are + * resolved there, against the original shapes) but gives the map SDK + * nothing for them, and removes any native polygon it had drawn for one. + * 2. [update] for an in-place change of a tiled polygon, or [remove] when the + * change means it can no longer be tiled. + * 3. [onTemplate] is how the tiles reach the map: a URL template to show as a + * raster layer, or null to remove it. A provider with a RasterLayer + * controller hands [polygonTileRasterLayerState] to its `upsert`, and + * removes it with `removeById(POLYGON_TILE_LAYER_ID)`. + * + * The routing is [ShapeTiler]'s, shared with [com.mapconductor.core.polyline.PolylineTiler]. + * + * Same as js-sdk-core's and ios-sdk-core's `PolygonTiler`. + */ +class PolygonTiler( + val options: PolygonTilingOptions = PolygonTilingOptions.Default, +) { + var onTemplate: (suspend (template: String?, tileSize: Int) -> Unit)? = null + + private val tiler = + ShapeTiler( + tileSet = PolygonTileSet().shapes, + canTile = PolygonTileSet::canTile, + vertexCount = PolygonTileSet::vertexCount, + shouldUseTiles = { count, vertices -> options.shouldUseTiles(count, vertices) }, + idOf = { it.id }, + onTemplate = { template, tileSize -> onTemplate?.invoke(template, tileSize) }, + ) + + /** Re-decides tiling for [data] and returns the ids drawn as tiles. */ + suspend fun route(data: List): Set = tiler.route(data) + + /** The states drawn as tiles, as of the last [route]. */ + fun tiledStates(): List = tiler.tiledStates() + + fun isTiled(id: String): Boolean = tiler.isTiled(id) + + /** An in-place change of a tiled polygon; only the tiles it touches are drawn again. */ + fun update(state: PolygonState) = tiler.update(state) + + internal suspend fun reorder(state: PolygonState) = tiler.reorder(state) + + /** + * Takes one polygon out of the tiles, for a change that left it no longer + * [PolygonTileSet.canTile]; only the tiles it was in are drawn again. The + * controller then hands it to the map SDK. + */ + fun remove(id: String) = tiler.remove(id) + + /** + * Releases the tiles when the map goes away. Unlike [clear], it does not + * call [onTemplate]: there is no map left to remove the layer from. + */ + fun dispose() = tiler.dispose() + + suspend fun clear() = tiler.clear() +} diff --git a/src/main/java/com/mapconductor/core/polygon/PolygonTilingOptions.kt b/src/main/java/com/mapconductor/core/polygon/PolygonTilingOptions.kt new file mode 100644 index 0000000..8f6644e --- /dev/null +++ b/src/main/java/com/mapconductor/core/polygon/PolygonTilingOptions.kt @@ -0,0 +1,31 @@ +package com.mapconductor.core.polygon + +/** + * Options for polygon tiling. + * + * When enabled and a map holds enough polygons, they are drawn into raster + * tiles by the SDK's local tile server instead of being handed to the map SDK + * one by one. Taps are still resolved against the original shapes in + * [PolygonManager], so tiling changes how polygons look, never what a tap hits. + * + * The counterpart of [com.mapconductor.core.marker.MarkerTilingOptions], and + * the same options as js-sdk-core's and ios-sdk-core's `PolygonTilingOptions`. + */ +data class PolygonTilingOptions( + val enabled: Boolean = true, + /** Tile once a map holds at least this many polygons… */ + val minPolygonCount: Int = 2000, + /** …or at least this many vertices across them, whichever comes first. */ + val minVertexCount: Int = 50_000, +) { + /** The one place the threshold is decided; callers must not restate it. */ + fun shouldUseTiles( + polygonCount: Int, + vertexCount: Int, + ): Boolean = enabled && (polygonCount >= minPolygonCount || vertexCount >= minVertexCount) + + companion object { + val Default: PolygonTilingOptions = PolygonTilingOptions() + val Disabled: PolygonTilingOptions = PolygonTilingOptions(enabled = false) + } +} diff --git a/src/main/java/com/mapconductor/core/polyline/Polyline.kt b/src/main/java/com/mapconductor/core/polyline/Polyline.kt index 5b2a4a1..12440fd 100644 --- a/src/main/java/com/mapconductor/core/polyline/Polyline.kt +++ b/src/main/java/com/mapconductor/core/polyline/Polyline.kt @@ -1,144 +1,233 @@ -package com.mapconductor.core.polyline - -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.setValue -import androidx.compose.runtime.snapshotFlow -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.unit.Dp -import androidx.compose.ui.unit.dp -import com.mapconductor.core.ComponentState -import com.mapconductor.core.features.GeoPointInterface -import java.io.Serializable -import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.flow.distinctUntilChanged - -class PolylineState( - points: List, - id: String? = null, - strokeColor: Color = Color.Black, - strokeWidth: Dp = 1.dp, - geodesic: Boolean = false, - clickable: Boolean = true, - zIndex: Int = 0, - extra: Serializable? = null, - onClick: OnPolylineEventHandler? = null, -) : ComponentState { - override val id = - ( - id ?: polylineId( - listOf( - listHashCode(points), - strokeColor.hashCode(), - strokeWidth.hashCode(), - geodesic.hashCode(), - clickable.hashCode(), - extra?.hashCode() ?: 0, - ), - ) - ).toString() - var strokeColor by mutableStateOf(strokeColor) - var strokeWidth by mutableStateOf(strokeWidth) - var geodesic by mutableStateOf(geodesic) - - /** - * タップを受け取るか。`false` ならこのポリラインはタップに対して透過し、 - * 下のオーバーレイ(無ければ地図クリック)へイベントが流れる。 - * - * 判定はコアの [com.mapconductor.core.polyline.PolylineManager.find] が行うため、 - * どのプロバイダでも同じ挙動になる。描画には影響しないので [fingerPrint] には - * 含めない(含めると値を変えるたびにオーバーレイが作り直される)。 - */ - var clickable by mutableStateOf(clickable) - var zIndex by mutableStateOf(zIndex) - var points by mutableStateOf>(points) - var extra by mutableStateOf(extra) - var onClick by mutableStateOf(onClick) - - private fun polylineId(hashCodes: List): Int = - hashCodes.reduce { result, hashCode -> - 31 * result + hashCode - } - - override fun equals(other: Any?): Boolean { - val otherState = (other as? PolylineState) ?: return false - return hashCode() == otherState.hashCode() - } - - override fun hashCode(): Int { - var result = extra?.hashCode() ?: 0 - result = 31 * result + this@PolylineState.strokeColor.hashCode() - result = 31 * result + this@PolylineState.strokeWidth.hashCode() - result = 31 * result + geodesic.hashCode() - result = 31 * result + clickable.hashCode() - result = 31 * result + zIndex.hashCode() - result = 31 * result + listHashCode(points) - return result - } - - fun copy( - points: List = this.points, - id: String? = this.id, - strokeColor: Color = this.strokeColor, - strokeWidth: Dp = this.strokeWidth, - geodesic: Boolean = this.geodesic, - clickable: Boolean = this.clickable, - zIndex: Int = this.zIndex, - extra: Serializable? = this.extra, - onClick: OnPolylineEventHandler? = this.onClick, - ): PolylineState = - PolylineState( - points = points, - id = id, - strokeColor = strokeColor, - strokeWidth = strokeWidth, - geodesic = geodesic, - clickable = clickable, - zIndex = zIndex, - extra = extra, - onClick = onClick, - ) - - private fun listHashCode(list: List): Int { - var result = 0 - list.forEach { - result = 31 * result + it.hashCode() - } - return result - } - - fun fingerPrint(): PolylineFingerPrint = - PolylineFingerPrint( - id = this.id.hashCode(), - strokeColor = this@PolylineState.strokeColor.hashCode(), - strokeWidth = this@PolylineState.strokeWidth.hashCode(), - geodesic = geodesic.hashCode(), - zIndex = zIndex.hashCode(), - points = listHashCode(points), - extra = extra?.hashCode() ?: 0, - ) - - fun asFlow(): Flow = snapshotFlow { fingerPrint() }.distinctUntilChanged() -} - -data class PolylineFingerPrint( - val id: Int, - val strokeColor: Int, - val strokeWidth: Int, - val geodesic: Int, - val zIndex: Int, - val points: Int, - val extra: Int, -) - -class PolylineEvent( - val state: PolylineState, - clicked: GeoPointInterface, -) { - // 生成時に wrap して [-180,180] / [-90,90] に正規化する(日付変更線対策)。 - // 正規化をここ(イベント型=出口)に一元化することで、コア/独自 Conductor/将来のプロバイダの - // どの配送経路を通っても wrap 漏れが起きない。ヒットテストの入力座標は wrap しないこと。 - val clicked: GeoPointInterface = clicked.wrap() -} - -typealias OnPolylineEventHandler = (PolylineEvent) -> Unit +package com.mapconductor.core.polyline + +import androidx.compose.runtime.getValue +import androidx.compose.runtime.setValue +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import com.mapconductor.core.ComponentState +import com.mapconductor.core.StateMutationSignal +import com.mapconductor.core.features.GeoPointInterface +import java.io.Serializable + +class PolylineState( + points: List, + id: String? = null, + strokeColor: Color = Color.Black, + strokeWidth: Dp = 1.dp, + geodesic: Boolean = false, + clickable: Boolean = true, + zIndex: Int = 0, + extra: Serializable? = null, + onClick: OnPolylineEventHandler? = null, + onAdded: OnPolylineAddedHandler? = null, +) : ComponentState { + override val id = + ( + id ?: polylineId( + listOf( + listHashCode(points), + strokeColor.hashCode(), + strokeWidth.hashCode(), + geodesic.hashCode(), + clickable.hashCode(), + extra?.hashCode() ?: 0, + ), + ) + ).toString() + + /** + * Writes to the fields below are announced here rather than discovered by + * reading them all back. See [StateMutationSignal]. + */ + override val mutations = StateMutationSignal() + + var strokeColor by mutations.notifying(strokeColor) + var strokeWidth by mutations.notifying(strokeWidth) + var geodesic by mutations.notifying(geodesic) + + /** + * タップを受け取るか。`false` ならこのポリラインはタップに対して透過し、 + * 下のオーバーレイ(無ければ地図クリック)へイベントが流れる。 + * + * 判定はコアの [com.mapconductor.core.polyline.PolylineManager.find] が行うため、 + * どのプロバイダでも同じ挙動になる。描画には影響しないので [fingerPrint] には + * 含めない(含めると値を変えるたびにオーバーレイが作り直される)。 + */ + var clickable by mutations.notifying(clickable) + var zIndex by mutations.notifying(zIndex) + + /** + * 線の頂点。 + * + * state が見ているのはこのプロパティへの代入だけ。渡したリストをその場で書き換えても + * 描き直されない(`mutableStateListOf` を渡して `add` / `set` する使い方は効かない)。 + * 形を変えるときは新しいリストを代入する: + * + * ``` + * polylineState.points = polylineState.points + nextPoint + * ``` + * + * 内容の等しいリストの代入は無視される。その場で書き換えた同じリストを代入し直しても、 + * 前の値と同じものなので何も起きない。 + */ + var points by mutations.notifying>(points) + var extra by mutations.notifying(extra) + var onClick by mutations.notifying(onClick) + + /** + * Called once each time this polyline goes from not being on the map to being on it: + * after the map SDK's object for it has been created, or, when it is drawn in tiles, + * after the URL template of those tiles has been handed to the map as a raster layer + * (the tile images may still be loading then). Not called for an in-place change, + * nor when it moves between native drawing and tiles while staying on the map; + * called again if it is removed and added again. Clearing or destroying the map calls + * nothing. + * + * Runs on the main thread once the map has finished adding the overlays it was given. + * A callback that throws is logged and does not stop the other overlays' callbacks. + * + * Like `onClick`, it is not part of the id, fingerprint, equality or hash: replacing + * it redraws nothing. If the same state is shown on two maps, each map calls it. + */ + var onAdded: OnPolylineAddedHandler? = onAdded + + @Deprecated("Binary compatibility only; use the overload with onAdded.", level = DeprecationLevel.HIDDEN) + constructor( + points: List, + id: String? = null, + strokeColor: Color = Color.Black, + strokeWidth: Dp = 1.dp, + geodesic: Boolean = false, + clickable: Boolean = true, + zIndex: Int = 0, + extra: Serializable? = null, + onClick: OnPolylineEventHandler? = null, + ) : this( + points, + id, + strokeColor, + strokeWidth, + geodesic, + clickable, + zIndex, + extra, + onClick, + null, + ) + + private fun polylineId(hashCodes: List): Int = + hashCodes.reduce { result, hashCode -> + 31 * result + hashCode + } + + override fun equals(other: Any?): Boolean { + val otherState = (other as? PolylineState) ?: return false + return hashCode() == otherState.hashCode() + } + + override fun hashCode(): Int { + var result = extra?.hashCode() ?: 0 + result = 31 * result + this@PolylineState.strokeColor.hashCode() + result = 31 * result + this@PolylineState.strokeWidth.hashCode() + result = 31 * result + geodesic.hashCode() + result = 31 * result + clickable.hashCode() + result = 31 * result + zIndex.hashCode() + result = 31 * result + listHashCode(points) + return result + } + + fun copy( + points: List = this.points, + id: String? = this.id, + strokeColor: Color = this.strokeColor, + strokeWidth: Dp = this.strokeWidth, + geodesic: Boolean = this.geodesic, + clickable: Boolean = this.clickable, + zIndex: Int = this.zIndex, + extra: Serializable? = this.extra, + onClick: OnPolylineEventHandler? = this.onClick, + onAdded: OnPolylineAddedHandler? = this.onAdded, + ): PolylineState = + PolylineState( + points = points, + id = id, + strokeColor = strokeColor, + strokeWidth = strokeWidth, + geodesic = geodesic, + clickable = clickable, + zIndex = zIndex, + extra = extra, + onClick = onClick, + onAdded = onAdded, + ) + + @Deprecated("Binary compatibility only; use the overload with onAdded.", level = DeprecationLevel.HIDDEN) + fun copy( + points: List = this.points, + id: String? = this.id, + strokeColor: Color = this.strokeColor, + strokeWidth: Dp = this.strokeWidth, + geodesic: Boolean = this.geodesic, + clickable: Boolean = this.clickable, + zIndex: Int = this.zIndex, + extra: Serializable? = this.extra, + onClick: OnPolylineEventHandler? = this.onClick, + ): PolylineState = + copy( + points, + id, + strokeColor, + strokeWidth, + geodesic, + clickable, + zIndex, + extra, + onClick, + onAdded, + ) + + private fun listHashCode(list: List): Int { + var result = 0 + list.forEach { + result = 31 * result + it.hashCode() + } + return result + } + + fun fingerPrint(): PolylineFingerPrint = + PolylineFingerPrint( + id = this.id.hashCode(), + strokeColor = this@PolylineState.strokeColor.hashCode(), + strokeWidth = this@PolylineState.strokeWidth.hashCode(), + geodesic = geodesic.hashCode(), + zIndex = zIndex.hashCode(), + points = listHashCode(points), + extra = extra?.hashCode() ?: 0, + ) +} + +data class PolylineFingerPrint( + val id: Int, + val strokeColor: Int, + val strokeWidth: Int, + val geodesic: Int, + val zIndex: Int, + val points: Int, + val extra: Int, +) + +class PolylineEvent( + val state: PolylineState, + clicked: GeoPointInterface, +) { + // 生成時に wrap して [-180,180] / [-90,90] に正規化する(日付変更線対策)。 + // 正規化をここ(イベント型=出口)に一元化することで、コア/独自 Conductor/将来のプロバイダの + // どの配送経路を通っても wrap 漏れが起きない。ヒットテストの入力座標は wrap しないこと。 + val clicked: GeoPointInterface = clicked.wrap() +} + +typealias OnPolylineEventHandler = (PolylineEvent) -> Unit + +/** Receives the state whose polyline was just added to the map. See [PolylineState.onAdded]. */ +typealias OnPolylineAddedHandler = (PolylineState) -> Unit diff --git a/src/main/java/com/mapconductor/core/polyline/PolylineController.kt b/src/main/java/com/mapconductor/core/polyline/PolylineController.kt index d5080cd..761ba9f 100644 --- a/src/main/java/com/mapconductor/core/polyline/PolylineController.kt +++ b/src/main/java/com/mapconductor/core/polyline/PolylineController.kt @@ -6,8 +6,10 @@ import com.mapconductor.core.controller.OverlayKind import com.mapconductor.core.controller.SlottedOverlayController import com.mapconductor.core.features.GeoPointInterface import com.mapconductor.core.map.MapCameraPosition +import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.sync.Semaphore import kotlinx.coroutines.sync.withPermit +import kotlinx.coroutines.withContext abstract class PolylineController( val polylineManager: PolylineManagerInterface, @@ -23,6 +25,15 @@ abstract class PolylineController( var clickListener: OnPolylineEventHandler? = null + /** + * Set by a provider that can show polyline tiles (see [PolylineTiler]). + * Polylines it tiles stay in [polylineManager], for taps, with no native + * overlay: their entity's `polyline` is null and the renderer never sees + * them. A renderer that redraws from the manager must skip those. + */ + var tiler: PolylineTiler? = null + private var tiledIds: Set = emptySet() + fun dispatchClick(event: PolylineEvent) { // 配送座標の wrap は PolylineEvent の生成時に一元化済み。 event.state.onClick?.invoke(event) @@ -31,15 +42,25 @@ abstract class PolylineController( override suspend fun add(data: List) { semaphore.withPermit { + val wasTiled = tiledIds + val tiled = tiler?.route(data) ?: emptySet() + tiledIds = tiled + val native = if (tiled.isEmpty()) data else data.filter { it.id !in tiled } val modifiedEntities = mutableListOf>() - val previous = polylineManager.allEntities().map { it.state.id }.toMutableSet() + // Only natively drawn polylines are diffed against the renderer. + val previous = + polylineManager + .allEntities() + .map { it.state.id } + .filterTo(mutableSetOf()) { it !in wasTiled } val added = mutableListOf() val updated = mutableListOf>() val removed = mutableListOf>() - data.forEach { state -> + native.forEach { state -> if (previous.contains(state.id)) { - val prevEntity = polylineManager.getEntity(state.id)!! + // Gone only if destroy() cleared the manager meanwhile; nothing left to update. + val prevEntity = polylineManager.getEntity(state.id) ?: return@withPermit if (state.fingerPrint() == prevEntity.fingerPrint) { // 描画結果が不変なら renderer を呼ばず最新の state だけ採用する(react-sdk と同じ)。 polylineManager.registerEntity(PolylineEntity(state = state, polyline = prevEntity.polyline)) @@ -111,13 +132,64 @@ abstract class PolylineController( } } + // Tiled polylines: kept for taps, nothing native. Those that left + // the tiles and the list are forgotten; those that left the tiles + // for native drawing were added above. + if (wasTiled.isNotEmpty()) { + val nativeIds = native.mapTo(HashSet()) { it.id } + for (id in wasTiled) { + if (id !in tiled && id !in nativeIds) polylineManager.removeEntity(id) + } + } + if (tiled.isNotEmpty()) { + val tiledStates = tiler!!.tiledStates() + withContext(Dispatchers.Default) { + for (state in tiledStates) { + polylineManager.registerEntity(PolylineEntity(polyline = inTiles(), state = state)) + } + } + } + renderer.onPostProcess() } } + /** What a tiled polyline's entity holds instead of a native polyline. */ + @Suppress("UNCHECKED_CAST") + private fun inTiles(): ActualPolyline = null as ActualPolyline + override suspend fun update(state: PolylineState) { semaphore.withPermit { val prevEntity = polylineManager.getEntity(state.id) ?: return + if (state.id in tiledIds) { + if (PolylineTileSet.canTile(state)) { + polylineManager.registerEntity(PolylineEntity(polyline = prevEntity.polyline, state = state)) + tiler?.update(state) + return + } + // No longer drawable in a tile (geodesic, half the world wide, or + // under 2 points): the map SDK draws it from now on. Still on the + // map, so this is not an add. Whether the rest stay in tiles is + // left to the next add(), which decides tiling for the whole list. + tiledIds = tiledIds - state.id + tiler?.remove(state.id) + val polylines = + renderer.onAdd( + listOf( + object : PolylineOverlayRendererInterface.AddParamsInterface { + override val state: PolylineState = state + }, + ), + ) + val polyline = polylines.firstOrNull() + if (polyline != null) { + polylineManager.registerEntity(PolylineEntity(polyline = polyline, state = state)) + } else { + polylineManager.removeEntity(state.id) + } + renderer.onPostProcess() + return + } val currentFinger = state.fingerPrint() val prevFinger = prevEntity.fingerPrint if (currentFinger == prevFinger) { @@ -151,10 +223,16 @@ abstract class PolylineController( override suspend fun clear() { semaphore.withPermit { - val entities: List> = polylineManager.allEntities() + val tiled = tiledIds + tiledIds = emptySet() + tiler?.clear() + val entities: List> = + polylineManager.allEntities().filter { it.state.id !in tiled } renderer.onRemove(entities) - renderer.onPostProcess() + // manager を空にしてから onPostProcess を呼ぶ。GL 系の描画担当は remove では何もせず、 + // onPostProcess で manager の全部を描き直すので、逆の順だと clear() 後も地図に残る。 polylineManager.clear() + renderer.onPostProcess() } } @@ -169,7 +247,12 @@ abstract class PolylineController( } override fun destroy() { - // No native resources to clean up for polylines + // The tile server outlives the map; without this its route keeps every + // tiled polyline (and the renderer's copies of them) alive. + tiler?.dispose() + // A destroyed controller can still be referenced (by its map controller, + // or a state that has not let go yet); without this it keeps every entity. + polylineManager.clear() } override fun has(id: String): Boolean = polylineManager.hasEntity(id) diff --git a/src/main/java/com/mapconductor/core/polyline/PolylineManager.kt b/src/main/java/com/mapconductor/core/polyline/PolylineManager.kt index a973408..8bc15a5 100644 --- a/src/main/java/com/mapconductor/core/polyline/PolylineManager.kt +++ b/src/main/java/com/mapconductor/core/polyline/PolylineManager.kt @@ -1,5 +1,6 @@ package com.mapconductor.core.polyline +import com.mapconductor.core.InternalMapConductorApi import com.mapconductor.core.ResourceProvider import com.mapconductor.core.features.GeoPointInterface import com.mapconductor.core.features.GeoRectBounds @@ -9,6 +10,7 @@ import com.mapconductor.core.spherical.WGS84Geodesic import com.mapconductor.core.spherical.calculateMetersPerPixel import com.mapconductor.settings.Settings import java.util.concurrent.ConcurrentHashMap +import kotlin.math.cos import android.util.Log data class PolylineHitResult( @@ -45,6 +47,9 @@ class PolylineManager : PolylineManagerInterface private const val DEBUG_FIND = false private const val TAG = "PolylineManagerInterface" + /** Meters per degree of latitude, rounded up: the box check may only ever let more through. */ + private const val METERS_PER_DEGREE = 111_000.0 + private fun d(msg: String) { if (DEBUG_FIND) Log.d(TAG, msg) } @@ -52,11 +57,34 @@ class PolylineManager : PolylineManagerInterface private val entities = ConcurrentHashMap>() + /** + * Each line's bounding box, made when it is registered (every change of a + * state registers it again). A tap first skips the lines whose box, grown + * by the tolerance, it is not in: a city of roads is 50,000 lines and + * 230,000 points, too many to measure on every tap. Null for a line the + * box would not hold (geodesic, or half the world wide); those are always + * measured. + */ + private val boxes = ConcurrentHashMap() + + @InternalMapConductorApi + private class LineBox( + val minLat: Double, + val maxLat: Double, + val minLng: Double, + val maxLng: Double, + ) + override fun registerEntity(entity: PolylineEntityInterface) { entities[entity.state.id] = entity + val box = boxOf(entity.state) + if (box != null) boxes[entity.state.id] = box else boxes.remove(entity.state.id) } - override fun removeEntity(id: String): PolylineEntityInterface? = entities.remove(id) + override fun removeEntity(id: String): PolylineEntityInterface? { + boxes.remove(id) + return entities.remove(id) + } override fun getEntity(id: String): PolylineEntityInterface? = entities[id] @@ -67,8 +95,18 @@ class PolylineManager : PolylineManagerInterface override fun clear() { entities.clear() + boxes.clear() } + /** + * The line nearest [position] that it is on, with the point on the line + * nearest it (the contract on all three platforms). + * + * A tap is on a line when it is within the finger's size + * ([Settings.tapTolerance]) of the line's edge: of its centre line plus + * half its [PolylineState.strokeWidth], both on screen at the camera's + * zoom. The same whether the line is drawn natively or in tiles. + */ override fun find( position: GeoPointInterface, cameraPosition: MapCameraPosition?, @@ -77,11 +115,21 @@ class PolylineManager : PolylineManagerInterface val candidates = mutableListOf, GeoPointInterface, Double>>() val fingerSize = ResourceProvider.dpToPx(Settings.Default.tapTolerance) val zoom = cameraPosition?.zoom ?: 0.0 - val threshold = calculateMetersPerPixel(position.latitude, zoom) * fingerSize + val metersPerPixel = calculateMetersPerPixel(position.latitude, zoom) + val lngScale = cos(Math.toRadians(position.latitude)).coerceAtLeast(0.01) + // dp → px as ResourceProvider.dpToPx does, without asking for every line. + val density = ResourceProvider.dpToPx(1.0) entities.values.forEach { entity -> // clickable=false のポリラインはタップに対して透過する(CircleManager と同じ方針)。 if (!entity.state.clickable) return@forEach + val threshold = metersPerPixel * (fingerSize + entity.state.strokeWidth.value * density / 2.0) + boxes[entity.state.id]?.let { box -> + val dLat = threshold / METERS_PER_DEGREE + val dLng = dLat / lngScale + if (position.latitude < box.minLat - dLat || position.latitude > box.maxLat + dLat) return@forEach + if (position.longitude < box.minLng - dLng || position.longitude > box.maxLng + dLng) return@forEach + } // 補間せず、元の線分を直接使う for (i in 0 until entity.state.points.size - 1) { val box = GeoRectBounds() @@ -113,7 +161,25 @@ class PolylineManager : PolylineManagerInterface val closest = candidates.minByOrNull { it.third } return closest?.let { (entity, closestPoint, distance) -> + d("hit ${entity.state.id} at $distance m") PolylineHitResult(entity = entity, closestPoint = closestPoint) } } + + private fun boxOf(state: PolylineState): LineBox? { + if (state.geodesic || state.points.isEmpty()) return null + var minLat = Double.POSITIVE_INFINITY + var maxLat = Double.NEGATIVE_INFINITY + var minLng = Double.POSITIVE_INFINITY + var maxLng = Double.NEGATIVE_INFINITY + for (p in state.points) { + if (p.latitude < minLat) minLat = p.latitude + if (p.latitude > maxLat) maxLat = p.latitude + if (p.longitude < minLng) minLng = p.longitude + if (p.longitude > maxLng) maxLng = p.longitude + } + // Across the antimeridian the box would be the rest of the world. + if (maxLng - minLng >= 180) return null + return LineBox(minLat, maxLat, minLng, maxLng) + } } diff --git a/src/main/java/com/mapconductor/core/polyline/PolylineOverlay.kt b/src/main/java/com/mapconductor/core/polyline/PolylineOverlay.kt index 9fe6bbb..0d5ee8d 100644 --- a/src/main/java/com/mapconductor/core/polyline/PolylineOverlay.kt +++ b/src/main/java/com/mapconductor/core/polyline/PolylineOverlay.kt @@ -1,16 +1,36 @@ package com.mapconductor.core.polyline +import com.mapconductor.core.OverlayAddedTracker +import com.mapconductor.core.controller.BaseMapViewController import com.mapconductor.core.controller.MapViewControllerInterface import com.mapconductor.core.map.MapOverlayInterface import kotlinx.coroutines.flow.StateFlow -class PolylineOverlay( - override val flow: StateFlow>, -) : MapOverlayInterface { - override suspend fun render( - data: MutableMap, - controller: MapViewControllerInterface, - ) { - (controller as? PolylineCapableInterface)?.compositionPolylines(data.values.toList()) +class PolylineOverlay + @JvmOverloads + constructor( + override val flow: StateFlow>, + /** + * This map's polyline tiling, when the app sets one (null keeps the + * provider's [PolylineTilingOptions.Default]). Applied to the map's + * [PolylineTiler] before every hand-over, so a change takes effect the + * next time the polylines are handed over. + */ + private val tilingOptions: StateFlow? = null, + ) : MapOverlayInterface { + /** Calls [PolylineState.onAdded] once the map has the state. See [OverlayAddedTracker]. */ + private val added = OverlayAddedTracker { it.onAdded } + + override suspend fun render( + data: MutableMap, + controller: MapViewControllerInterface, + ) { + val capable = controller as? PolylineCapableInterface ?: return + tilingOptions?.value?.let { options -> + (controller as? BaseMapViewController)?.polylineTilers()?.forEach { it.options = options } + } + val states = data.values.toList() + capable.compositionPolylines(states) + added.synced(controller, states, capable::hasPolyline) + } } -} diff --git a/src/main/java/com/mapconductor/core/polyline/PolylineTileGeometry.kt b/src/main/java/com/mapconductor/core/polyline/PolylineTileGeometry.kt new file mode 100644 index 0000000..82b56e2 --- /dev/null +++ b/src/main/java/com/mapconductor/core/polyline/PolylineTileGeometry.kt @@ -0,0 +1,216 @@ +package com.mapconductor.core.polyline + +import androidx.compose.ui.graphics.toArgb +import com.mapconductor.core.InternalMapConductorApi +import com.mapconductor.core.polygon.DP_TOLERANCE_PX +import com.mapconductor.core.polygon.douglasPeucker +import com.mapconductor.core.polygon.isVisibleColor +import com.mapconductor.core.polygon.toMercatorRing +import com.mapconductor.core.shapetile.GlShapeScene +import com.mapconductor.core.shapetile.ShapeTileRenderer +import com.mapconductor.core.shapetile.toTilePixels +import kotlin.math.floor +import kotlin.math.max +import kotlin.math.min +import android.graphics.Canvas + +// The geometry of polyline tiles: the same steps as the polyline part of the +// "Shape tiles" section of js-sdk-core's tile-sw.js and ios-sdk-core's +// PolylineTileGeometry, so the three platforms draw the same pixels from the +// same lines. +// +// A line becomes a Web Mercator path in [0, 1]. Each zoom gets its own +// simplified copy, built the first time a tile at that zoom needs it: points +// snapped to that zoom's pixel grid, repeats dropped, Douglas-Peucker at half +// a pixel with both ends kept. A line that collapses to one point (or whose +// box is under a pixel) is a dot as wide as the line. Taps never see any of +// this -- they are resolved against the original points in PolylineManager. + +/** + * One polyline as the tiles draw it. + * + * [path] is Web Mercator `[x0, y0, x1, y1, ...]` in [0, 1], open (never + * closed by the tiles). [strokeWidth] is in dp, the unit of + * [PolylineState.strokeWidth], which is also the tile unit: the line is as + * wide on screen at every zoom. + */ +@InternalMapConductorApi +internal class TilePolyline( + val path: DoubleArray, + /** minX, minY, maxX, maxY. */ + val bbox: DoubleArray, + val color: Int, + val strokeWidth: Float, +) { + val visible: Boolean get() = strokeWidth > 0f && isVisibleColor(color) + + @InternalMapConductorApi + companion object { + /** Null when the line has fewer than two points. */ + fun from(state: PolylineState): TilePolyline? { + if (state.points.size < 2) return null + val path = toMercatorRing(state.points) + var minX = Double.POSITIVE_INFINITY + var minY = Double.POSITIVE_INFINITY + var maxX = Double.NEGATIVE_INFINITY + var maxY = Double.NEGATIVE_INFINITY + var i = 0 + while (i < path.size) { + minX = min(minX, path[i]) + maxX = max(maxX, path[i]) + minY = min(minY, path[i + 1]) + maxY = max(maxY, path[i + 1]) + i += 2 + } + return TilePolyline( + path = path, + bbox = doubleArrayOf(minX, minY, maxX, maxY), + color = state.strokeColor.toArgb(), + strokeWidth = state.strokeWidth.value, + ) + } + } +} + +/** What one polyline looks like at one zoom. */ +@InternalMapConductorApi +internal sealed class PolylineTileShape { + /** World-pixel points at the zoom, `[x0, y0, ...]`, two or more. */ + @InternalMapConductorApi + class Path( + val points: DoubleArray, + ) : PolylineTileShape() + + /** A line that is one point at this zoom, drawn as a dot as wide as the line, centred at [x], [y]. */ + @InternalMapConductorApi + class Dot( + val x: Double, + val y: Double, + ) : PolylineTileShape() +} + +/** + * The line as drawn at a zoom whose world is [scale] pixels wide: a path of + * world-pixel points, or a dot for a line that is one point there; never + * nothing. + */ +@InternalMapConductorApi +internal fun simplifyPolyline( + line: TilePolyline, + scale: Double, +): PolylineTileShape { + val w = (line.bbox[2] - line.bbox[0]) * scale + val h = (line.bbox[3] - line.bbox[1]) * scale + if (w < 1 && h < 1) { + return PolylineTileShape.Dot( + ((line.bbox[0] + line.bbox[2]) / 2) * scale, + ((line.bbox[1] + line.bbox[3]) / 2) * scale, + ) + } + val path = line.path + val snapped = DoubleArray(path.size) + var n = 0 + var px = Double.NaN + var py = Double.NaN + var i = 0 + while (i < path.size) { + val x = jsRound(path[i] * scale) + val y = jsRound(path[i + 1] * scale) + i += 2 + if (x == px && y == py) continue + snapped[n++] = x + snapped[n++] = y + px = x + py = y + } + if (n < 4) return PolylineTileShape.Dot(snapped[0], snapped[1]) + // Douglas-Peucker keeps both ends, so the line still starts and ends where it did. + return PolylineTileShape.Path(douglasPeucker(snapped, n / 2, DP_TOLERANCE_PX)) +} + +/** `Math.round` as JavaScript has it (halves go up), so pixels land where tile-sw.js puts them. */ +private fun jsRound(v: Double): Double = floor(v + 0.5) + +/** Total points across [states]. */ +@InternalMapConductorApi +internal fun polylineVertexCountOf(states: List): Int { + var n = 0 + for (s in states) n += s.points.size + return n +} + +/** + * How a polyline is drawn in a shape tile: stroked, never filled, with round + * caps and joins (as the map SDKs' lines and the polygon tiles' outlines are), + * the stroke as wide in dp as [PolylineState.strokeWidth] at every zoom. + */ +@InternalMapConductorApi +internal object PolylineTilePainter : ShapeTileRenderer.Painter { + override fun bbox(item: TilePolyline): DoubleArray = item.bbox + + override fun strokeWidth(item: TilePolyline): Float = if (item.visible) item.strokeWidth else 0f + + override fun simplify( + item: TilePolyline, + scale: Double, + ): Any = simplifyPolyline(item, scale) + + override fun draw( + canvas: Canvas, + item: TilePolyline, + shape: Any, + originX: Double, + originY: Double, + r: Float, + paints: ShapeTileRenderer.Paints, + ): Boolean { + if (!item.visible) return false + when (shape) { + is PolylineTileShape.Dot -> { + paints.fill.color = item.color + val radius = max(item.strokeWidth * r, 1f) / 2f + val cx = ((shape.x - originX) * r).toFloat() + val cy = ((shape.y - originY) * r).toFloat() + canvas.drawCircle(cx, cy, radius, paints.fill) + } + is PolylineTileShape.Path -> { + val path = paints.path + path.rewind() + val p = shape.points + path.moveTo(((p[0] - originX) * r).toFloat(), ((p[1] - originY) * r).toFloat()) + var i = 2 + while (i < p.size) { + path.lineTo(((p[i] - originX) * r).toFloat(), ((p[i + 1] - originY) * r).toFloat()) + i += 2 + } + paints.stroke.color = item.color + paints.stroke.strokeWidth = item.strokeWidth * r + canvas.drawPath(path, paints.stroke) + } + else -> return false + } + return true + } + + override val drawsOnGpu: Boolean get() = ShapeTileRenderer.gpuPolygonsAndLines + + override fun record( + scene: GlShapeScene, + item: TilePolyline, + shape: Any, + originX: Double, + originY: Double, + r: Float, + ): Boolean { + if (!item.visible) return false + when (shape) { + is PolylineTileShape.Dot -> { + val radius = max(item.strokeWidth * r, 1f) / 2f + scene.addLineDot(((shape.x - originX) * r).toFloat(), ((shape.y - originY) * r).toFloat(), radius, item.color) + } + is PolylineTileShape.Path -> scene.addLine(toTilePixels(shape.points, originX, originY, r), item.color, item.strokeWidth * r) + else -> return false + } + return true + } +} diff --git a/src/main/java/com/mapconductor/core/polyline/PolylineTileSet.kt b/src/main/java/com/mapconductor/core/polyline/PolylineTileSet.kt new file mode 100644 index 0000000..25296db --- /dev/null +++ b/src/main/java/com/mapconductor/core/polyline/PolylineTileSet.kt @@ -0,0 +1,103 @@ +package com.mapconductor.core.polyline + +import com.mapconductor.core.shapetile.ShapeTileRenderer +import com.mapconductor.core.shapetile.ShapeTileSet +import com.mapconductor.core.tileserver.LocalTileServer +import com.mapconductor.core.tileserver.TileServerRegistry +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob + +/** + * The polylines of one map that are drawn as raster tiles, and their route on + * the local tile server. + * + * Provider-independent: a provider decides which polylines to tile + * ([PolylineTilingOptions.shouldUseTiles], [canTile]), hands them to + * [setPolylines], and shows the returned URL template as a raster layer. + * In-place changes go through [update]; each one ends in a new template (the + * version in it is what makes the map ask again), reported to + * [onTemplateChanged]. Tiles the change did not touch are still cached by the + * renderer and come back without being drawn again. + * + * The same as [com.mapconductor.core.polygon.PolygonTileSet] for lines: both + * are [ShapeTileSet]s, with their own route, version and tile cache. Same + * shape as js-sdk-core's and ios-sdk-core's `PolylineTileSet`. + */ +class PolylineTileSet( + server: LocalTileServer = TileServerRegistry.get(), + scope: CoroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Default), +) { + internal val renderer: ShapeTileRenderer = + ShapeTileRenderer(tileSize = TILE_SIZE, painter = PolylineTilePainter) + + internal val shapes: ShapeTileSet = + ShapeTileSet( + routePrefix = "polylines", + server = server, + scope = scope, + renderer = renderer, + idOf = { it.id }, + zIndexOf = { it.zIndex }, + toTile = TilePolyline::from, + ) + + val routeId: String get() = shapes.routeId + + /** Called with the new template after an [update] or [remove]. */ + var onTemplateChanged: (suspend (String) -> Unit)? + get() = shapes.onTemplateChanged + set(value) { + shapes.onTemplateChanged = value + } + + val tileSize: Int get() = TILE_SIZE + + /** + * Registers [states] (replacing whatever was registered) and returns the + * URL template of their tiles. Draw order is zIndex, then the order given. + */ + suspend fun setPolylines(states: List): String = shapes.setShapes(states) + + fun has(id: String): Boolean = shapes.has(id) + + /** + * One polyline changed in place. A change of zIndex reorders the list and + * needs [setPolylines] instead; everything else is applied here. + */ + fun update(state: PolylineState) = shapes.update(state) + + /** + * Takes one polyline out of the tiles. Only the tiles it was in are drawn + * again. + */ + fun remove(id: String) = shapes.remove(id) + + fun template(): String = shapes.template() + + fun dispose() = shapes.dispose() + + companion object { + private const val TILE_SIZE = 256 + + /** + * Whether a polyline can be drawn in a tile. Geodesic lines are curves + * the tile does not trace, a line spanning half the world or more + * crosses the antimeridian, and a line needs two points; the map SDK + * draws the rest. + */ + fun canTile(state: PolylineState): Boolean { + if (state.geodesic || state.points.size < 2) return false + var min = Double.POSITIVE_INFINITY + var max = Double.NEGATIVE_INFINITY + for (p in state.points) { + if (p.longitude < min) min = p.longitude + if (p.longitude > max) max = p.longitude + } + return max - min < 180 + } + + /** Points across [states]. */ + fun vertexCount(states: List): Int = polylineVertexCountOf(states) + } +} diff --git a/src/main/java/com/mapconductor/core/polyline/PolylineTiler.kt b/src/main/java/com/mapconductor/core/polyline/PolylineTiler.kt new file mode 100644 index 0000000..3f289c6 --- /dev/null +++ b/src/main/java/com/mapconductor/core/polyline/PolylineTiler.kt @@ -0,0 +1,90 @@ +package com.mapconductor.core.polyline + +import com.mapconductor.core.raster.RasterLayerSource +import com.mapconductor.core.raster.RasterLayerState +import com.mapconductor.core.shapetile.ShapeTiler + +/** The id of the raster layer that shows tiled polylines. */ +const val POLYLINE_TILE_LAYER_ID: String = "mc-polyline-tiles" + +/** The raster layer state for tiled polylines at [template]. */ +fun polylineTileRasterLayerState( + template: String, + tileSize: Int = 256, +): RasterLayerState = + RasterLayerState( + id = POLYLINE_TILE_LAYER_ID, + source = RasterLayerSource.UrlTemplate(template = template, tileSize = tileSize), + ) + +/** + * Decides which of a map's polylines are drawn as tiles, keeps them + * registered with the local tile server, and tells the provider where the + * tiles are. Used exactly as [com.mapconductor.core.polygon.PolygonTiler]: + * + * 1. [route] with the full list on every composition. It returns the ids now + * in tiles; the controller keeps those in its [PolylineManager] (taps are + * resolved there, against the original lines) but gives the map SDK + * nothing for them, and removes any native polyline it had drawn for one. + * 2. [update] for an in-place change of a tiled polyline, or [remove] when the + * change means it can no longer be tiled (it became geodesic, say). + * 3. [onTemplate] is how the tiles reach the map: a URL template to show as a + * raster layer, or null to remove it. A provider with a RasterLayer + * controller hands [polylineTileRasterLayerState] to its `upsert`, and + * removes it with `removeById(POLYLINE_TILE_LAYER_ID)`. The layer belongs + * to the polyline band: over circles, under native polylines and markers. + * + * [options] is read at every [route]: setting it decides again the next time + * the polylines are handed over. + * + * Same as js-sdk-core's and ios-sdk-core's `PolylineTiler`. + */ +class PolylineTiler( + options: PolylineTilingOptions = PolylineTilingOptions.Default, +) { + @Volatile + var options: PolylineTilingOptions = options + + var onTemplate: (suspend (template: String?, tileSize: Int) -> Unit)? = null + + private val tileSet = PolylineTileSet() + + private val tiler = + ShapeTiler( + tileSet = tileSet.shapes, + canTile = PolylineTileSet::canTile, + vertexCount = PolylineTileSet::vertexCount, + shouldUseTiles = { count, vertices -> this.options.shouldUseTiles(count, vertices) }, + idOf = { it.id }, + onTemplate = { template, tileSize -> onTemplate?.invoke(template, tileSize) }, + ) + + /** Re-decides tiling for [data] and returns the ids drawn as tiles. */ + suspend fun route(data: List): Set = tiler.route(data) + + /** The states drawn as tiles, as of the last [route]. */ + fun tiledStates(): List = tiler.tiledStates() + + fun isTiled(id: String): Boolean = tiler.isTiled(id) + + /** An in-place change of a tiled polyline; only the tiles it touches are drawn again. */ + fun update(state: PolylineState) = tiler.update(state) + + /** + * Takes one polyline out of the tiles, for a change that left it no longer + * [PolylineTileSet.canTile]; only the tiles it was in are drawn again. The + * controller then hands it to the map SDK. + */ + fun remove(id: String) = tiler.remove(id) + + /** + * Releases the tiles when the map goes away. Unlike [clear], it does not + * call [onTemplate]: there is no map left to remove the layer from. + */ + fun dispose() = tiler.dispose() + + suspend fun clear() = tiler.clear() + + /** The tile set, for tests that look at the pixels. */ + internal val tiles: PolylineTileSet get() = tileSet +} diff --git a/src/main/java/com/mapconductor/core/polyline/PolylineTilingOptions.kt b/src/main/java/com/mapconductor/core/polyline/PolylineTilingOptions.kt new file mode 100644 index 0000000..53da4de --- /dev/null +++ b/src/main/java/com/mapconductor/core/polyline/PolylineTilingOptions.kt @@ -0,0 +1,32 @@ +package com.mapconductor.core.polyline + +/** + * Options for polyline tiling. + * + * When enabled and a map holds enough polylines, they are drawn into raster + * tiles by the SDK's local tile server instead of being handed to the map SDK + * one by one. Taps are still resolved against the original lines in + * [PolylineManager], so tiling changes how polylines look, never what a tap + * hits. + * + * The counterpart of [com.mapconductor.core.polygon.PolygonTilingOptions], and + * the same options as js-sdk-core's and ios-sdk-core's `PolylineTilingOptions`. + */ +data class PolylineTilingOptions( + val enabled: Boolean = true, + /** Tile once a map holds at least this many polylines… */ + val minPolylineCount: Int = 2000, + /** …or at least this many points across them, whichever comes first. */ + val minVertexCount: Int = 50_000, +) { + /** The one place the threshold is decided; callers must not restate it. */ + fun shouldUseTiles( + polylineCount: Int, + vertexCount: Int, + ): Boolean = enabled && (polylineCount >= minPolylineCount || vertexCount >= minVertexCount) + + companion object { + val Default: PolylineTilingOptions = PolylineTilingOptions() + val Disabled: PolylineTilingOptions = PolylineTilingOptions(enabled = false) + } +} diff --git a/src/main/java/com/mapconductor/core/projection/MapCoordinateSystem.kt b/src/main/java/com/mapconductor/core/projection/MapCoordinateSystem.kt new file mode 100644 index 0000000..94a9171 --- /dev/null +++ b/src/main/java/com/mapconductor/core/projection/MapCoordinateSystem.kt @@ -0,0 +1,36 @@ +package com.mapconductor.core.projection + +/** + * 地図エンジンが地図を並べている座標系。**画面座標ではない。** + * + * [com.mapconductor.core.map.MapViewHolderInterface.toProjectedPoint] が返す + * [ProjectedPoint] がどの座標系の値かを示す。 + * + * - [code] は `"EPSG:3857"` のような識別子。エンジンが独自に定義した投影で、 + * EPSG などの番号を持たないときは null。 + * - [unit] は x / y の単位。 + * + * Mercator しか持たないエンジンと、地球儀表示中のエンジンは [WebMercator] + * (EPSG:3857 メートル)になる。 + */ +data class MapCoordinateSystem( + val code: String?, + val unit: ProjectedUnit, +) { + companion object { + /** EPSG:3857。x / y はメートル。 */ + val WebMercator = MapCoordinateSystem("EPSG:3857", ProjectedUnit.Meters) + + /** EPSG:4326。x が経度、y が緯度で、単位は度。 */ + val WGS84 = MapCoordinateSystem("EPSG:4326", ProjectedUnit.Degrees) + } +} + +/** [ProjectedPoint] の x / y の単位。 */ +enum class ProjectedUnit { + Meters, + Degrees, + + /** フィートなど上の 2 つ以外、またはエンジン独自の単位。 */ + Other, +} diff --git a/src/main/java/com/mapconductor/core/projection/ProjectedPoint.kt b/src/main/java/com/mapconductor/core/projection/ProjectedPoint.kt new file mode 100644 index 0000000..b2411cd --- /dev/null +++ b/src/main/java/com/mapconductor/core/projection/ProjectedPoint.kt @@ -0,0 +1,27 @@ +package com.mapconductor.core.projection + +/** + * 投影後の座標。**画面ピクセルではない。** + * + * 以前ここは `androidx.compose.ui.geometry.Offset` だった。Compose の `Offset` は + * Float なので、画面座標(せいぜい数千)なら十分でも、Web Mercator のワールド + * 座標には足りない。EPSG:3857 の x/y は ±20,037,508 m まで伸び、Float32 の有効 + * 桁 7 桁では小数部が丸ごと消える。 + * + * 実測(`projection-vectors.txt`): + * + * | 入力 | Double | Float | + * | --- | --- | --- | + * | 東京 | 15558805.184640 | 15558805.000000 | + * | 経度 180 | 20037508.342789 | 20037508.000000 | + * + * 0.18〜0.34 m ずれる。ios-sdk は `CGPoint`、js-sdk-core は `number` で、どちらも + * Double。**Android だけが落としていた。** + * + * 型を分けたのは、同じ理由で二度踏まないため。画面座標が欲しいところでは + * `Offset` を使い続けてよい。 + */ +data class ProjectedPoint( + val x: Double, + val y: Double, +) diff --git a/src/main/java/com/mapconductor/core/projection/ProjectionInterface.kt b/src/main/java/com/mapconductor/core/projection/ProjectionInterface.kt index 4a72e5e..26e18b2 100644 --- a/src/main/java/com/mapconductor/core/projection/ProjectionInterface.kt +++ b/src/main/java/com/mapconductor/core/projection/ProjectionInterface.kt @@ -1,10 +1,9 @@ package com.mapconductor.core.projection -import androidx.compose.ui.geometry.Offset import com.mapconductor.core.features.GeoPointInterface interface ProjectionInterface { - fun project(position: GeoPointInterface): Offset + fun project(position: GeoPointInterface): ProjectedPoint - fun unproject(point: Offset): GeoPointInterface + fun unproject(point: ProjectedPoint): GeoPointInterface } diff --git a/src/main/java/com/mapconductor/core/projection/WGS84.kt b/src/main/java/com/mapconductor/core/projection/WGS84.kt index ff0922c..e61cc32 100644 --- a/src/main/java/com/mapconductor/core/projection/WGS84.kt +++ b/src/main/java/com/mapconductor/core/projection/WGS84.kt @@ -1,6 +1,5 @@ package com.mapconductor.core.projection -import androidx.compose.ui.geometry.Offset import com.mapconductor.core.features.GeoPoint import com.mapconductor.core.features.GeoPointInterface @@ -23,14 +22,14 @@ import com.mapconductor.core.features.GeoPointInterface * https://github.com/googlemaps/android-maps-utils/blob/70a77b066b8391da06a2d708792de8337bf5d3b6/library/src/main/java/com/google/maps/android/projection/SphericalMercatorProjection.java */ object WGS84 : ProjectionInterface { - override fun project(position: GeoPointInterface): Offset { + override fun project(position: GeoPointInterface): ProjectedPoint { val x = position.longitude / 360 + .5 val siny = Math.sin(Math.toRadians(position.latitude)) val y = 0.5 * Math.log((1 + siny) / (1 - siny)) / -(2 * Math.PI) + .5 - return Offset((x * 256).toFloat(), (y * 256).toFloat()) + return ProjectedPoint(x * 256, y * 256) } - override fun unproject(point: Offset): GeoPointInterface { + override fun unproject(point: ProjectedPoint): GeoPointInterface { val x = point.x / 256 - 0.5 val lng = x * 360 val y = .5 - point.y / 256 diff --git a/src/main/java/com/mapconductor/core/projection/WebMercator.kt b/src/main/java/com/mapconductor/core/projection/WebMercator.kt index 093958c..2862958 100644 --- a/src/main/java/com/mapconductor/core/projection/WebMercator.kt +++ b/src/main/java/com/mapconductor/core/projection/WebMercator.kt @@ -1,6 +1,5 @@ package com.mapconductor.core.projection -import androidx.compose.ui.geometry.Offset import com.mapconductor.core.features.GeoPoint import com.mapconductor.core.features.GeoPointInterface import kotlin.math.PI @@ -16,22 +15,36 @@ import kotlin.math.tan */ const val WEB_MERCATOR_MAX_EXTENT_METERS: Double = PI * Earth.RADIUS_METERS +/** + * 投影が定義される緯度の端。 + * + * Web Mercator は極で発散するので、正方形のワールドに収まる範囲で切る。 + * 世界中のタイルサーバが使っている値で、ここが `MAX_EXTENT` と一致する緯度。 + */ +const val WEB_MERCATOR_MAX_LATITUDE: Double = 85.05112878 + object WebMercator : ProjectionInterface { - override fun project(position: GeoPointInterface): Offset { - val x = position.longitude * WEB_MERCATOR_MAX_EXTENT_METERS / 180 - val y = ln(tan((90 + position.latitude) * Math.PI / 360)) * WEB_MERCATOR_MAX_EXTENT_METERS / Math.PI - return Offset(x.toFloat(), y.toFloat()) + /** + * 緯度経度 → EPSG:3857 メートル。 + * + * 入力は投影前に wrap とクランプを通す。通さないと `latitude = 90` で + * `tan()` が発散し、呼び出し側に無限大が渡る。実測では web / android の + * 旧実装が `+90` で 238107693(有限のゴミ)を、`-90` で `-inf` を返して + * いた -- 同じ式が符号で違う壊れ方をしていた。ios-sdk は最初からクランプ + * していたので、そちらに合わせてある。 + */ + override fun project(position: GeoPointInterface): ProjectedPoint { + val wrapped = position.wrap() + val latitude = wrapped.latitude.coerceIn(-WEB_MERCATOR_MAX_LATITUDE, WEB_MERCATOR_MAX_LATITUDE) + val x = wrapped.longitude * WEB_MERCATOR_MAX_EXTENT_METERS / 180 + val y = ln(tan((90 + latitude) * PI / 360)) * WEB_MERCATOR_MAX_EXTENT_METERS / PI + return ProjectedPoint(x, y) } - override fun unproject(point: Offset): GeoPointInterface { + /** EPSG:3857 メートル → 緯度経度。結果は wrap して返す。 */ + override fun unproject(point: ProjectedPoint): GeoPointInterface { val longitude = point.x * 180 / WEB_MERCATOR_MAX_EXTENT_METERS - val latitude = 180 / Math.PI * (2 * atan(exp(point.y * Math.PI / WEB_MERCATOR_MAX_EXTENT_METERS)) - Math.PI / 2) - return object : GeoPointInterface { - override val latitude: Double = latitude - override val longitude: Double = longitude - override val altitude: Double? = null - - override fun wrap(): GeoPointInterface = GeoPoint(latitude, longitude, altitude ?: 0.0).wrap() - } + val latitude = 180 / PI * (2 * atan(exp(point.y * PI / WEB_MERCATOR_MAX_EXTENT_METERS)) - PI / 2) + return GeoPoint(latitude, longitude, 0.0).wrap() } } diff --git a/src/main/java/com/mapconductor/core/projection/WebMercatorScreenProjection.kt b/src/main/java/com/mapconductor/core/projection/WebMercatorScreenProjection.kt index f7066c1..c45fd90 100644 --- a/src/main/java/com/mapconductor/core/projection/WebMercatorScreenProjection.kt +++ b/src/main/java/com/mapconductor/core/projection/WebMercatorScreenProjection.kt @@ -3,10 +3,12 @@ package com.mapconductor.core.projection import androidx.compose.ui.geometry.Offset import com.mapconductor.core.features.GeoPoint import com.mapconductor.core.features.GeoPointInterface +import com.mapconductor.core.map.CameraBearing import com.mapconductor.core.map.MapCameraPosition import kotlin.math.cos import kotlin.math.pow import kotlin.math.sin +import kotlin.math.tan /** * 地理座標 ⇄ 画面座標を、カメラとビューの大きさだけから計算する。 @@ -25,11 +27,12 @@ import kotlin.math.sin * * - **Web Mercator でない地図**(3D globe の HERE、球面の Cesium 等)。 * これらは地図SDK自身の投影を使うこと。 - * - **tilt が 0 でないとき。** 傾いたカメラは平面の相似変換にならないので誤差が出る。 - * (必要になったら `visibleRegion` の 4 隅からホモグラフィを組む方式へ拡張できる。 - * 平面地図なら透視投影はホモグラフィそのものなので厳密に扱える。) * - * bearing(回転)には対応している。 + * bearing(回転)に対応している。tilt は、カメラの上下視野角(`fovDegrees`)を渡したときだけ + * 透視(ピンホールカメラ)で扱う。MapLibre GL JS と同じカメラ模型で、画面中央の 1px が + * 世界の 1px(`256 * 2^zoom`)になり、カメラは中央の地点から焦点距離 + * `(高さ / 2) / tan(fov / 2)` だけ離れて tilt 分だけ傾いている。視野角を渡さない呼び出しは + * 従来どおり平面の相似変換で、tilt があると奥ほどずれる(tilt 60 で 250px 近く)。 */ object WebMercatorScreenProjection { /** @@ -52,6 +55,19 @@ object WebMercatorScreenProjection { camera: MapCameraPosition, widthPx: Float, heightPx: Float, + ): Offset? = toScreenOffset(position, camera, widthPx, heightPx, fovDegrees = null) + + /** + * [toScreenOffset] の tilt 対応版。[fovDegrees] はカメラの上下視野角(地図エンジンの値)。 + * null か 0 以下、または tilt が 0 なら平面の式と同じ結果になる。カメラの背後や + * 地平線より向こうに当たる点は null。 + */ + fun toScreenOffset( + position: GeoPointInterface, + camera: MapCameraPosition, + widthPx: Float, + heightPx: Float, + fovDegrees: Double?, ): Offset? { if (widthPx <= 0f || heightPx <= 0f) return null val worldSize = WORLD_SIZE_AT_ZOOM_0 * 2.0.pow(camera.zoom) @@ -66,13 +82,25 @@ object WebMercatorScreenProjection { var sx = dx * worldSize var sy = (target.y - center.y) * worldSize if (camera.bearing != 0.0) { - // bearing は「画面の上が指す方位(北から時計回り)」。世界を -bearing 回す。 - val angle = -camera.bearing * Math.PI / 180.0 + // 画面の上が指す方位はカメラの heading(= bearing の符号反転)。世界を + // -heading 回すと、その方位が画面の上(-y)に来る。 + val angle = -CameraBearing.toNativeHeading(camera.bearing) * Math.PI / 180.0 val rx = sx * cos(angle) - sy * sin(angle) val ry = sx * sin(angle) + sy * cos(angle) sx = rx sy = ry } + val distance = cameraDistance(camera, heightPx, fovDegrees) + if (distance != null) { + // 地面上で中央から sy 手前(画面の下向き)の点。カメラは中央から distance 離れて + // tilt だけ傾いているので、奥行きは distance - sy·sin(tilt)。 + val tilt = camera.tilt * Math.PI / 180.0 + val depth = distance - sy * sin(tilt) + if (depth <= 0.0) return null + val scale = distance / depth + sx *= scale + sy *= cos(tilt) * scale + } val x = widthPx / 2.0 + sx val y = heightPx / 2.0 + sy if (!x.isFinite() || !y.isFinite()) return null @@ -85,12 +113,31 @@ object WebMercatorScreenProjection { camera: MapCameraPosition, widthPx: Float, heightPx: Float, + ): GeoPoint? = fromScreenOffset(offset, camera, widthPx, heightPx, fovDegrees = null) + + /** tilt 対応版の [toScreenOffset] の逆。地平線より上の点は null。 */ + fun fromScreenOffset( + offset: Offset, + camera: MapCameraPosition, + widthPx: Float, + heightPx: Float, + fovDegrees: Double?, ): GeoPoint? { if (widthPx <= 0f || heightPx <= 0f) return null var sx = offset.x - widthPx / 2.0 var sy = offset.y - heightPx / 2.0 + val distance = cameraDistance(camera, heightPx, fovDegrees) + if (distance != null) { + // toScreenOffset の透視を外す: y = D·g·cos t / (D − g·sin t) を g について解く。 + val tilt = camera.tilt * Math.PI / 180.0 + val denominator = distance * cos(tilt) + sy * sin(tilt) + if (denominator <= 0.0) return null + val ground = sy * distance / denominator + sx *= (distance - ground * sin(tilt)) / distance + sy = ground + } if (camera.bearing != 0.0) { - val angle = camera.bearing * Math.PI / 180.0 + val angle = CameraBearing.toNativeHeading(camera.bearing) * Math.PI / 180.0 val rx = sx * cos(angle) - sy * sin(angle) val ry = sx * sin(angle) + sy * cos(angle) sx = rx @@ -103,15 +150,29 @@ object WebMercatorScreenProjection { wx -= Math.floor(wx) val projected = - Offset( - ((wx - 0.5) * 2.0 * WEB_MERCATOR_MAX_EXTENT_METERS).toFloat(), - ((0.5 - wy) * 2.0 * WEB_MERCATOR_MAX_EXTENT_METERS).toFloat(), + ProjectedPoint( + (wx - 0.5) * 2.0 * WEB_MERCATOR_MAX_EXTENT_METERS, + (0.5 - wy) * 2.0 * WEB_MERCATOR_MAX_EXTENT_METERS, ) val point = WebMercator.unproject(projected) if (!point.latitude.isFinite() || !point.longitude.isFinite()) return null return GeoPoint(latitude = point.latitude, longitude = point.longitude, altitude = 0.0) } + /** + * 画面中央の地点からカメラまでの距離([heightPx] と同じ単位)。tilt が無いか視野角が + * 分からなければ null(平面の式を使う)。 + */ + private fun cameraDistance( + camera: MapCameraPosition, + heightPx: Float, + fovDegrees: Double?, + ): Double? { + if (fovDegrees == null || fovDegrees <= 0.0 || camera.tilt == 0.0) return null + val halfFov = fovDegrees * Math.PI / 360.0 + return heightPx / 2.0 / tan(halfFov) + } + /** Web Mercator のメートル座標を [0,1] へ。y は北が 0。 */ private fun normalize(position: GeoPointInterface): Normalized { val projected = WebMercator.project(position) diff --git a/src/main/java/com/mapconductor/core/raster/RasterLayer.kt b/src/main/java/com/mapconductor/core/raster/RasterLayer.kt index f6e97c5..a70bcdf 100644 --- a/src/main/java/com/mapconductor/core/raster/RasterLayer.kt +++ b/src/main/java/com/mapconductor/core/raster/RasterLayer.kt @@ -1,129 +1,201 @@ -package com.mapconductor.core.raster - -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.setValue -import androidx.compose.runtime.snapshotFlow -import com.mapconductor.core.ComponentState -import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.flow.distinctUntilChanged - -class RasterLayerState( - source: RasterLayerSource, - opacity: Float = 1.0f, - visible: Boolean = true, - zIndex: Int = 0, - userAgent: String = DEFAULT_USER_AGENT, - debug: Boolean = false, - id: String? = null, - extraHeaders: Map? = null, -) : ComponentState { - override val id = - ( - id ?: rasterLayerId( - listOf( - source.hashCode(), - opacity.hashCode(), - visible.hashCode(), - debug.hashCode(), - extraHeaders?.hashCode() ?: 0, - ), - ) - ).toString() - - var source by mutableStateOf(source) - var opacity by mutableStateOf(opacity) - var visible by mutableStateOf(visible) - var zIndex by mutableStateOf(zIndex) - var userAgent by mutableStateOf(userAgent) - var debug by mutableStateOf(debug) - var extraHeaders by mutableStateOf(extraHeaders) - - private fun rasterLayerId(hashCodes: List): Int = - hashCodes.reduce { result, hashCode -> - 31 * result + hashCode - } - - override fun equals(other: Any?): Boolean { - val otherState = (other as? RasterLayerState) ?: return false - return hashCode() == otherState.hashCode() - } - - override fun hashCode(): Int { - var result = source.hashCode() - result = 31 * result + opacity.hashCode() - result = 31 * result + visible.hashCode() - result = 31 * result + zIndex.hashCode() - result = 31 * result + debug.hashCode() - result = 31 * result + (extraHeaders?.hashCode() ?: 0) - result = 31 * result + userAgent.hashCode() - return result - } - - fun copy( - source: RasterLayerSource = this.source, - opacity: Float = this.opacity, - visible: Boolean = this.visible, - zIndex: Int = this.zIndex, - debug: Boolean = this.debug, - userAgent: String = this.userAgent, - id: String? = this.id, - extraHeaders: Map? = this.extraHeaders, - ): RasterLayerState = - RasterLayerState( - source = source, - opacity = opacity, - visible = visible, - zIndex = zIndex, - userAgent = userAgent, - debug = debug, - id = id, - extraHeaders = extraHeaders, - ) - - fun fingerPrint(): RasterLayerFingerPrint = - RasterLayerFingerPrint( - id = id.hashCode(), - source = source.hashCode(), - opacity = opacity.hashCode(), - visible = visible.hashCode(), - zIndex = zIndex.hashCode(), - userAgent = userAgent.hashCode(), - debug = debug.hashCode(), - extra = extraHeaders?.hashCode() ?: 0, - ) - - fun asFlow(): Flow = - snapshotFlow { fingerPrint() } - .distinctUntilChanged() - - companion object { - /** - * `userAgent` を明示しなかったときに入る値。 - * - * 定数として公開しているのは、プロバイダ側が「利用者が本当に指定したのか、 - * 既定のまま来ただけなのか」を判断するため。ヘッダを載せるのに追加のコストが - * 要るプロバイダは、既定値のままならそのコストを払わない。 - * ios-sdk の `RasterLayerState.defaultUserAgent` / react-sdk の - * `DEFAULT_RASTER_LAYER_USER_AGENT` と同じ値。 - */ - const val DEFAULT_USER_AGENT = "MapConductor/RasterLayerAgent(https://mapconductor.com)" - } -} - -data class RasterLayerFingerPrint( - val id: Int, - val source: Int, - val opacity: Int, - val visible: Int, - val zIndex: Int, - val userAgent: Int, - val debug: Int, - val extra: Int, -) - -data class RasterLayerEvent( - val state: RasterLayerState, -) - -typealias OnRasterLayerEventHandler = (RasterLayerEvent) -> Unit +package com.mapconductor.core.raster + +import androidx.compose.runtime.getValue +import androidx.compose.runtime.setValue +import com.mapconductor.core.ComponentState +import com.mapconductor.core.StateMutationSignal + +class RasterLayerState( + source: RasterLayerSource, + opacity: Float = 1.0f, + visible: Boolean = true, + zIndex: Int = 0, + userAgent: String = DEFAULT_USER_AGENT, + debug: Boolean = false, + id: String? = null, + extraHeaders: Map? = null, + onAdded: OnRasterLayerAddedHandler? = null, +) : ComponentState { + override val id = + ( + id ?: rasterLayerId( + listOf( + source.hashCode(), + opacity.hashCode(), + visible.hashCode(), + debug.hashCode(), + extraHeaders?.hashCode() ?: 0, + ), + ) + ).toString() + + /** + * Writes to the fields below are announced here rather than discovered by + * reading them all back. See [StateMutationSignal]. + */ + override val mutations = StateMutationSignal() + + var source by mutations.notifying(source) + var opacity by mutations.notifying(opacity) + var visible by mutations.notifying(visible) + var zIndex by mutations.notifying(zIndex) + var userAgent by mutations.notifying(userAgent) + var debug by mutations.notifying(debug) + + /** + * タイル要求に足すヘッダー。変えるときは新しい Map を代入する。渡した Map をその場で + * 書き換えても state には伝わらず、内容の等しい Map の代入は無視される。 + */ + var extraHeaders by mutations.notifying(extraHeaders) + + /** + * Called once each time this raster layer goes from not being on the map to being on it: + * after the map SDK's object for it has been created, or, when it is drawn in tiles, + * after the URL template of those tiles has been handed to the map as a raster layer + * (the tile images may still be loading then). Not called for an in-place change, + * nor when it moves between native drawing and tiles while staying on the map; + * called again if it is removed and added again. Clearing or destroying the map calls + * nothing. + * + * Runs on the main thread once the map has finished adding the overlays it was given. + * A callback that throws is logged and does not stop the other overlays' callbacks. + * + * Like `onClick`, it is not part of the id, fingerprint, equality or hash: replacing + * it redraws nothing. If the same state is shown on two maps, each map calls it. + */ + var onAdded: OnRasterLayerAddedHandler? = onAdded + + @Deprecated("Binary compatibility only; use the overload with onAdded.", level = DeprecationLevel.HIDDEN) + constructor( + source: RasterLayerSource, + opacity: Float = 1.0f, + visible: Boolean = true, + zIndex: Int = 0, + userAgent: String = DEFAULT_USER_AGENT, + debug: Boolean = false, + id: String? = null, + extraHeaders: Map? = null, + ) : this( + source, + opacity, + visible, + zIndex, + userAgent, + debug, + id, + extraHeaders, + null, + ) + + private fun rasterLayerId(hashCodes: List): Int = + hashCodes.reduce { result, hashCode -> + 31 * result + hashCode + } + + override fun equals(other: Any?): Boolean { + val otherState = (other as? RasterLayerState) ?: return false + return hashCode() == otherState.hashCode() + } + + override fun hashCode(): Int { + var result = source.hashCode() + result = 31 * result + opacity.hashCode() + result = 31 * result + visible.hashCode() + result = 31 * result + zIndex.hashCode() + result = 31 * result + debug.hashCode() + result = 31 * result + (extraHeaders?.hashCode() ?: 0) + result = 31 * result + userAgent.hashCode() + return result + } + + fun copy( + source: RasterLayerSource = this.source, + opacity: Float = this.opacity, + visible: Boolean = this.visible, + zIndex: Int = this.zIndex, + debug: Boolean = this.debug, + userAgent: String = this.userAgent, + id: String? = this.id, + extraHeaders: Map? = this.extraHeaders, + onAdded: OnRasterLayerAddedHandler? = this.onAdded, + ): RasterLayerState = + RasterLayerState( + source = source, + opacity = opacity, + visible = visible, + zIndex = zIndex, + userAgent = userAgent, + debug = debug, + id = id, + extraHeaders = extraHeaders, + onAdded = onAdded, + ) + + @Deprecated("Binary compatibility only; use the overload with onAdded.", level = DeprecationLevel.HIDDEN) + fun copy( + source: RasterLayerSource = this.source, + opacity: Float = this.opacity, + visible: Boolean = this.visible, + zIndex: Int = this.zIndex, + debug: Boolean = this.debug, + userAgent: String = this.userAgent, + id: String? = this.id, + extraHeaders: Map? = this.extraHeaders, + ): RasterLayerState = + copy( + source, + opacity, + visible, + zIndex, + debug, + userAgent, + id, + extraHeaders, + onAdded, + ) + + fun fingerPrint(): RasterLayerFingerPrint = + RasterLayerFingerPrint( + id = id.hashCode(), + source = source.hashCode(), + opacity = opacity.hashCode(), + visible = visible.hashCode(), + zIndex = zIndex.hashCode(), + userAgent = userAgent.hashCode(), + debug = debug.hashCode(), + extra = extraHeaders?.hashCode() ?: 0, + ) + + companion object { + /** + * `userAgent` を明示しなかったときに入る値。 + * + * 定数として公開しているのは、プロバイダ側が「利用者が本当に指定したのか、 + * 既定のまま来ただけなのか」を判断するため。ヘッダを載せるのに追加のコストが + * 要るプロバイダは、既定値のままならそのコストを払わない。 + * ios-sdk の `RasterLayerState.defaultUserAgent` / react-sdk の + * `DEFAULT_RASTER_LAYER_USER_AGENT` と同じ値。 + */ + const val DEFAULT_USER_AGENT = "MapConductor/RasterLayerAgent(https://mapconductor.com)" + } +} + +data class RasterLayerFingerPrint( + val id: Int, + val source: Int, + val opacity: Int, + val visible: Int, + val zIndex: Int, + val userAgent: Int, + val debug: Int, + val extra: Int, +) + +data class RasterLayerEvent( + val state: RasterLayerState, +) + +typealias OnRasterLayerEventHandler = (RasterLayerEvent) -> Unit + +/** Receives the state whose layer was just added to the map. See [RasterLayerState.onAdded]. */ +typealias OnRasterLayerAddedHandler = (RasterLayerState) -> Unit diff --git a/src/main/java/com/mapconductor/core/raster/RasterLayerController.kt b/src/main/java/com/mapconductor/core/raster/RasterLayerController.kt index 29d9205..1e27d46 100644 --- a/src/main/java/com/mapconductor/core/raster/RasterLayerController.kt +++ b/src/main/java/com/mapconductor/core/raster/RasterLayerController.kt @@ -236,8 +236,41 @@ abstract class RasterLayerController( upsertedIds.clear() val entities: List> = rasterLayerManager.allEntities() renderer.onRemove(entities) - renderer.onPostProcess() + // manager を空にしてから onPostProcess を呼ぶ。GL 系の描画担当は remove では何もせず、 + // onPostProcess で manager の全部を描き直すので、逆の順だと clear() 後も地図に残る。 rasterLayerManager.clear() + renderer.onPostProcess() + } + } + } + + /** + * Re-adds every registered layer after the style was replaced, which drops + * the sources and layers the SDK added. + * + * It runs under the same lock as add/update/upsert/clear, so it reads the + * manager only after any change in progress has registered its entity. Read + * outside the lock, a change between renderer.onChange() and registerEntity() + * would be re-applied with its old source or opacity (react-sdk hit this: + * MapConductor/js-sdk-core#15). + * + * Entities are not registered again: the providers that call this build + * their handles from the layer id, so the registered ones stay valid on the + * new style. + */ + open suspend fun reapplyStyle() { + withContext(renderer.coroutine.coroutineContext) { + semaphore.withPermit { + val states = rasterLayerManager.allEntities().map { it.state } + if (states.isEmpty()) return@withPermit + renderer.onAdd( + states.map { state -> + object : RasterLayerOverlayRendererInterface.AddParamsInterface { + override val state: RasterLayerState = state + } + }, + ) + renderer.onPostProcess() } } } @@ -251,7 +284,9 @@ abstract class RasterLayerController( } override fun destroy() { - // No native resources to clean up + // A destroyed controller can still be referenced (by its map controller, + // or a state that has not let go yet); without this it keeps every entity. + rasterLayerManager.clear() } override fun has(id: String): Boolean = rasterLayerManager.hasEntity(id) diff --git a/src/main/java/com/mapconductor/core/raster/RasterLayerOverlay.kt b/src/main/java/com/mapconductor/core/raster/RasterLayerOverlay.kt index 97bb911..7b58c13 100644 --- a/src/main/java/com/mapconductor/core/raster/RasterLayerOverlay.kt +++ b/src/main/java/com/mapconductor/core/raster/RasterLayerOverlay.kt @@ -1,5 +1,6 @@ package com.mapconductor.core.raster +import com.mapconductor.core.OverlayAddedTracker import com.mapconductor.core.controller.MapViewControllerInterface import com.mapconductor.core.map.MapOverlayInterface import kotlinx.coroutines.flow.StateFlow @@ -7,10 +8,16 @@ import kotlinx.coroutines.flow.StateFlow class RasterLayerOverlay( override val flow: StateFlow>, ) : MapOverlayInterface { + /** Calls [RasterLayerState.onAdded] once the map has the state. See [OverlayAddedTracker]. */ + private val added = OverlayAddedTracker { it.onAdded } + override suspend fun render( data: MutableMap, controller: MapViewControllerInterface, ) { - (controller as? RasterLayerCapableInterface)?.compositionRasterLayers(data.values.toList()) + val capable = controller as? RasterLayerCapableInterface ?: return + val states = data.values.toList() + capable.compositionRasterLayers(states) + added.synced(controller, states, capable::hasRasterLayer) } } diff --git a/src/main/java/com/mapconductor/core/raster/RasterTilePreference.kt b/src/main/java/com/mapconductor/core/raster/RasterTilePreference.kt new file mode 100644 index 0000000..40c934a --- /dev/null +++ b/src/main/java/com/mapconductor/core/raster/RasterTilePreference.kt @@ -0,0 +1,47 @@ +package com.mapconductor.core.raster + +import com.mapconductor.core.map.MapServiceKey + +/** + * どの大きさのタイルなら、この地図 SDK がうまく扱えるか。 + * + * タイルの一辺は本来アプリの好みで決めてよく、既定は 512 にしてある(1 枚あたりの + * 固定費 — HTTP の往復、PNG の符号化・復号、レンダラの立ち上げ — が枚数に比例する + * ので、同じ画面を覆うなら枚数は少ないほうが安い)。ところが SDK 側に都合がある + * ことがあり、その都合はレイヤを載せる側からは見えない。 + * + * 実例が ArcGIS の 3D SceneView で、**タイルは 256px**という前提でレベルを選ぶ。 + * 512px のタイルを渡すと 1 段深いレベルを取りに行き、同じ画面を 4 倍の枚数で + * 覆う(実測: Pixel 5a・統一ズーム 12 で、2D は z=11、3D は z=12)。絵は正しい + * ので気づきにくいが、端末が遅いほど効く。 + * + * そこでプロバイダに「この大きさで来てほしい」と言わせ、タイルを供給する側 + * (ベクタータイル層など)がそれを読む。アプリが明示した値のほうが常に強い。 + */ +interface RasterTilePreference { + /** この SDK に渡してほしいタイルの一辺(dp)。 */ + val preferredTileSize: Int + + /** + * この SDK がラスタータイルを **物理ピクセル** でレイアウトするなら true。 + * + * 地図 SDK には 2 つの流儀がある。宣言された一辺を dp として敷くものと、 + * 物理ピクセルとして敷くもの。後者に density 2 の端末で「512」と宣言すると + * 256 dp しか覆わず、1 段深いズームを要求してスタイルをそこで読む — + * ラベルは半分、道路は倍の密度になる(web の HERE で実測)。供給側は + * この流儀を知りようがないので、プロバイダが言う。 + * + * true のとき、供給側は [preferredTileSize] × density を宣言し、描画は + * 同じピクセル数で行い、スタイルには [preferredTileSize] dp として + * 読ませる。既定は false。react-sdk / ios-sdk の同名フィールドに対応。 + */ + val layoutInDevicePixels: Boolean + get() = false +} + +/** + * [RasterTilePreference] の登録キー。 + * + * 宣言しないプロバイダは「好みは無い」。その場合は供給側の既定が使われる。 + */ +object RasterTilePreferenceKey : MapServiceKey diff --git a/src/main/java/com/mapconductor/core/shapetile/GlShapeRasterizer.kt b/src/main/java/com/mapconductor/core/shapetile/GlShapeRasterizer.kt new file mode 100644 index 0000000..377db43 --- /dev/null +++ b/src/main/java/com/mapconductor/core/shapetile/GlShapeRasterizer.kt @@ -0,0 +1,618 @@ +package com.mapconductor.core.shapetile + +import com.mapconductor.core.InternalMapConductorApi +import java.nio.ByteBuffer +import java.nio.ByteOrder +import java.nio.FloatBuffer +import java.util.ArrayDeque +import android.opengl.EGL14 +import android.opengl.EGLConfig +import android.opengl.EGLContext +import android.opengl.EGLDisplay +import android.opengl.EGLSurface +import android.opengl.GLES30 +import android.util.Log + +/** + * Draws a [GlShapeScene] with OpenGL ES 3.0 off screen and reads the pixels + * back: the GPU path of [ShapeTileRenderer], the counterpart of ios-sdk-core's + * `MetalShapeRasterizer` and `MetalPathRasterizer`. + * + * - 4x MSAA (or what the GPU offers up to 4) gives the antialiasing; the stencil + * is multisampled too, so a covered edge is the share of its samples drawn. + * - Premultiplied colours, blended source-over (`ONE, ONE_MINUS_SRC_ALPHA`), as an + * `ARGB_8888` bitmap holds them; the pixels come back premultiplied. + * - y is flipped in the vertex shaders, so the first row `glReadPixels` returns + * is the top of the tile, as a bitmap's first row is. + * + * Tiles are asked for on several of the tile server's threads at once. A GL + * context is current on one thread at a time, so there is a small pool of + * contexts, each with its own programs and targets; a tile borrows one and + * makes it current for the draw. Without GLES 3 (or when anything fails to set + * up) [render] returns null and the caller draws on the CPU. + */ +@InternalMapConductorApi +internal object GlShapeRasterizer { + private const val TAG = "GlShapeRasterizer" + private const val MAX_CONTEXTS = 4 + private const val EGL_OPENGL_ES3_BIT = 0x40 + + private val idle = ArrayDeque() + private var created = 0 + private val lock = Object() + + @Volatile + private var broken = false + + /** Whether GLES 3 drawing works here; false after the first failure to set it up. */ + val isAvailable: Boolean + get() { + if (broken) return false + val context = acquire() ?: return false + release(context) + return true + } + + /** + * Draws [scene] and returns its pixels: a direct buffer of `pixels * pixels` + * premultiplied RGBA, top row first. Null when the GPU cannot draw it. + */ + fun render(scene: GlShapeScene): ByteBuffer? { + if (scene.isEmpty) return null + val context = acquire() ?: return null + var ok = false + try { + val result = context.draw(scene) + ok = result != null + return result + } catch (error: RuntimeException) { + Log.w(TAG, "GPU tile failed; drawing on the CPU", error) + return null + } finally { + if (ok) release(context) else context.destroy() + } + } + + /** + * Makes every context of the pool and its shaders ahead of the first tiles, + * which otherwise wait for them (about a tenth of a second each on a tablet). + */ + fun prepare() { + if (broken) return + val made = ArrayList() + repeat(MAX_CONTEXTS) { + val context = acquire() ?: return@repeat + context.releaseCurrent() + made += context + } + for (context in made) { + synchronized(lock) { + idle.addLast(context) + lock.notifyAll() + } + } + } + + private fun acquire(): Context? { + synchronized(lock) { + if (broken) return null + idle.pollFirst()?.let { context -> + return if (context.makeCurrent()) context else null + } + if (created >= MAX_CONTEXTS) { + while (idle.isEmpty()) lock.wait() + return idle.pollFirst()?.takeIf { it.makeCurrent() } + } + created++ + } + val context = + try { + Context.create() + } catch (error: RuntimeException) { + Log.w(TAG, "GLES 3 unavailable; shape tiles are drawn on the CPU", error) + null + } + if (context == null) { + synchronized(lock) { + created-- + broken = true + lock.notifyAll() + } + } + return context + } + + private fun release(context: Context) { + context.releaseCurrent() + synchronized(lock) { + idle.addLast(context) + lock.notifyAll() + } + } + + private fun Context.destroy() { + destroyContext() + synchronized(lock) { + created-- + lock.notifyAll() + } + } + + private class Context private constructor( + private val display: EGLDisplay, + private val context: EGLContext, + private val surface: EGLSurface, + ) { + private val samples: Int + private val circleProgram: Int + private val pathProgram: Int + private val coverProgram: Int + private val lineProgram: Int + private val buffers = IntArray(8) + private val pathExtentAt: Int + private val coverExtentAt: Int + private val circleExtentAt: Int + private val lineExtentAt: Int + /** Direct buffers for uploads, grown as needed and kept. */ + private var uploadBytes: ByteBuffer = ByteBuffer.allocateDirect(1 shl 16).order(ByteOrder.nativeOrder()) + private var targets = HashMap() + + private class Targets( + val msaa: Int, + val resolve: Int, + ) + + init { + val max = IntArray(1) + GLES30.glGetIntegerv(GLES30.GL_MAX_SAMPLES, max, 0) + samples = minOf(4, max[0]).coerceAtLeast(1) + circleProgram = program(CIRCLE_VERTEX, CIRCLE_FRAGMENT) + pathProgram = program(PATH_VERTEX, PATH_FRAGMENT) + coverProgram = program(COVER_VERTEX, COVER_FRAGMENT) + lineProgram = program(LINE_VERTEX, COVER_FRAGMENT) + pathExtentAt = GLES30.glGetUniformLocation(pathProgram, "extent") + coverExtentAt = GLES30.glGetUniformLocation(coverProgram, "extent") + circleExtentAt = GLES30.glGetUniformLocation(circleProgram, "extent") + lineExtentAt = GLES30.glGetUniformLocation(lineProgram, "extent") + GLES30.glGenBuffers(buffers.size, buffers, 0) + GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, buffers[CORNERS]) + val corners = floatArrayOf(0f, 0f, 1f, 0f, 0f, 1f, 1f, 0f, 1f, 1f, 0f, 1f) + GLES30.glBufferData(GLES30.GL_ARRAY_BUFFER, corners.size * 4, staticFloats(corners), GLES30.GL_STATIC_DRAW) + glOk("setup") + } + + fun makeCurrent(): Boolean = EGL14.eglMakeCurrent(display, surface, surface, context) + + fun releaseCurrent() { + EGL14.eglMakeCurrent(display, EGL14.EGL_NO_SURFACE, EGL14.EGL_NO_SURFACE, EGL14.EGL_NO_CONTEXT) + } + + fun destroyContext() { + releaseCurrent() + EGL14.eglDestroySurface(display, surface) + EGL14.eglDestroyContext(display, context) + } + + fun draw(scene: GlShapeScene): ByteBuffer? { + val pixels = scene.pixels + val target = targets.getOrPut(pixels) { createTargets(pixels) } + GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, target.msaa) + GLES30.glViewport(0, 0, pixels, pixels) + GLES30.glClearColor(0f, 0f, 0f, 0f) + GLES30.glClearStencil(0) + GLES30.glClearDepthf(1f) + GLES30.glDepthMask(true) + GLES30.glStencilMask(0xFF) + GLES30.glColorMask(true, true, true, true) + GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT or GLES30.GL_STENCIL_BUFFER_BIT or GLES30.GL_DEPTH_BUFFER_BIT) + GLES30.glEnable(GLES30.GL_BLEND) + GLES30.glBlendFuncSeparate(GLES30.GL_ONE, GLES30.GL_ONE_MINUS_SRC_ALPHA, GLES30.GL_ONE, GLES30.GL_ONE_MINUS_SRC_ALPHA) + GLES30.glEnable(GLES30.GL_STENCIL_TEST) + GLES30.glDisable(GLES30.GL_DEPTH_TEST) + GLES30.glDisable(GLES30.GL_CULL_FACE) + + upload(FILL, scene.fill) + upload(STROKE, scene.stroke) + upload(FILL_COVERS, scene.fillCovers) + upload(STROKE_COVERS, scene.strokeCovers) + upload(CIRCLES, scene.circles) + upload(LINES, scene.lineVertices) + if (scene.lineColors.size > 0) { + GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, buffers[LINE_COLORS]) + GLES30.glBufferData(GLES30.GL_ARRAY_BUFFER, scene.lineColors.size * 4, ints(scene.lineColors.data, scene.lineColors.size), GLES30.GL_STREAM_DRAW) + } + + val extent = pixels.toFloat() + for (batch in scene.batches) { + if (!batch.fill.isEmpty()) { + GLES30.glColorMask(false, false, false, false) + GLES30.glStencilFunc(GLES30.GL_ALWAYS, 0, 0xFF) + // nonzero: front faces +1, back faces -1, both wrapping at 256. + GLES30.glStencilOpSeparate(GLES30.GL_FRONT, GLES30.GL_KEEP, GLES30.GL_KEEP, GLES30.GL_INCR_WRAP) + GLES30.glStencilOpSeparate(GLES30.GL_BACK, GLES30.GL_KEEP, GLES30.GL_KEEP, GLES30.GL_DECR_WRAP) + drawPath(FILL, batch.fill, extent) + GLES30.glColorMask(true, true, true, true) + } + if (!batch.fillCovers.isEmpty()) drawCovers(FILL_COVERS, batch.fillCovers, extent) + if (!batch.circles.isEmpty()) drawCircles(batch.circles, extent) + if (!batch.stroke.isEmpty()) { + GLES30.glColorMask(false, false, false, false) + GLES30.glStencilFunc(GLES30.GL_ALWAYS, 1, 0xFF) + GLES30.glStencilOp(GLES30.GL_KEEP, GLES30.GL_KEEP, GLES30.GL_REPLACE) + drawPath(STROKE, batch.stroke, extent) + GLES30.glColorMask(true, true, true, true) + } + if (!batch.strokeCovers.isEmpty()) drawCovers(STROKE_COVERS, batch.strokeCovers, extent) + } + if (scene.lineCount > 0) drawLines(scene, extent) + + GLES30.glBindFramebuffer(GLES30.GL_READ_FRAMEBUFFER, target.msaa) + GLES30.glBindFramebuffer(GLES30.GL_DRAW_FRAMEBUFFER, target.resolve) + GLES30.glBlitFramebuffer(0, 0, pixels, pixels, 0, 0, pixels, pixels, GLES30.GL_COLOR_BUFFER_BIT, GLES30.GL_NEAREST) + GLES30.glBindFramebuffer(GLES30.GL_READ_FRAMEBUFFER, target.resolve) + val out = ByteBuffer.allocateDirect(pixels * pixels * 4).order(ByteOrder.nativeOrder()) + GLES30.glReadPixels(0, 0, pixels, pixels, GLES30.GL_RGBA, GLES30.GL_UNSIGNED_BYTE, out) + GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0) + if (!glOk("draw")) return null + out.rewind() + return out + } + + private fun drawPath( + buffer: Int, + range: IntRange, + extent: Float, + ) { + GLES30.glUseProgram(pathProgram) + GLES30.glUniform1f(pathExtentAt, extent) + GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, buffers[buffer]) + GLES30.glEnableVertexAttribArray(0) + GLES30.glVertexAttribPointer(0, 2, GLES30.GL_FLOAT, false, 8, 0) + GLES30.glDrawArrays(GLES30.GL_TRIANGLES, range.first, range.last - range.first + 1) + GLES30.glDisableVertexAttribArray(0) + } + + private fun drawCovers( + buffer: Int, + range: IntRange, + extent: Float, + ) { + // Paint where the stencil is not 0, and put it back to 0 for the next shapes. + GLES30.glStencilFunc(GLES30.GL_NOTEQUAL, 0, 0xFF) + GLES30.glStencilOp(GLES30.GL_KEEP, GLES30.GL_KEEP, GLES30.GL_ZERO) + GLES30.glUseProgram(coverProgram) + GLES30.glUniform1f(coverExtentAt, extent) + bindCorners() + GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, buffers[buffer]) + val stride = GlShapeScene.COVER_FLOATS * 4 + val offset = range.first * stride + instanced(1, 4, stride, offset) + instanced(2, 4, stride, offset + 16) + GLES30.glDrawArraysInstanced(GLES30.GL_TRIANGLES, 0, 6, range.last - range.first + 1) + disable(0, 1, 2) + } + + private fun drawCircles( + range: IntRange, + extent: Float, + ) { + GLES30.glStencilFunc(GLES30.GL_ALWAYS, 0, 0xFF) + GLES30.glStencilOp(GLES30.GL_KEEP, GLES30.GL_KEEP, GLES30.GL_KEEP) + GLES30.glUseProgram(circleProgram) + GLES30.glUniform1f(circleExtentAt, extent) + bindCorners() + GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, buffers[CIRCLES]) + val stride = GlShapeScene.CIRCLE_FLOATS * 4 + val offset = range.first * stride + instanced(1, 4, stride, offset) + instanced(2, 4, stride, offset + 16) + instanced(3, 4, stride, offset + 32) + instanced(4, 1, stride, offset + 48) + GLES30.glDrawArraysInstanced(GLES30.GL_TRIANGLES, 0, 6, range.last - range.first + 1) + disable(0, 1, 2, 3, 4) + } + + private fun drawLines( + scene: GlShapeScene, + extent: Float, + ) { + // Every line in one draw: each paints only nearer than what is there, + // so once per line whatever its own joins and crossings overlap, and + // each later line (nearer) over the earlier ones. + GLES30.glDisable(GLES30.GL_STENCIL_TEST) + GLES30.glEnable(GLES30.GL_DEPTH_TEST) + GLES30.glDepthFunc(GLES30.GL_LESS) + GLES30.glDepthMask(true) + GLES30.glUseProgram(lineProgram) + GLES30.glUniform1f(lineExtentAt, extent) + GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, buffers[LINES]) + GLES30.glEnableVertexAttribArray(0) + GLES30.glVertexAttribPointer(0, 3, GLES30.GL_FLOAT, false, 12, 0) + GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, buffers[LINE_COLORS]) + GLES30.glEnableVertexAttribArray(1) + GLES30.glVertexAttribPointer(1, 4, GLES30.GL_UNSIGNED_BYTE, true, 4, 0) + GLES30.glDrawArrays(GLES30.GL_TRIANGLES, 0, scene.lineVertices.size / 3) + GLES30.glDisableVertexAttribArray(0) + GLES30.glDisableVertexAttribArray(1) + GLES30.glDisable(GLES30.GL_DEPTH_TEST) + GLES30.glEnable(GLES30.GL_STENCIL_TEST) + } + + private fun bindCorners() { + GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, buffers[CORNERS]) + GLES30.glEnableVertexAttribArray(0) + GLES30.glVertexAttribPointer(0, 2, GLES30.GL_FLOAT, false, 8, 0) + GLES30.glVertexAttribDivisor(0, 0) + } + + private fun instanced( + location: Int, + size: Int, + stride: Int, + offset: Int, + ) { + GLES30.glEnableVertexAttribArray(location) + GLES30.glVertexAttribPointer(location, size, GLES30.GL_FLOAT, false, stride, offset) + GLES30.glVertexAttribDivisor(location, 1) + } + + private fun disable(vararg locations: Int) { + for (location in locations) { + GLES30.glVertexAttribDivisor(location, 0) + GLES30.glDisableVertexAttribArray(location) + } + } + + private fun upload( + index: Int, + values: GlShapeScene.Floats, + ) { + if (values.size == 0) return + GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, buffers[index]) + GLES30.glBufferData(GLES30.GL_ARRAY_BUFFER, values.size * 4, floats(values.data, values.size), GLES30.GL_STREAM_DRAW) + } + + /** [values] in the shared upload buffer, grown when too small. */ + private fun floats( + values: FloatArray, + size: Int, + ): FloatBuffer { + val bytes = staging(size * 4) + val buffer = bytes.asFloatBuffer() + buffer.put(values, 0, size) + buffer.rewind() + return buffer + } + + private fun ints( + values: IntArray, + size: Int, + ): java.nio.IntBuffer { + val bytes = staging(size * 4) + val buffer = bytes.asIntBuffer() + buffer.put(values, 0, size) + buffer.rewind() + return buffer + } + + private fun staging(bytes: Int): ByteBuffer { + if (uploadBytes.capacity() < bytes) { + uploadBytes = ByteBuffer.allocateDirect(Integer.highestOneBit(bytes) shl 1).order(ByteOrder.nativeOrder()) + } + uploadBytes.clear() + return uploadBytes + } + + private fun createTargets(pixels: Int): Targets { + val renderbuffers = IntArray(3) + GLES30.glGenRenderbuffers(3, renderbuffers, 0) + GLES30.glBindRenderbuffer(GLES30.GL_RENDERBUFFER, renderbuffers[0]) + GLES30.glRenderbufferStorageMultisample(GLES30.GL_RENDERBUFFER, samples, GLES30.GL_RGBA8, pixels, pixels) + GLES30.glBindRenderbuffer(GLES30.GL_RENDERBUFFER, renderbuffers[1]) + GLES30.glRenderbufferStorageMultisample(GLES30.GL_RENDERBUFFER, samples, GLES30.GL_DEPTH24_STENCIL8, pixels, pixels) + GLES30.glBindRenderbuffer(GLES30.GL_RENDERBUFFER, renderbuffers[2]) + GLES30.glRenderbufferStorage(GLES30.GL_RENDERBUFFER, GLES30.GL_RGBA8, pixels, pixels) + val framebuffers = IntArray(2) + GLES30.glGenFramebuffers(2, framebuffers, 0) + GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, framebuffers[0]) + GLES30.glFramebufferRenderbuffer(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_RENDERBUFFER, renderbuffers[0]) + GLES30.glFramebufferRenderbuffer(GLES30.GL_FRAMEBUFFER, GLES30.GL_DEPTH_STENCIL_ATTACHMENT, GLES30.GL_RENDERBUFFER, renderbuffers[1]) + check(GLES30.glCheckFramebufferStatus(GLES30.GL_FRAMEBUFFER) == GLES30.GL_FRAMEBUFFER_COMPLETE) { "MSAA framebuffer incomplete" } + GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, framebuffers[1]) + GLES30.glFramebufferRenderbuffer(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_RENDERBUFFER, renderbuffers[2]) + check(GLES30.glCheckFramebufferStatus(GLES30.GL_FRAMEBUFFER) == GLES30.GL_FRAMEBUFFER_COMPLETE) { "resolve framebuffer incomplete" } + GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0) + return Targets(framebuffers[0], framebuffers[1]) + } + + private fun program( + vertex: String, + fragment: String, + ): Int { + fun shader( + type: Int, + source: String, + ): Int { + val shader = GLES30.glCreateShader(type) + GLES30.glShaderSource(shader, source) + GLES30.glCompileShader(shader) + val ok = IntArray(1) + GLES30.glGetShaderiv(shader, GLES30.GL_COMPILE_STATUS, ok, 0) + check(ok[0] != 0) { "shader: " + GLES30.glGetShaderInfoLog(shader) } + return shader + } + val program = GLES30.glCreateProgram() + GLES30.glAttachShader(program, shader(GLES30.GL_VERTEX_SHADER, vertex)) + GLES30.glAttachShader(program, shader(GLES30.GL_FRAGMENT_SHADER, fragment)) + GLES30.glLinkProgram(program) + val ok = IntArray(1) + GLES30.glGetProgramiv(program, GLES30.GL_LINK_STATUS, ok, 0) + check(ok[0] != 0) { "program: " + GLES30.glGetProgramInfoLog(program) } + return program + } + + private fun glOk(where: String): Boolean { + val error = GLES30.glGetError() + if (error == GLES30.GL_NO_ERROR) return true + Log.w(TAG, "GL error 0x${Integer.toHexString(error)} in $where") + return false + } + + companion object { + const val FILL = 0 + const val STROKE = 1 + const val FILL_COVERS = 2 + const val STROKE_COVERS = 3 + const val CIRCLES = 4 + const val LINES = 5 + const val CORNERS = 6 + const val LINE_COLORS = 7 + + fun create(): Context { + 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" } + val attributes = + intArrayOf( + EGL14.EGL_RENDERABLE_TYPE, EGL_OPENGL_ES3_BIT, + EGL14.EGL_SURFACE_TYPE, EGL14.EGL_PBUFFER_BIT, + 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) + check(EGL14.eglChooseConfig(display, attributes, 0, configs, 0, 1, count, 0) && count[0] > 0) { "no GLES 3 config" } + val config = configs[0] + val context = + EGL14.eglCreateContext(display, config, EGL14.EGL_NO_CONTEXT, intArrayOf(EGL14.EGL_CONTEXT_CLIENT_VERSION, 3, EGL14.EGL_NONE), 0) + check(context != EGL14.EGL_NO_CONTEXT) { "eglCreateContext" } + val surface = EGL14.eglCreatePbufferSurface(display, config, intArrayOf(EGL14.EGL_WIDTH, 1, EGL14.EGL_HEIGHT, 1, EGL14.EGL_NONE), 0) + check(surface != EGL14.EGL_NO_SURFACE) { "eglCreatePbufferSurface" } + check(EGL14.eglMakeCurrent(display, surface, surface, context)) { "eglMakeCurrent" } + return Context(display, context, surface) + } + + private fun staticFloats(values: FloatArray): FloatBuffer { + val buffer = ByteBuffer.allocateDirect(values.size * 4).order(ByteOrder.nativeOrder()).asFloatBuffer() + buffer.put(values) + buffer.rewind() + return buffer + } + + private const val CIRCLE_VERTEX = """#version 300 es +layout(location = 0) in vec2 corner; +layout(location = 1) in vec4 geometry; +layout(location = 2) in vec4 fillColor; +layout(location = 3) in vec4 strokeColor; +layout(location = 4) in float kind; +uniform float extent; +out vec2 pixel; +flat out vec4 vGeometry; +flat out vec4 vFill; +flat out vec4 vStroke; +flat out float vKind; +void main() { + vec2 lo; + vec2 hi; + if (kind > 0.5) { + lo = geometry.xy; + hi = lo + geometry.zw; + } else { + float reach = geometry.z + geometry.w * 0.5 + 1.0; + lo = geometry.xy - reach; + hi = geometry.xy + reach; + } + vec2 px = mix(lo, hi, corner); + vec2 unit = px / extent; + gl_Position = vec4(unit.x * 2.0 - 1.0, unit.y * 2.0 - 1.0, 0.0, 1.0); + pixel = px; + vGeometry = geometry; + vFill = fillColor; + vStroke = strokeColor; + vKind = kind; +} +""" + + private const val CIRCLE_FRAGMENT = """#version 300 es +precision highp float; +in vec2 pixel; +flat in vec4 vGeometry; +flat in vec4 vFill; +flat in vec4 vStroke; +flat in float vKind; +out vec4 color; +void main() { + if (vKind > 0.5) { + color = vFill; + return; + } + float d = length(pixel - vGeometry.xy); + float radius = vGeometry.z; + float halfWidth = vGeometry.w * 0.5; + float fillCoverage = clamp(radius - d + 0.5, 0.0, 1.0); + float strokeCoverage = clamp(radius + halfWidth - d + 0.5, 0.0, 1.0) - clamp(radius - halfWidth - d + 0.5, 0.0, 1.0); + vec4 fill = vFill * fillCoverage; + vec4 stroke = vStroke * strokeCoverage; + color = stroke + fill * (1.0 - stroke.a); +} +""" + + private const val PATH_VERTEX = """#version 300 es +layout(location = 0) in vec2 position; +uniform float extent; +void main() { + vec2 unit = position / extent; + gl_Position = vec4(unit.x * 2.0 - 1.0, unit.y * 2.0 - 1.0, 0.0, 1.0); +} +""" + + private const val LINE_VERTEX = """#version 300 es +layout(location = 0) in vec3 position; +layout(location = 1) in vec4 lineColor; +uniform float extent; +flat out vec4 vColor; +void main() { + vec2 unit = position.xy / extent; + gl_Position = vec4(unit.x * 2.0 - 1.0, unit.y * 2.0 - 1.0, position.z * 2.0 - 1.0, 1.0); + vColor = lineColor; +} +""" + + private const val COVER_VERTEX = """#version 300 es +layout(location = 0) in vec2 corner; +layout(location = 1) in vec4 rect; +layout(location = 2) in vec4 coverColor; +uniform float extent; +flat out vec4 vColor; +void main() { + vec2 px = mix(rect.xy, rect.zw, corner); + vec2 unit = px / extent; + gl_Position = vec4(unit.x * 2.0 - 1.0, unit.y * 2.0 - 1.0, 0.0, 1.0); + vColor = coverColor; +} +""" + + private const val PATH_FRAGMENT = """#version 300 es +precision mediump float; +uniform vec4 color; +out vec4 fragColor; +void main() { + fragColor = color; +} +""" + + private const val COVER_FRAGMENT = """#version 300 es +precision mediump float; +flat in vec4 vColor; +out vec4 fragColor; +void main() { + fragColor = vColor; +} +""" + } + } +} diff --git a/src/main/java/com/mapconductor/core/shapetile/GlShapeScene.kt b/src/main/java/com/mapconductor/core/shapetile/GlShapeScene.kt new file mode 100644 index 0000000..bac3eb7 --- /dev/null +++ b/src/main/java/com/mapconductor/core/shapetile/GlShapeScene.kt @@ -0,0 +1,453 @@ +package com.mapconductor.core.shapetile + +import com.mapconductor.core.InternalMapConductorApi +import kotlin.math.PI +import kotlin.math.ceil +import kotlin.math.cos +import kotlin.math.floor +import kotlin.math.max +import kotlin.math.min +import kotlin.math.sin +import kotlin.math.sqrt + +/** + * What one shape tile draws on the GPU ([GlShapeRasterizer]): plain float + * arrays, built here without touching GL so the building can be tested on the JVM. + * The counterpart of ios-sdk-core's `MetalPathRasterizer.Scene` and + * `PathSceneBuilder`; coordinates are tile pixels, y down. + * + * Three kinds of content, drawn as the CPU path ([android.graphics.Canvas]) draws them: + * - **Circles** (and one-pixel dots): one instance each, fill and outline from + * the distance to the centre. + * - **Polygons**: a nonzero fill by stencil-then-cover (a fan of triangles from + * one point per ring, +1 front / -1 back), then the outline as segment quads + * plus vertex discs written to the stencil and covered once -- a translucent + * outline is not painted twice where its joins overlap, as with `drawPath`. + * - **Polylines**: each its own depth, nearer for each later line, drawn with + * `GL_LESS`: a line's own overlapping triangles are at one depth and paint + * once, a later line passes over an earlier one, and all of them are one draw + * call. (ios-sdk-core does this with stencil numbers written by the fragment + * shader; GLES cannot write the stencil from a shader.) + * + * Shapes are drawn in the order added. Circles of a circle tile go in one + * instanced draw ([orderedCircles]), which keeps their order by itself; other + * shapes are grouped into batches of shapes whose boxes do not overlap + * (checked on an 8 px grid), where order does not show. + */ +@InternalMapConductorApi +internal class GlShapeScene( + val pixels: Int, + /** + * Circles go into one ordered list and nothing else may be added: a + * circle tile is mostly overlapping circles, which would split batches + * into thousands. [addPolygon] then throws [NeedsBatches]. + */ + val orderedCircles: Boolean = false, +) { + /** Thrown by [addPolygon] in [orderedCircles] mode: draw the tile again batched. */ + class NeedsBatches : RuntimeException(null, null, false, false) + + /** A growable float array. */ + class Floats(capacity: Int = 1024) { + var data = FloatArray(capacity) + private set + var size = 0 + private set + + fun add(value: Float) { + if (size == data.size) data = data.copyOf(max(16, data.size * 2)) + data[size++] = value + } + + fun clear() { + size = 0 + } + + fun add2( + a: Float, + b: Float, + ) { + if (size + 2 > data.size) data = data.copyOf(max(16, data.size * 2)) + data[size++] = a + data[size++] = b + } + } + + /** Ranges of each array that a batch draws, as `[start, end)` element indices. */ + class Batch( + val fill: IntRange, + val fillCovers: IntRange, + val circles: IntRange, + val stroke: IntRange, + val strokeCovers: IntRange, + ) + + /** Fill fans: `x, y` per vertex, triangles. */ + val fill = Floats() + + /** Polygon outlines: `x, y` per vertex, triangles. */ + val stroke = Floats() + + /** `left, top, right, bottom, r, g, b, a` (premultiplied) per cover. */ + val fillCovers = Floats(256) + val strokeCovers = Floats(256) + + /** + * [CIRCLE_FLOATS] per circle: `x, y, radius, strokeWidth, fill rgba, + * stroke rgba, kind` -- kind 0 a circle, 1 a rectangle at `x, y` of + * `radius` by `strokeWidth` (a pixel-sized dot). + */ + val circles = Floats() + val batches = ArrayList() + + /** Polyline triangles: `x, y, depth` per vertex. */ + val lineVertices = Floats() + + /** Per polyline vertex: premultiplied RGBA bytes, `r` lowest. */ + val lineColors = IntList() + + /** Polylines recorded. */ + var lineCount = 0 + private set + + private val lineScratch = Floats() + + val isEmpty: Boolean + get() = fillCovers.size == 0 && strokeCovers.size == 0 && circles.size == 0 && lineVertices.size == 0 + + private val cell = 8 + private val cells = (pixels + cell - 1) / cell + private val occupied = BooleanArray(cells * cells) + private val touched = IntList() + private var fillStart = 0 + private var fillCoverStart = 0 + private var circleStart = 0 + private var strokeStart = 0 + private var strokeCoverStart = 0 + + /** A circle (kind 0) or a pixel rectangle (kind 1); see [circles]. */ + fun addCircle( + x: Float, + y: Float, + radius: Float, + strokeWidth: Float, + fill: Int, + stroke: Int, + kind: Int, + ) { + if (!orderedCircles) { + val box = + if (kind == 1) { + floatArrayOf(x, y, x + radius, y + strokeWidth) + } else { + val reach = radius + strokeWidth / 2f + 1f + floatArrayOf(x - reach, y - reach, x + reach, y + reach) + } + if (!claim(box)) return + } + circles.add2(x, y) + circles.add2(radius, strokeWidth) + addColor(circles, fill) + addColor(circles, stroke) + circles.add(kind.toFloat()) + } + + /** + * A polygon: [rings] in tile pixels (`x, y, ...`, the outline first) filled + * nonzero with [fill], and the outline drawn [strokeWidth] wide with + * [outline]; a colour of 0 is not drawn. + */ + fun addPolygon( + rings: List, + fill: Int, + outline: Int, + strokeWidth: Float, + ) { + if (orderedCircles) throw NeedsBatches() + val first = rings.firstOrNull() ?: return + if (first.size < 6) return + val bounds = bounds(first) + val box = if (outline != 0) inflate(bounds, strokeWidth / 2f) else bounds + if (!claim(inflate(box, 1f))) return + if (fill != 0) { + val px = first[0] + val py = first[1] + for (ring in rings) { + val n = ring.size / 2 + if (n < 3) continue + for (i in 0 until n) { + val j = (i + 1) % n + this.fill.add2(px, py) + this.fill.add2(ring[i * 2], ring[i * 2 + 1]) + this.fill.add2(ring[j * 2], ring[j * 2 + 1]) + } + } + addCover(fillCovers, inflate(bounds, 1f), fill) + } + if (outline != 0) { + strokeGeometry(first, closed = true, halfWidth = strokeWidth / 2f, out = stroke) + addCover(strokeCovers, inflate(box, 1f), outline) + } + } + + /** A polyline in tile pixels (`x, y, ...`, two points or more). */ + fun addLine( + points: FloatArray, + color: Int, + strokeWidth: Float, + ) { + if (points.size < 4) return + lineScratch.clear() + strokeGeometry(points, closed = false, halfWidth = strokeWidth / 2f, out = lineScratch) + endLine(color) + } + + /** A polyline that collapsed to one point: a disc of [radius] round [x], [y]. */ + fun addLineDot( + x: Float, + y: Float, + radius: Float, + color: Int, + ) { + lineScratch.clear() + disc(x, y, radius, lineScratch) + endLine(color) + } + + /** Closes the last batch; the scene is complete. */ + fun finish(): GlShapeScene { + close() + return this + } + + /** Moves the line in [lineScratch] into [lineVertices] at the next depth. */ + private fun endLine(color: Int) { + val count = lineScratch.size / 2 + if (count == 0) return + lineCount++ + // Nearer for each later line; 2^-22 apart is several steps of a 24-bit depth. + val depth = 1f - lineCount / 4_194_304f + val packed = packColor(color) + val points = lineScratch.data + for (v in 0 until count) { + lineVertices.add2(points[v * 2], points[v * 2 + 1]) + lineVertices.add(depth) + lineColors.add(packed) + } + } + + private fun close() { + val batch = + Batch( + fill = fillStart / 2 until fill.size / 2, + fillCovers = fillCoverStart / COVER_FLOATS until fillCovers.size / COVER_FLOATS, + circles = circleStart / CIRCLE_FLOATS until circles.size / CIRCLE_FLOATS, + stroke = strokeStart / 2 until stroke.size / 2, + strokeCovers = strokeCoverStart / COVER_FLOATS until strokeCovers.size / COVER_FLOATS, + ) + if (!batch.fillCovers.isEmpty() || !batch.circles.isEmpty() || !batch.strokeCovers.isEmpty()) batches.add(batch) + for (k in 0 until touched.size) occupied[touched[k]] = false + touched.clear() + fillStart = fill.size + fillCoverStart = fillCovers.size + circleStart = circles.size + strokeStart = stroke.size + strokeCoverStart = strokeCovers.size + } + + /** + * Takes the cells of [box] (left, top, right, bottom) for the current batch, + * closing it first when one of them is taken. False when the box is off the tile. + */ + private fun claim(box: FloatArray): Boolean { + if (box[2] < 0f || box[3] < 0f || box[0] > pixels || box[1] > pixels) return false + val x0 = max(0, floor(box[0]).toInt() / cell) + val y0 = max(0, floor(box[1]).toInt() / cell) + val x1 = min(cells - 1, ceil(box[2]).toInt() / cell) + val y1 = min(cells - 1, ceil(box[3]).toInt() / cell) + if (x0 > x1 || y0 > y1) return false + var overlaps = false + loop@ for (y in y0..y1) { + for (x in x0..x1) { + if (occupied[y * cells + x]) { + overlaps = true + break@loop + } + } + } + if (overlaps) close() + for (y in y0..y1) { + for (x in x0..x1) { + val i = y * cells + x + if (!occupied[i]) { + occupied[i] = true + touched.add(i) + } + } + } + return true + } + + private fun addCover( + to: Floats, + box: FloatArray, + color: Int, + ) { + to.add2(box[0], box[1]) + to.add2(box[2], box[3]) + addColor(to, color) + } + + @InternalMapConductorApi + companion object { + const val COVER_FLOATS = 8 + const val CIRCLE_FLOATS = 13 + + /** Premultiplied RGBA bytes of an ARGB colour, `r` in the lowest byte. */ + fun packColor(argb: Int): Int { + val a = argb ushr 24 + fun channel(shift: Int) = (((argb shr shift) and 0xFF) * a + 127) / 255 + return channel(16) or (channel(8) shl 8) or (channel(0) shl 16) or (a shl 24) + } + + /** Premultiplied `r, g, b, a` of an ARGB colour. */ + fun addColor( + to: Floats, + argb: Int, + ) { + val a = (argb ushr 24) / 255f + to.add2(((argb shr 16) and 0xFF) / 255f * a, ((argb shr 8) and 0xFF) / 255f * a) + to.add2((argb and 0xFF) / 255f * a, a) + } + + private fun bounds(points: FloatArray): FloatArray { + val box = floatArrayOf(Float.MAX_VALUE, Float.MAX_VALUE, -Float.MAX_VALUE, -Float.MAX_VALUE) + var i = 0 + while (i < points.size) { + box[0] = min(box[0], points[i]) + box[2] = max(box[2], points[i]) + box[1] = min(box[1], points[i + 1]) + box[3] = max(box[3], points[i + 1]) + i += 2 + } + return box + } + + private fun inflate( + box: FloatArray, + d: Float, + ) = floatArrayOf(box[0] - d, box[1] - d, box[2] + d, box[3] + d) + + /** Unit circles (cos, sin pairs) for 6..32 segments, made once. */ + private val unitCircles: Array = + Array(33) { segments -> + if (segments < 6) { + FloatArray(0) + } else { + FloatArray(segments * 2) { i -> + val a = (i / 2).toDouble() / segments * 2 * PI + (if (i % 2 == 0) cos(a) else sin(a)).toFloat() + } + } + } + + /** Segments of a disc of [radius] px: enough for its round edge to look round. */ + private fun circleSegments(radius: Float): Int = (ceil(radius * 2f).toInt() + 4).coerceIn(6, 32) + + /** + * A quad per segment and a disc per vertex (round joins and caps), as + * triangles. They overlap; the stencil takes their union. + */ + fun strokeGeometry( + points: FloatArray, + closed: Boolean, + halfWidth: Float, + out: Floats, + ) { + val n = points.size / 2 + if (n < 2 || halfWidth <= 0f) return + val edges = if (closed) n else n - 1 + for (i in 0 until edges) { + val j = (i + 1) % n + val ax = points[i * 2] + val ay = points[i * 2 + 1] + val bx = points[j * 2] + val by = points[j * 2 + 1] + val dx = bx - ax + val dy = by - ay + val length = sqrt(dx * dx + dy * dy) + if (length <= 0f) continue + val nx = -dy / length * halfWidth + val ny = dx / length * halfWidth + out.add2(ax + nx, ay + ny) + out.add2(ax - nx, ay - ny) + out.add2(bx + nx, by + ny) + out.add2(ax - nx, ay - ny) + out.add2(bx - nx, by - ny) + out.add2(bx + nx, by + ny) + } + for (i in 0 until n) disc(points[i * 2], points[i * 2 + 1], halfWidth, out) + } + + /** A disc of [radius] round [cx], [cy], as a fan of triangles. */ + fun disc( + cx: Float, + cy: Float, + radius: Float, + out: Floats, + ) { + val unit = unitCircles[circleSegments(radius)] + val segments = unit.size / 2 + var px = cx + unit[(segments - 1) * 2] * radius + var py = cy + unit[(segments - 1) * 2 + 1] * radius + for (k in 0 until segments) { + val nx = cx + unit[k * 2] * radius + val ny = cy + unit[k * 2 + 1] * radius + out.add2(cx, cy) + out.add2(px, py) + out.add2(nx, ny) + px = nx + py = ny + } + } + } +} + +/** A growable int array. */ +@InternalMapConductorApi +internal class IntList( + capacity: Int = 256, +) { + var data = IntArray(capacity) + private set + var size = 0 + private set + + operator fun get(index: Int): Int = data[index] + + fun add(value: Int) { + if (size == data.size) data = data.copyOf(max(16, data.size * 2)) + data[size++] = value + } + + fun clear() { + size = 0 + } +} + +/** World-pixel points (`x, y, ...`) as tile pixels: [originX], [originY] at 0, [r] pixels per unit. */ +internal fun toTilePixels( + points: DoubleArray, + originX: Double, + originY: Double, + r: Float, +): FloatArray { + val out = FloatArray(points.size) + var i = 0 + while (i < points.size) { + out[i] = ((points[i] - originX) * r).toFloat() + out[i + 1] = ((points[i + 1] - originY) * r).toFloat() + i += 2 + } + return out +} diff --git a/src/main/java/com/mapconductor/core/shapetile/ShapeGridIndex.kt b/src/main/java/com/mapconductor/core/shapetile/ShapeGridIndex.kt new file mode 100644 index 0000000..e776dd2 --- /dev/null +++ b/src/main/java/com/mapconductor/core/shapetile/ShapeGridIndex.kt @@ -0,0 +1,192 @@ +package com.mapconductor.core.shapetile + +import com.mapconductor.core.InternalMapConductorApi +import com.mapconductor.core.polygon.IntList +import com.mapconductor.core.polygon.POLYGON_CELL +import com.mapconductor.core.polygon.POLYGON_MAX_CELLS +import java.util.BitSet +import kotlin.math.floor + +/** A multiresolution grid: wide shapes use coarser cells, not a global scan list. */ +@InternalMapConductorApi +internal class ShapeGridIndex private constructor( + val cells: HashMap, + /** Shapes that formerly needed a global scan; retained for diagnostics. */ + val large: IntArray, + private val levels: List, + private val count: Int, + private val legacyLarge: IntArray = IntArray(0), +) { + @InternalMapConductorApi + private class Level( + val size: Double, + val cells: HashMap, + val groups: HashMap>? = null, + ) + + @InternalMapConductorApi + constructor(cells: HashMap, large: IntArray) : this( + cells, large, listOf(Level(POLYGON_CELL, cells)), + maxOf(cells.values.maxOfOrNull { it.maxOrNull() ?: -1 } ?: -1, large.maxOrNull() ?: -1) + 1, + large, + ) + + fun query( + bboxOf: (Int) -> DoubleArray?, + minX: Double, + minY: Double, + maxX: Double, + maxY: Double, + order: StorageOrder? = null, + ): IntArray { + val seen = BitSet(count) + val matches = BitSet(count) + + fun take(i: Int) { + seen.set(i) + } + for (i in legacyLarge) take(i) + for (level in levels) { + val cx0 = floor(minX / level.size).toLong() + val cx1 = floor(maxX / level.size).toLong() + val cy0 = floor(minY / level.size).toLong() + val cy1 = floor(maxY / level.size).toLong() + val area = (cx1 - cx0 + 1).toDouble() * (cy1 - cy0 + 1) + val groups = level.groups + if (area > 16_384 && groups != null) { + val gx0 = Math.floorDiv(cx0, 16L) + val gx1 = Math.floorDiv(cx1, 16L) + val gy0 = Math.floorDiv(cy0, 16L) + val gy1 = Math.floorDiv(cy1, 16L) + val groupArea = (gx1 - gx0 + 1).toDouble() * (gy1 - gy0 + 1) + if (groupArea > groups.size) { + for (bucket in level.cells.values) for (i in bucket) take(i) + } else { + for (gx in gx0..gx1) { + for (gy in gy0..gy1) { + val buckets = groups[cellKey(gx, gy)] ?: continue + for (bucket in buckets) for (i in bucket) take(i) + } + } + } + } else if (area > level.cells.size) { + // A zoomed-out tile must not enumerate millions of empty cells. + for (bucket in level.cells.values) for (i in bucket) take(i) + } else { + for (cx in cx0..cx1) { + for (cy in cy0..cy1) { + val bucket = level.cells[cellKey(cx, cy)] ?: continue + for (i in bucket) take(i) + } + } + } + } + // Read boxes in storage order. File-backed geometry can then stream + // through its block cache instead of seeking in spatial bucket order. + fun check(candidate: Int) { + val b = bboxOf(candidate) + if (b != null && b[0] <= maxX && b[2] >= minX && b[1] <= maxY && b[3] >= minY) matches.set(candidate) + } + if (order == null) { + var candidate = seen.nextSetBit(0) + while (candidate >= 0) { + check(candidate) + candidate = seen.nextSetBit(candidate + 1) + } + } else { + val positions = BitSet(count) + var candidate = seen.nextSetBit(0) + while (candidate >= 0) { + positions.set(order.positionOf[candidate]) + candidate = seen.nextSetBit(candidate + 1) + } + var position = positions.nextSetBit(0) + while (position >= 0) { + check(order.indexAt[position]) + position = positions.nextSetBit(position + 1) + } + } + // A bitset removes duplicates before bounding-box checks and produces + // draw order without sorting the same shape once for every cell it spans. + val out = IntArray(matches.cardinality()) + var next = matches.nextSetBit(0) + var at = 0 + while (next >= 0) { + out[at++] = next + next = matches.nextSetBit(next + 1) + } + return out + } + + @InternalMapConductorApi + companion object { + /** [bboxOf] is called in [order] (storage order) when given; buckets need no order. */ + fun build( + count: Int, + order: StorageOrder? = null, + bboxOf: (Int) -> DoubleArray?, + ): ShapeGridIndex { + val buckets = Array(7) { HashMap() } + val canGroup = BooleanArray(7) { true } + val large = IntList() + for (p in 0 until count) { + val i = order?.indexAt?.get(p) ?: p + val b = bboxOf(i) ?: continue + var level = 0 + var size = POLYGON_CELL + + fun cellsWide() = + (floor(b[2] / size) - floor(b[0] / size) + 1) * + (floor(b[3] / size) - floor(b[1] / size) + 1) + if (cellsWide() > POLYGON_MAX_CELLS) large.add(i) + while (level < buckets.lastIndex && cellsWide() > 16) { + level++ + size *= 4 + } + val cx0 = floor(b[0] / size).toLong() + val cx1 = floor(b[2] / size).toLong() + val cy0 = floor(b[1] / size).toLong() + val cy1 = floor(b[3] / size).toLong() + // Group keys can be decoded only when Y is in the packed key's + // nonnegative range. Keep the original query for polar overhangs. + if (cy0 < 0 || cy1 >= 1_048_576L) canGroup[level] = false + for (cx in cx0..cx1) { + for (cy in cy0..cy1) { + buckets[level].getOrPut(cellKey(cx, cy)) { IntList() }.add(i) + } + } + } + val levels = + buckets.mapIndexed { level, map -> + val packed = HashMap(map.size * 2) + for ((key, list) in map) packed[key] = list.toArray() + val groups = + if (canGroup[level]) { + val grouped = HashMap>() + for ((key, values) in packed) { + val cx = Math.floorDiv(key, 1_048_576L) + val cy = Math.floorMod(key, 1_048_576L) + grouped + .getOrPut(cellKey(Math.floorDiv(cx, 16L), Math.floorDiv(cy, 16L))) { ArrayList() } + .add(values) + } + HashMap>().also { out -> + for ((key, values) in grouped) { + out[key] = + values.toTypedArray() + } + } + } else { + null + } + Level(POLYGON_CELL * (1 shl (level * 2)), packed, groups) + } + return ShapeGridIndex(levels[0].cells, large.toArray(), levels.filter { it.cells.isNotEmpty() }, count) + } + + fun cellKey( + cx: Long, + cy: Long, + ): Long = cx * 1_048_576L + cy + } +} diff --git a/src/main/java/com/mapconductor/core/shapetile/ShapeTileRenderer.kt b/src/main/java/com/mapconductor/core/shapetile/ShapeTileRenderer.kt new file mode 100644 index 0000000..83ceed4 --- /dev/null +++ b/src/main/java/com/mapconductor/core/shapetile/ShapeTileRenderer.kt @@ -0,0 +1,730 @@ +package com.mapconductor.core.shapetile + +import androidx.core.graphics.createBitmap +import com.mapconductor.core.InternalMapConductorApi +import com.mapconductor.core.ResourceProvider +import com.mapconductor.core.tileserver.ScratchPool +import com.mapconductor.core.tileserver.TilePngEncoder +import com.mapconductor.core.tileserver.TileProviderInterface +import com.mapconductor.core.tileserver.TileRequest +import java.io.ByteArrayOutputStream +import java.nio.ByteBuffer +import java.util.BitSet +import java.util.concurrent.atomic.AtomicLong +import java.util.concurrent.atomic.AtomicReferenceArray +import kotlin.math.max +import kotlin.math.roundToInt +import android.graphics.Bitmap +import android.graphics.Canvas +import android.graphics.Color +import android.graphics.Paint +import android.graphics.Path +import android.util.LruCache + +/** + * Draws a list of shapes into raster tiles, served by + * [com.mapconductor.core.tileserver.LocalTileServer]: the part the polygon + * tiles and the polyline tiles share. What a shape is and how it is drawn is + * the [Painter]'s; everything else is here -- the grid index, a simplified copy + * per zoom, the tile cache and its invalidation, the scratch bitmaps, PNG + * encoding and cancellation. The counterpart of the "Shape tiles" section of + * js-sdk-core's tile-sw.js and ios-sdk-core's `ShapeTileRenderer`. + * + * Geometry is in tile units (a tile is [tileSize] wide whatever its pixels); + * a tile is drawn [pixelScale] pixels per unit, so a stroke of 1 dp is one + * unit wide, as on the web where it is one CSS pixel, and stays that wide at + * every zoom. + * + * Tiles are cached here without the version the map sees in their URL. An + * in-place change ([update]) drops only the tiles that overlap what changed, + * widened by the widest stroke; the map asks again for every tile because the + * version moved, and the ones the change did not touch come straight back + * from the cache. + * + * [renderTile] runs concurrently on the tile server's threads. Every change + * replaces the model it reads, so a tile is drawn from one consistent list. + */ +@InternalMapConductorApi +internal class ShapeTileRenderer( + val tileSize: Int = 256, + cacheSizeBytes: Int = DEFAULT_CACHE_BYTES, + private val pixelScale: () -> Float = { ResourceProvider.getDensity() }, + private val painter: Painter, + /** What a cancelled tile throws: a failure the map may retry, never an empty tile. */ + private val cancelled: () -> Exception = { TileRenderCancelled() }, +) : TileProviderInterface { + /** What a kind of shape is to the tiles. */ + @InternalMapConductorApi + interface Painter { + /** Web Mercator `minX, minY, maxX, maxY`. */ + fun bbox(item: T): DoubleArray + + /** + * The widest the shape is drawn past its bounding box, as a stroke + * width in tile units (dp): half of it reaches past each side. 0 when + * nothing is drawn outside the box. + */ + fun strokeWidth(item: T): Float + + val cacheSimplifiedShapes: Boolean get() = true + val thinSubpixelOverlaps: Boolean get() = false + + fun isVisible(item: T): Boolean = true + + /** Pixel slot, -1 outside the tile, or -2 when the shape is not subpixel. */ + fun subpixelSlot( + item: T, + scale: Double, + originX: Double, + originY: Double, + tileSize: Int, + ): Int = -2 + + /** The shape at a zoom whose world is [scale] units wide. Cached per zoom. */ + fun simplify( + item: T, + scale: Double, + ): Any + + /** + * Draws [shape] (from [simplify]) with its origin at [originX], [originY] + * world units and [r] pixels per unit. True if anything was drawn. + */ + fun draw( + canvas: Canvas, + item: T, + shape: Any, + originX: Double, + originY: Double, + r: Float, + paints: Paints, + ): Boolean + + /** Whether [record] can put this kind of shape in a [GlShapeScene]. */ + val drawsOnGpu: Boolean get() = false + + /** + * Records [shape] into [scene] for the GPU, exactly as [draw] would draw + * it on the canvas. True if anything was recorded. + */ + fun record( + scene: GlShapeScene, + item: T, + shape: Any, + originX: Double, + originY: Double, + r: Float, + ): Boolean = throw UnsupportedOperationException() + + /** + * Records every shape of [candidates] at once, reading [storage] + * directly instead of an item per shape; false when this painter or + * storage has no such path (then the renderer records them one by one). + * Must make the same choices as the one-by-one path. + */ + fun recordAll( + scene: GlShapeScene, + storage: ShapeTileStorage, + candidates: IntArray, + active: BitSet?, + scale: Double, + originX: Double, + originY: Double, + tileSize: Int, + r: Float, + checkCancelled: () -> Unit, + ): Boolean = false + } + + /** Paints and a path, one set per tile drawn. */ + @InternalMapConductorApi + class Paints { + val fill = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.FILL } + val stroke = + Paint(Paint.ANTI_ALIAS_FLAG).apply { + style = Paint.Style.STROKE + strokeJoin = Paint.Join.ROUND + strokeCap = Paint.Cap.ROUND + } + + /** Not anti-aliased: a polygon under a pixel is one whole pixel. */ + val dot = Paint().apply { style = Paint.Style.FILL } + val path = Path() + } + + @InternalMapConductorApi + private class Simplified( + val source: Any, + val shape: Any, + ) + + /** + * What tiles are drawn from. [perZoom] is shared by the models an + * [update] derives from one [setItems]: an entry is used only while its + * source is still the item at that index, so a changed item is + * simplified again without clearing anything. + */ + @InternalMapConductorApi + private class Model( + val storage: ShapeTileStorage, + val index: ShapeGridIndex, + val maxStroke: Float, + val perZoom: LinkedHashMap>, + val active: BitSet? = null, + ) + + @Volatile + private var model: Model? = null + private val modelLock = Any() + + private fun acquireModel(): Model? = + synchronized(modelLock) { + model?.also { it.storage.retain() } + } + + /** Takes ownership of the replacement's storage reference. */ + private fun replaceModel(next: Model?) = + synchronized(modelLock) { + val previous = model + model = next + previous?.storage?.release() + } + + fun itemAt(index: Int): T? { + val current = acquireModel() ?: return null + return try { + current.storage[index] + } finally { + current.storage.release() + } + } + + /** + * Indices of the items whose bounding box meets the given one (Web Mercator, + * [0, 1]), through the index the tiles use. For taps: the caller tests these + * few against their states instead of reading every state. + */ + fun candidates( + minX: Double, + minY: Double, + maxX: Double, + maxY: Double, + ): IntArray { + val m = acquireModel() ?: return IntArray(0) + return try { + m.index.query( + { index -> if (m.active?.get(index) == false) null else m.storage.bbox(index) }, + minX, minY, maxX, maxY, m.storage.storageOrder, + ) + } finally { + m.storage.release() + } + } + + /** The widest stroke drawn, in pixels of a [tileSize] tile. */ + val maxStroke: Float get() = model?.maxStroke ?: 0f + + /** Immutable membership snapshot; geometry and its spatial index stay shared. */ + fun setActiveItems(active: BitSet) { + synchronized(modelLock) { + val current = model ?: return + current.storage.retain() + replaceModel(Model(current.storage, current.index, current.maxStroke, current.perZoom, active)) + } + synchronized(cacheLock) { + generation.incrementAndGet() + tileCache.evictAll() + } + } + + /** Bumped by every change, so a tile drawn before it is not cached after it. */ + private val generation = AtomicLong() + + private val tileCache = + object : LruCache(cacheSizeBytes) { + override fun sizeOf( + key: Long, + value: ByteArray, + ): Int = value.size + } + private val cacheLock = Any() + + // Pools, not thread-locals: tiles are drawn on the map SDK's threads, which can + // outlive this renderer (see ScratchPool) and would keep a tile bitmap each. + private val scratchBitmaps = ScratchPool() + private val byteStreams = ScratchPool() + + /** Replaces every shape. Draw order is list order. */ + fun setItems(items: List) { + setStorage(MemoryShapeTileStorage(items, painter)) + } + + /** Builds the shared shape index without materialising file-backed geometry. Consumes [storage]. */ + fun setStorage( + storage: ShapeTileStorage, + checkCancelled: () -> Unit = {}, + ) { + val index = + try { + var built = 0 + ShapeGridIndex + .build(storage.size, storage.storageOrder) { + if (built++ % 4096 == 0) checkCancelled() + storage.bbox(it) + }.also { checkCancelled() } + } catch (error: Throwable) { + storage.release() + throw error + } + replaceModel(Model(storage, index, storage.maxStroke, LinkedHashMap(8, 0.75f, true))) + synchronized(cacheLock) { + generation.incrementAndGet() + tileCache.evictAll() + } + } + + /** + * Replaces the shapes at the given indexes. Only the tiles that + * overlapped one of them, before or after, are drawn again. + */ + fun update(updates: List>) { + val current = acquireModel() ?: return + var next: ShapeTileStorage? = null + try { + val touched = ArrayList(updates.size * 2) + var maxStroke = current.maxStroke + var reindex = false + for ((index, after) in updates) { + if (index !in 0 until current.storage.size) continue + val before = current.storage.bbox(index) + val afterBox = after?.let(painter::bbox) + before?.let(touched::add) + afterBox?.let(touched::add) + if (after != null) maxStroke = max(maxStroke, painter.strokeWidth(after)) + // A shape that moved needs the index rebuilt; a restyle does not. + if (before == null || afterBox == null || !before.contentEquals(afterBox)) reindex = true + } + val replacement = current.storage.updated(updates) + next = replacement + val index = if (reindex) ShapeGridIndex.build(replacement.size, replacement.storageOrder, replacement::bbox) else current.index + replaceModel(Model(replacement, index, maxStroke, current.perZoom, current.active)) + next = null + synchronized(cacheLock) { + generation.incrementAndGet() + dropTilesIn(touched, maxStroke) + } + } finally { + next?.release() + current.storage.release() + } + } + + fun clear() { + replaceModel(null) + synchronized(cacheLock) { + generation.incrementAndGet() + tileCache.evictAll() + } + } + + override fun renderTile(request: TileRequest): ByteArray? = renderTile(request) { false } + + override fun renderTile( + request: TileRequest, + isCancelled: () -> Boolean, + ): ByteArray? { + val generationAtStart = generation.get() + val m = acquireModel() ?: return null + try { + val z = request.z + if (z !in 0..MAX_ZOOM) return null + val n = 1 shl z + val x = ((request.x % n) + n) % n + val y = request.y + if (y !in 0 until n) return null + val ratio = request.pixelRatio.coerceIn(1, 3) + val key = cacheKey(z, x, y, ratio) + synchronized(cacheLock) { tileCache.get(key) }?.let { return it } + + val bytes = + when (val gpu = drawOnGpu(m, x, y, z, ratio, isCancelled)) { + Gpu.Empty -> return null + is Gpu.Drawn -> encode(gpu.pixels, gpu.size) + Gpu.Unavailable -> { + val bitmap = draw(m, x, y, z, ratio, isCancelled) ?: return null + try { + encode(bitmap) + } finally { + releaseScratch(bitmap) + } + } + } + synchronized(cacheLock) { + // The shapes may have changed while this tile was drawn. + if (generation.get() == generationAtStart) tileCache.put(key, bytes) + } + return bytes + } finally { + m.storage.release() + } + } + + /** The tile as a bitmap, or null when nothing of any shape is in it. For tests and [renderTile]. */ + fun renderBitmap( + x: Int, + y: Int, + z: Int, + pixelRatio: Int = 1, + ): Bitmap? { + val current = acquireModel() ?: return null + return try { + when (val gpu = drawOnGpu(current, x, y, z, pixelRatio) { false }) { + Gpu.Empty -> return null + is Gpu.Drawn -> + return createBitmap(gpu.size, gpu.size).apply { copyPixelsFromBuffer(gpu.pixels) } + Gpu.Unavailable -> Unit + } + draw(current, x, y, z, pixelRatio) { false }?.let { scratch -> + try { + scratch.copy(Bitmap.Config.ARGB_8888, false) + } finally { + releaseScratch(scratch) + } + } + } finally { + current.storage.release() + } + } + + /** What [drawOnGpu] did. */ + private sealed class Gpu { + /** Premultiplied RGBA, [size] pixels square, top row first. */ + class Drawn( + val pixels: ByteBuffer, + val size: Int, + ) : Gpu() + + /** Nothing of any shape is in the tile. */ + object Empty : Gpu() + + /** No GPU drawing here (or this kind of shape): draw on the canvas. */ + object Unavailable : Gpu() + } + + /** + * The tile drawn by [GlShapeRasterizer]: the same shapes as [drawInto], in + * the same order, recorded by the painter instead of drawn on a canvas. + */ + private fun drawOnGpu( + m: Model, + x: Int, + y: Int, + z: Int, + pixelRatio: Int, + isCancelled: () -> Boolean, + ): Gpu { + if (!useGpu || !painter.drawsOnGpu) return Gpu.Unavailable + val scale = tileSize.toDouble() * (1L shl z).toDouble() + val originX = x.toDouble() * tileSize + val originY = y.toDouble() * tileSize + val candidates = candidatesFor(m, originX, originY, scale) + if (candidates.isEmpty()) return Gpu.Empty + val r = pixelScale() * pixelRatio + val px = (tileSize * r).roundToInt().coerceAtLeast(1) + // A circle tile is one ordered list of circles; a circle drawn as its + // 128-gon needs the batched scene instead. + val scene = + try { + val ordered = GlShapeScene(px, orderedCircles = painter.thinSubpixelOverlaps) + val checkCancelled = { if (isCancelled()) throw cancelled() } + if (painter.recordAll(ordered, m.storage, candidates, m.active, scale, originX, originY, tileSize, r, checkCancelled)) { + ordered.finish() + } else { + record(ordered, m, candidates, originX, originY, r, z, scale, isCancelled) + } + } catch (_: GlShapeScene.NeedsBatches) { + record(GlShapeScene(px), m, candidates, originX, originY, r, z, scale, isCancelled) + } + if (scene.isEmpty) return Gpu.Empty + if (isCancelled()) throw cancelled() + val pixels = GlShapeRasterizer.render(scene) ?: return Gpu.Unavailable + return Gpu.Drawn(pixels, px) + } + + /** [drawInto]'s loop, recording into [scene]. */ + private fun record( + scene: GlShapeScene, + m: Model, + candidates: IntArray, + originX: Double, + originY: Double, + r: Float, + z: Int, + scale: Double, + isCancelled: () -> Boolean, + ): GlShapeScene { + val perZoom = perZoomOf(m, z) + val lastDot = IntArray(if (painter.thinSubpixelOverlaps) tileSize * tileSize else 0) + if (painter.thinSubpixelOverlaps) { + for ((k, index) in candidates.withIndex()) { + if (k % CANCEL_CHECK_EVERY == 0 && isCancelled()) throw cancelled() + if (m.active != null && !m.active[index]) continue + val item = m.storage[index] ?: continue + if (!painter.isVisible(item)) continue + val slot = painter.subpixelSlot(item, scale, originX, originY, tileSize) + if (slot >= 0) lastDot[slot] = index + 1 + } + } + for ((k, index) in candidates.withIndex()) { + if (k % CANCEL_CHECK_EVERY == 0 && isCancelled()) throw cancelled() + if (m.active != null && !m.active[index]) continue + val item = m.storage[index] ?: continue + if (painter.thinSubpixelOverlaps) { + val slot = painter.subpixelSlot(item, scale, originX, originY, tileSize) + if (slot == -1 || (slot >= 0 && lastDot[slot] != index + 1)) continue + } + painter.record(scene, item, simplifiedAt(perZoom, index, item, scale), originX, originY, r) + } + return scene.finish() + } + + private fun candidatesFor( + m: Model, + originX: Double, + originY: Double, + scale: Double, + ): IntArray { + // A stroke reaches half its width past the shape: take the shapes that + // close to the tile too, and draw them whole (the canvas cuts them), so + // the tile next door draws the same line at the same place. + val pad = m.maxStroke / 2.0 + 1.0 + return m.index.query( + { index -> if (m.active?.get(index) == false) null else m.storage.bbox(index) }, + (originX - pad) / scale, + (originY - pad) / scale, + (originX + tileSize + pad) / scale, + (originY + tileSize + pad) / scale, + m.storage.storageOrder, + ) + } + + private fun draw( + m: Model, + x: Int, + y: Int, + z: Int, + pixelRatio: Int, + isCancelled: () -> Boolean, + ): Bitmap? { + val scale = tileSize.toDouble() * (1L shl z).toDouble() + val originX = x.toDouble() * tileSize + val originY = y.toDouble() * tileSize + val candidates = candidatesFor(m, originX, originY, scale) + if (candidates.isEmpty()) return null + + val r = pixelScale() * pixelRatio + val px = (tileSize * r).roundToInt().coerceAtLeast(1) + val bitmap = scratch(px) + try { + return drawInto(bitmap, m, candidates, originX, originY, r, z, scale, isCancelled) + } catch (error: Throwable) { + releaseScratch(bitmap) + throw error + } + } + + /** Draws into [bitmap]; null (and the bitmap back in the pool) when nothing was drawn. */ + @Suppress("UNCHECKED_CAST") + private fun drawInto( + bitmap: Bitmap, + m: Model, + candidates: IntArray, + originX: Double, + originY: Double, + r: Float, + z: Int, + scale: Double, + isCancelled: () -> Boolean, + ): Bitmap? { + val canvas = Canvas(bitmap) + val paints = Paints() + val perZoom = perZoomOf(m, z) + // Subpixel circles are display representatives: keep the last visible + // circle at each world pixel. Never remove states or larger circles. + val lastDot = IntArray(if (painter.thinSubpixelOverlaps) tileSize * tileSize else 0) + if (painter.thinSubpixelOverlaps) { + for ((k, index) in candidates.withIndex()) { + if (k % CANCEL_CHECK_EVERY == 0 && isCancelled()) throw cancelled() + if (m.active != null && !m.active[index]) continue + val item = m.storage[index] ?: continue + if (!painter.isVisible(item)) continue + val slot = painter.subpixelSlot(item, scale, originX, originY, tileSize) + if (slot >= 0) lastDot[slot] = index + 1 + } + } + var drew = false + for ((k, index) in candidates.withIndex()) { + if (k % CANCEL_CHECK_EVERY == 0 && isCancelled()) throw cancelled() + if (m.active != null && !m.active[index]) continue + val item = m.storage[index] ?: continue + if (painter.thinSubpixelOverlaps) { + val slot = painter.subpixelSlot(item, scale, originX, originY, tileSize) + if (slot == -1 || (slot >= 0 && lastDot[slot] != index + 1)) continue + } + val shape = simplifiedAt(perZoom, index, item, scale) + if (painter.draw(canvas, item, shape, originX, originY, r, paints)) drew = true + } + if (!drew) releaseScratch(bitmap) + return if (drew) bitmap else null + } + + private fun perZoomOf( + m: Model, + z: Int, + ): AtomicReferenceArray = + if (!painter.cacheSimplifiedShapes) { + AtomicReferenceArray(0) + } else { + synchronized(m.perZoom) { + // Access order: a lookup makes the zoom the most recent one. + m.perZoom[z] ?: AtomicReferenceArray(m.storage.size).also { created -> + m.perZoom[z] = created + val it = m.perZoom.keys.iterator() + while (m.perZoom.size > ZOOMS_KEPT && it.hasNext()) { + it.next() + it.remove() + } + } + } + } + + private fun simplifiedAt( + perZoom: AtomicReferenceArray, + index: Int, + item: T, + scale: Double, + ): Any { + // Dot and Arc are cheap projections of compact circle data. Caching + // them for every source circle at several zooms defeats raster tiling. + if (!painter.cacheSimplifiedShapes) return painter.simplify(item, scale) + val cached = perZoom.get(index) + if (cached != null && cached.source === item) return cached.shape + val shape = painter.simplify(item, scale) + perZoom.set(index, Simplified(item, shape)) + return shape + } + + private fun scratch(px: Int): Bitmap { + val existing = scratchBitmaps.acquire { !it.isRecycled && it.width == px && it.height == px } + if (existing != null) { + existing.eraseColor(Color.TRANSPARENT) + return existing + } + return createBitmap(px, px) + } + + private fun releaseScratch(bitmap: Bitmap) { + scratchBitmaps.release(bitmap) + } + + /** The GPU's pixels as PNG: Rust when it can, else through a bitmap. */ + private fun encode( + pixels: ByteBuffer, + size: Int, + ): ByteArray { + TilePngEncoder.encode(pixels, size, size, premultiplied = true)?.let { return it } + pixels.rewind() + val bitmap = scratch(size) + try { + bitmap.copyPixelsFromBuffer(pixels) + return encode(bitmap) + } finally { + releaseScratch(bitmap) + } + } + + private fun encode(bitmap: Bitmap): ByteArray { + // Rust first, as for marker tiles: Bitmap.compress is several times slower. + TilePngEncoder.encode(bitmap)?.let { return it } + val out = byteStreams.acquire() ?: ByteArrayOutputStream(16 * 1024) + try { + out.reset() + bitmap.compress(Bitmap.CompressFormat.PNG, 100, out) + return out.toByteArray() + } finally { + byteStreams.release(out) + } + } + + private fun dropTilesIn( + boxes: List, + strokePx: Float, + ) { + if (boxes.isEmpty()) return + for (key in tileCache.snapshot().keys) { + val z = (key ushr 56).toInt() + val x = ((key ushr 27) and COORD_MASK).toInt() + val y = (key and COORD_MASK).toInt() + val scale = tileSize.toDouble() * (1L shl z).toDouble() + val pad = (strokePx + 2.0) / scale + val tx0 = x * tileSize / scale - pad + val tx1 = (x + 1) * tileSize / scale + pad + val ty0 = y * tileSize / scale - pad + val ty1 = (y + 1) * tileSize / scale + pad + if (boxes.any { b -> b[0] <= tx1 && b[2] >= tx0 && b[1] <= ty1 && b[3] >= ty0 }) { + tileCache.remove(key) + } + } + } + + private fun cacheKey( + z: Int, + x: Int, + y: Int, + ratio: Int, + ): Long = (z.toLong() shl 56) or (ratio.toLong() shl 54) or (x.toLong() shl 27) or y.toLong() + + /** Thrown when the map stops wanting a tile mid-draw: a failure it may retry, never an empty tile. */ + @InternalMapConductorApi + class TileRenderCancelled : Exception("shape tile no longer wanted") + + init { + if (useGpu && painter.drawsOnGpu) prepareGpu + } + + @InternalMapConductorApi + companion object { + const val DEFAULT_CACHE_BYTES = 16 * 1024 * 1024 + + /** + * Draw shape tiles on the GPU ([GlShapeRasterizer]) when it can. False + * draws every tile on the canvas, to compare the two. + */ + @Volatile + var useGpu: Boolean = true + + /** + * Polygons and polylines on the GPU too. Off: on a Pixel 5a and a + * Lenovo TB520FU, Skia drew their tiles as fast or faster (a polygon tile + * splits into thousands of small batches), while circles were 2x faster + * on the GPU. Kept for the comparison tests and for later work. + */ + @Volatile + var gpuPolygonsAndLines: Boolean = false + + /** + * The GL contexts and shaders are made on first use. Start that when + * shapes are about to be tiled, instead of making the first tiles the + * map asks for wait for it. + */ + private val prepareGpu: Unit by lazy { + Thread({ GlShapeRasterizer.prepare() }, "mc-shape-gpu-prepare").apply { isDaemon = true }.start() + } + + /** Simplified copies kept, most recent zooms first. */ + private const val ZOOMS_KEPT = 4 + private const val MAX_ZOOM = 26 + private const val CANCEL_CHECK_EVERY = 256 + private const val COORD_MASK = (1L shl 27) - 1 + } +} diff --git a/src/main/java/com/mapconductor/core/shapetile/ShapeTileSet.kt b/src/main/java/com/mapconductor/core/shapetile/ShapeTileSet.kt new file mode 100644 index 0000000..3e7c68c --- /dev/null +++ b/src/main/java/com/mapconductor/core/shapetile/ShapeTileSet.kt @@ -0,0 +1,316 @@ +package com.mapconductor.core.shapetile + +import com.mapconductor.core.InternalMapConductorApi +import com.mapconductor.core.tileserver.LocalTileServer +import java.util.BitSet +import java.util.UUID +import kotlin.time.Duration.Companion.milliseconds +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.delay +import kotlinx.coroutines.ensureActive +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext + +/** + * The shapes of one map that are drawn as raster tiles, and their route on the + * local tile server: the part `PolygonTileSet` and `PolylineTileSet` share. + * Each of those adds what a state is as a tile ([toTile]) and which states can + * be tiled. + * + * [setShapes] registers the list and returns the URL template of its tiles; + * [update] and [remove] change one shape in place, coalesced over + * [UPDATE_COALESCE], and each batch ends in a new template -- the version in + * it is what makes the map ask again -- reported to [onTemplateChanged]. Tiles + * the change did not touch are still cached by the renderer and come back + * without being drawn again. + * + * The same as js-sdk-core's and ios-sdk-core's `ShapeTileSet`. + */ +@InternalMapConductorApi +internal class ShapeTileSet( + routePrefix: String, + private val server: LocalTileServer, + private val scope: CoroutineScope, + private val renderer: ShapeTileRenderer, + private val idOf: (S) -> String, + private val zIndexOf: (S) -> Int, + private val toTile: (S) -> T?, + private val canReuse: ((S, T) -> Boolean)? = null, + private val createStorage: (suspend (List) -> ShapeTileStorage?)? = null, +) { + val routeId: String = "$routePrefix-${UUID.randomUUID().toString().take(8)}" + + /** Called with the new template after an [update] or [remove]. */ + var onTemplateChanged: (suspend (String) -> Unit)? = null + + val tileSize: Int get() = renderer.tileSize + + private val lock = Any() + private var indexById: Map = emptyMap() + private var sourceStates: MutableList = mutableListOf() + private var sourceZ = IntArray(0) + private var active: BitSet? = null + + fun ids(): Set = + synchronized(lock) { + val mask = active ?: return@synchronized indexById.keys + val ids = indexById + object : AbstractSet() { + override val size = mask.cardinality() + + override fun contains(element: String): Boolean = ids[element]?.let { mask[it] } == true + + override fun iterator(): Iterator = + ids.entries + .asSequence() + .filter { mask[it.value] } + .map { it.key } + .iterator() + } + } + + fun source(id: String): S? = + synchronized(lock) { + indexById[id]?.takeIf { active?.get(it) != false }?.let { sourceStates[it] } + } + + fun visitSources(action: (S) -> Unit) = + synchronized(lock) { + for ((index, state) in sourceStates.withIndex()) { + if (state != null && + active?.get(index) != false + ) { + action(state) + } + } + } + + /** + * The registered states whose shape's bounding box meets the given one (Web + * Mercator, [0, 1]), as of now: changes still waiting for [flush] are + * included, since their shape in the renderer may be the old one. + */ + fun sources( + minX: Double, + minY: Double, + maxX: Double, + maxY: Double, + ): List { + val slots = renderer.candidates(minX, minY, maxX, maxY) + return synchronized(lock) { + val seen = HashSet() + val states = ArrayList(slots.size) + for (slot in slots) { + if (slot >= sourceStates.size || active?.get(slot) == false) continue + val state = sourceStates[slot] ?: continue + if (seen.add(idOf(state))) states.add(state) + } + for ((id, state) in pending) { + if (indexById.containsKey(id) && seen.add(id)) states.add(state) + } + states + } + } + + /** The widest stroke drawn, in pixels of a tile. */ + val maxStroke: Float get() = renderer.maxStroke + + @Volatile + private var version = 0 + private var registered = false + private val pending = LinkedHashMap() + private val pendingRemovals = ArrayList() + private var flushJob: Job? = null + + /** + * Registers [states] (replacing whatever was registered) and returns the + * URL template of their tiles. + */ + suspend fun setShapes(states: List): String { + cancelPending() + val ordered = withContext(Dispatchers.Default) { states.sortedBy(zIndexOf) } + // A filtered collection often refers to the same geometry. Keep the + // original slots, including temporarily hidden shapes, for re-enabling. + val reused = + withContext(Dispatchers.Default) { + val context = currentCoroutineContext() + synchronized(lock) { + val matches = canReuse + if (!registered || matches == null) { + false + } else { + val mask = BitSet(sourceStates.size) + var previous = -1 + var checked = 0 + val reusable = + ordered.all { state -> + if (++checked % 4096 == 0) context.ensureActive() + val index = indexById[idOf(state)] + val item = index?.let(renderer::itemAt) + val ok = + index != null && + index > previous && + item != null && + sourceZ[index] == zIndexOf(state) && + matches(state, item) + if (ok) { + mask.set(index!!) + previous = index + } + ok + } + if (reusable) { + // Cache geometry, not removed application states/handlers. + for (index in sourceStates.indices) if (!mask[index]) sourceStates[index] = null + for (state in ordered) sourceStates[indexById.getValue(idOf(state))] = state + active = mask + renderer.setActiveItems(mask) + version++ + } + reusable + } + } + } + if (reused) return template() + var prepared: ShapeTileStorage? = null + try { + val (shapes, ids, sources) = + withContext(Dispatchers.Default) { + // Draw order is list order: zIndex, then the order given (sortedBy is stable). + val ids = HashMap(ordered.size * 2) + ordered.forEachIndexed { index, state -> ids[idOf(state)] = index } + val sources: MutableList = ordered.toMutableList() + prepared = createStorage?.invoke(ordered) + Triple(if (prepared == null) ordered.map(toTile) else emptyList(), ids, sources) + } + withContext(Dispatchers.Default) { + val context = currentCoroutineContext() + synchronized(lock) { + val storage = prepared + prepared = null + if (storage != + null + ) { + renderer.setStorage(storage) { context.ensureActive() } + } else { + renderer.setItems(shapes) + } + if (!registered) server.register(routeId, renderer) + indexById = ids + sourceStates = sources + sourceZ = IntArray(ordered.size) { zIndexOf(ordered[it]) } + active = null + registered = true + version++ + } + } + return template() + } finally { + prepared?.release() + } + } + + fun has(id: String): Boolean = + synchronized(lock) { + indexById[id]?.let { active?.get(it) != false } == true + } + + /** + * One shape changed in place. A change of zIndex reorders the list and + * needs [setShapes] instead; everything else is applied here. + */ + fun update(state: S) { + synchronized(lock) { + val id = idOf(state) + if (!indexById.containsKey(id)) return + sourceStates[indexById.getValue(id)] = state + pending[id] = state + scheduleFlushLocked() + } + } + + /** + * Takes one shape out of the tiles. Its slot in the renderer's list is + * left empty, so the others keep their indices and only the tiles it was + * in are drawn again. + */ + fun remove(id: String) { + synchronized(lock) { + val index = indexById[id] ?: return + sourceStates[index] = null + indexById = indexById - id + active?.let { previous -> + val next = previous.clone() as BitSet + next.clear(index) + active = next + renderer.setActiveItems(next) + } + pending.remove(id) + pendingRemovals.add(index) + scheduleFlushLocked() + } + } + + /** Called with [lock] held. */ + private fun scheduleFlushLocked() { + if (flushJob == null) { + flushJob = + scope.launch { + delay(UPDATE_COALESCE) + flush() + } + } + } + + /** The URL template, with the version that changes on every change. */ + fun template(): String = server.urlTemplate(routeId, renderer.tileSize, version.toString()) + + fun dispose() { + cancelPending() + synchronized(lock) { + if (registered) server.unregister(routeId) + registered = false + indexById = emptyMap() + sourceStates = mutableListOf() + sourceZ = IntArray(0) + active = null + renderer.clear() + } + } + + private suspend fun flush() { + val template = + synchronized(lock) { + flushJob = null + val updates: List> = + pending.values.mapNotNull { state -> + indexById[idOf(state)]?.let { index -> index to toTile(state) } + } + pendingRemovals.map { index -> index to null } + pending.clear() + pendingRemovals.clear() + if (updates.isEmpty() || !registered) return + renderer.update(updates) + version++ + template() + } + onTemplateChanged?.invoke(template) + } + + private fun cancelPending() { + synchronized(lock) { + flushJob?.cancel() + flushJob = null + pending.clear() + pendingRemovals.clear() + } + } + + @InternalMapConductorApi + companion object { + /** In-place changes arriving within this window are drawn as one. */ + val UPDATE_COALESCE = 16.milliseconds + } +} diff --git a/src/main/java/com/mapconductor/core/shapetile/ShapeTileStorage.kt b/src/main/java/com/mapconductor/core/shapetile/ShapeTileStorage.kt new file mode 100644 index 0000000..a15b579 --- /dev/null +++ b/src/main/java/com/mapconductor/core/shapetile/ShapeTileStorage.kt @@ -0,0 +1,143 @@ +package com.mapconductor.core.shapetile + +import com.mapconductor.core.InternalMapConductorApi +import java.util.concurrent.atomic.AtomicInteger +import kotlin.math.max + +/** Immutable geometry snapshot. A renderer owns one reference; each reader leases another. */ +@InternalMapConductorApi +internal abstract class ShapeTileStorage { + private val references = AtomicInteger(1) + abstract val size: Int + abstract val maxStroke: Float + + abstract operator fun get(index: Int): T? + + abstract fun bbox(index: Int): DoubleArray? + + abstract fun updated(updates: List>): ShapeTileStorage + + /** + * How the shapes are laid out in storage, when not in index order: a large + * file-backed set is stored by place, so that a tile reads the few blocks + * round it. Indices stay the list's (draw order, updates, activation); + * whatever reads many shapes walks them in this order. + */ + open val storageOrder: StorageOrder? get() = null + + fun retain() { + while (true) { + val count = references.get() + check(count > 0) { "Geometry storage already closed" } + if (references.compareAndSet(count, count + 1)) return + } + } + + fun release() { + val remaining = references.decrementAndGet() + check(remaining >= 0) + if (remaining == 0) close() + } + + protected open fun close() = Unit +} + +/** Existing polygon/polyline storage, and small circle collections. */ +@InternalMapConductorApi +internal class MemoryShapeTileStorage private constructor( + private val items: Array, + private val boxes: Array, + override val maxStroke: Float, + private val painter: ShapeTileRenderer.Painter, +) : ShapeTileStorage() { + constructor(items: List, painter: ShapeTileRenderer.Painter) : this( + items.toTypedArray(), + Array(items.size) { items[it]?.let(painter::bbox) }, + items.maxOfOrNull { it?.let(painter::strokeWidth) ?: 0f } ?: 0f, + painter, + ) + + override val size: Int get() = items.size + + @Suppress("UNCHECKED_CAST") + override fun get(index: Int): T? = items.getOrNull(index) as T? + + override fun bbox(index: Int): DoubleArray? = boxes.getOrNull(index) + + override fun updated(updates: List>): ShapeTileStorage { + val next = items.copyOf() + val nextBoxes = boxes.copyOf() + var widest = maxStroke + for ((index, item) in updates) { + if (index in next.indices) { + next[index] = item + nextBoxes[index] = item?.let(painter::bbox) + if (item != null) widest = max(widest, painter.strokeWidth(item)) + } + } + return MemoryShapeTileStorage(next, nextBoxes, widest, painter) + } +} + +/** Stored position -> index ([indexAt]) and back ([positionOf]). */ +@InternalMapConductorApi +internal class StorageOrder( + val indexAt: IntArray, +) { + val positionOf: IntArray = + IntArray(indexAt.size).also { positions -> for (p in indexAt.indices) positions[indexAt[p]] = p } + + @InternalMapConductorApi + companion object { + /** + * The indices `0 until size` sorted by [keyOf] (24-bit keys), ties in + * index order: two stable 12-bit counting passes, since a comparison sort + * of a nationwide set takes most of a second on a phone. + */ + fun sortedBy( + size: Int, + keyOf: (Int) -> Int, + ): StorageOrder { + val keys = IntArray(size) { keyOf(it) and 0xffffff } + var from = IntArray(size) { it } + var to = IntArray(size) + val counts = IntArray(4096) + for (shift in intArrayOf(0, 12)) { + counts.fill(0) + for (i in 0 until size) counts[(keys[from[i]] ushr shift) and 4095]++ + var sum = 0 + for (b in 0 until 4096) { + val c = counts[b] + counts[b] = sum + sum += c + } + for (i in 0 until size) to[counts[(keys[from[i]] ushr shift) and 4095]++] = from[i] + val swap = from + from = to + to = swap + } + return StorageOrder(from) + } + + /** + * The z12 cell of a point in Z-order (Morton), 24 bits: cells next to + * each other mostly get keys next to each other. The same key as + * js-sdk-core's `mortonCellKey` and ios-sdk-core's. + */ + fun mortonCellKey( + latitude: Double, + longitude: Double, + ): Int { + val x = (longitude + 180.0) / 360.0 + val sin = kotlin.math.sin(latitude.coerceIn(-85.0, 85.0) * Math.PI / 180.0) + val y = 0.5 - kotlin.math.ln((1 + sin) / (1 - sin)) / (4 * Math.PI) + val cx = kotlin.math.floor(x * 4096).toInt().coerceIn(0, 4095) + val cy = kotlin.math.floor(y * 4096).toInt().coerceIn(0, 4095) + var key = 0 + for (bit in 0 until 12) { + key = key or (((cx ushr bit) and 1) shl (2 * bit)) or (((cy ushr bit) and 1) shl (2 * bit + 1)) + } + return key + } + } +} diff --git a/src/main/java/com/mapconductor/core/shapetile/ShapeTiler.kt b/src/main/java/com/mapconductor/core/shapetile/ShapeTiler.kt new file mode 100644 index 0000000..ad3b385 --- /dev/null +++ b/src/main/java/com/mapconductor/core/shapetile/ShapeTiler.kt @@ -0,0 +1,93 @@ +package com.mapconductor.core.shapetile + +import com.mapconductor.core.InternalMapConductorApi +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext + +/** + * Decides which of a map's shapes are drawn as tiles and keeps them registered + * in [tileSet]: the part `PolygonTiler` and `PolylineTiler` share. See + * `PolygonTiler` for how a provider's controller uses it. + * + * [shouldUseTiles] is read at every [route], so a tiler whose options change + * decides again on the next one. + */ +@InternalMapConductorApi +internal class ShapeTiler( + private val tileSet: ShapeTileSet, + private val canTile: (S) -> Boolean, + private val vertexCount: (List) -> Int, + private val shouldUseTiles: (count: Int, vertices: Int) -> Boolean, + private val idOf: (S) -> String, + private val onTemplate: suspend (template: String?, tileSize: Int) -> Unit, +) { + @Volatile + private var tiled: Set = emptySet() + + @Volatile + private var states: List = emptyList() + + init { + tileSet.onTemplateChanged = { template -> onTemplate(template, tileSet.tileSize) } + } + + /** Re-decides tiling for [data] and returns the ids drawn as tiles. */ + suspend fun route(data: List): Set { + // A city of shapes is a second of work; none of it belongs on the map's thread. + val (tileable, useTiles) = + withContext(Dispatchers.Default) { + val tileable = data.filter(canTile) + tileable to shouldUseTiles(tileable.size, vertexCount(tileable)) + } + val template = if (useTiles) tileSet.setShapes(tileable) else null + if (template == null) { + tileSet.dispose() + tiled = emptySet() + states = emptyList() + } else { + // Share the tile set's ID index instead of retaining a second hash set. + tiled = tileSet.ids() + states = tileable + } + onTemplate(template, tileSet.tileSize) + return tiled + } + + fun tiledStates(): List = states + + fun isTiled(id: String): Boolean = tiled.contains(id) + + fun update(state: S) { + tileSet.update(state) + } + + /** Rebuild draw order without re-evaluating the native/tile threshold. */ + suspend fun reorder(state: S) { + val updated = ArrayList() + tileSet.visitSources { updated.add(if (idOf(it) == idOf(state)) state else it) } + val template = tileSet.setShapes(updated) + states = updated + tiled = tileSet.ids() + onTemplate(template, tileSet.tileSize) + } + + fun remove(id: String) { + if (id !in tiled) return + tiled = tiled - id + states = states.filter { idOf(it) != id } + tileSet.remove(id) + } + + fun dispose() { + tileSet.dispose() + tiled = emptySet() + states = emptyList() + } + + suspend fun clear() { + tileSet.dispose() + tiled = emptySet() + states = emptyList() + onTemplate(null, tileSet.tileSize) + } +} diff --git a/src/main/java/com/mapconductor/core/spherical/Spherical.kt b/src/main/java/com/mapconductor/core/spherical/Spherical.kt index b27bcb8..efeac65 100644 --- a/src/main/java/com/mapconductor/core/spherical/Spherical.kt +++ b/src/main/java/com/mapconductor/core/spherical/Spherical.kt @@ -1,286 +1,287 @@ -package com.mapconductor.core.spherical - -import com.mapconductor.core.features.GeoPoint -import com.mapconductor.core.features.GeoPointInterface -import com.mapconductor.core.projection.Earth -import kotlin.math.abs -import kotlin.math.acos -import kotlin.math.asin -import kotlin.math.atan2 -import kotlin.math.cos -import kotlin.math.sin -import kotlin.math.sqrt - -/** - * Spherical geometry utility functions for calculating distances, headings, - * and positions on Earth's surface using the spherical Earth model. - * - * This is a Kotlin port of the Cordova Google Maps plugin spherical.js utilities. - * Uses GeoPointInterface instead of LatLng for coordinate representation. - */ -object Spherical { - // Mathematical constants - private const val PI = Math.PI - private const val RAD_TO_DEG = 180.0 / PI - private const val DEG_TO_RAD = PI / 180.0 - - /** - * Returns the distance, in meters, between two GeoPointInterface locations. - * Uses the haversine formula. - * - * @param from Starting point - * @param to Ending point - * @return Distance in meters - */ - fun computeDistanceBetween( - from: GeoPointInterface, - to: GeoPointInterface, - ): Double { - val lat1Rad = from.latitude * DEG_TO_RAD - val lat2Rad = to.latitude * DEG_TO_RAD - val deltaLat = (to.latitude - from.latitude) * DEG_TO_RAD - val deltaLng = (to.longitude - from.longitude) * DEG_TO_RAD - - val haversineA = - sin(deltaLat / 2) * sin(deltaLat / 2) + - cos(lat1Rad) * cos(lat2Rad) * - sin(deltaLng / 2) * sin(deltaLng / 2) - - val centralAngle = 2 * atan2(sqrt(haversineA), sqrt(1 - haversineA)) - - return Earth.RADIUS_METERS * centralAngle - } - - /** - * Returns the heading from one GeoPointInterface to another GeoPointInterface. - * Headings are expressed in degrees clockwise from North within the range (-180, 180). - * - * @param from Starting point - * @param to Ending point - * @return Heading in degrees - */ - fun computeHeading( - from: GeoPointInterface, - to: GeoPointInterface, - ): Double { - val lat1Rad = from.latitude * DEG_TO_RAD - val lat2Rad = to.latitude * DEG_TO_RAD - val deltaLng = (to.longitude - from.longitude) * DEG_TO_RAD - - val deltaY = sin(deltaLng) * cos(lat2Rad) - val deltaX = cos(lat1Rad) * sin(lat2Rad) - sin(lat1Rad) * cos(lat2Rad) * cos(deltaLng) - - var heading = atan2(deltaY, deltaX) * RAD_TO_DEG - - // Normalize to (-180, 180] - while (heading > 180) heading -= 360 - while (heading <= -180) heading += 360 - - return heading - } - - /** - * Returns the GeoPointInterface resulting from moving a distance from an origin - * in the specified heading (expressed in degrees clockwise from north). - * - * @param origin Starting point - * @param distance Distance to travel in meters - * @param heading Direction to travel in degrees (0 = North, 90 = East) - * @return New GeoPointInterface position - */ - fun computeOffset( - origin: GeoPointInterface, - distance: Double, - heading: Double, - ): GeoPoint { - val distanceRad = distance / Earth.RADIUS_METERS - val headingRad = heading * DEG_TO_RAD - val lat1Rad = origin.latitude * DEG_TO_RAD - val lng1Rad = origin.longitude * DEG_TO_RAD - - val lat2Rad = - asin( - sin(lat1Rad) * cos(distanceRad) + - cos(lat1Rad) * sin(distanceRad) * cos(headingRad), - ) - - val lng2Rad = - lng1Rad + - atan2( - sin(headingRad) * sin(distanceRad) * cos(lat1Rad), - cos(distanceRad) - sin(lat1Rad) * sin(lat2Rad), - ) - - return GeoPoint( - latitude = lat2Rad * RAD_TO_DEG, - longitude = lng2Rad * RAD_TO_DEG, - altitude = origin.altitude ?: 0.0, - ) - } - - /** - * Returns the location of origin when provided with a GeoPointInterface destination, - * meters travelled and original heading. - * Headings are expressed in degrees clockwise from North. - * - * @param to Destination point - * @param distance Distance travelled in meters - * @param heading Original heading in degrees - * @return Origin GeoPointInterface position, or null if no solution is available - */ - fun computeOffsetOrigin( - to: GeoPointInterface, - distance: Double, - heading: Double, - ): GeoPoint? { - // Calculate the reverse heading - val reverseHeading = (heading + 180) % 360 - - return try { - computeOffset(to, distance, reverseHeading) - } catch (e: Exception) { - null - } - } - - /** - * Returns the length of the given path in meters. - * - * @param path List of GeoPointInterface locations defining the path - * @return Length in meters - */ - fun computeLength(path: List): Double { - if (path.size < 2) return 0.0 - - var length = 0.0 - for (i in 1 until path.size) { - length += computeDistanceBetween(path[i - 1], path[i]) - } - - return length - } - - /** - * Returns the area of a closed path in square meters. - * The path should form a closed polygon. - * - * @param path List of GeoPointInterface locations defining the closed path - * @return Area in square meters - */ - fun computeArea(path: List): Double = abs(computeSignedArea(path)) - - /** - * Returns the signed area of a closed path in square meters. - * The signed area may be used to determine the orientation of the path. - * Positive values indicate counter-clockwise orientation, - * negative values indicate clockwise orientation. - * - * @param path List of GeoPointInterface locations defining the closed path - * @return Signed area in square meters - */ - fun computeSignedArea(path: List): Double { - if (path.size < 3) return 0.0 - - var area = 0.0 - val pointCount = path.size - - for (i in path.indices) { - val j = (i + 1) % pointCount - val lat1 = path[i].latitude * DEG_TO_RAD - val lat2 = path[j].latitude * DEG_TO_RAD - val deltaLng = (path[j].longitude - path[i].longitude) * DEG_TO_RAD - - area += deltaLng * (2 + sin(lat1) + sin(lat2)) - } - - return area * Earth.RADIUS_METERS * Earth.RADIUS_METERS / 2.0 - } - - /** - * Interpolates between two GeoPointInterface locations along the great circle path using spherical linear interpolation (Slerp). - * This method considers Earth's curvature and provides high accuracy for any distance. - * - * @param from Starting point - * @param to Ending point - * @param fraction Interpolation fraction (0.0 = from, 1.0 = to) - * @return Interpolated GeoPointInterface position - */ - fun interpolate( - from: GeoPointInterface, - to: GeoPointInterface, - fraction: Double, - ): GeoPoint { - // ラジアンに変換 - val lat1 = from.latitude * DEG_TO_RAD - val lng1 = from.longitude * DEG_TO_RAD - val lat2 = to.latitude * DEG_TO_RAD - val lng2 = to.longitude * DEG_TO_RAD - - // 3D単位ベクトルに変換 - val x1 = cos(lat1) * cos(lng1) - val y1 = cos(lat1) * sin(lng1) - val z1 = sin(lat1) - - val x2 = cos(lat2) * cos(lng2) - val y2 = cos(lat2) * sin(lng2) - val z2 = sin(lat2) - - // 内積から角度を求める - val dot = x1 * x2 + y1 * y2 + z1 * z2 - val angle = acos(dot.coerceIn(-1.0, 1.0)) - - // 非常に近い点は線形補間 - if (angle < 1e-6) { - val interpolatedAltitude = - when { - from.altitude != null && to.altitude != null -> - from.altitude!! + fraction * (to.altitude!! - from.altitude!!) - from.altitude != null -> from.altitude - to.altitude != null -> to.altitude - else -> 0.0 - } - - return GeoPoint( - latitude = from.latitude + fraction * (to.latitude - from.latitude), - longitude = from.longitude + fraction * (to.longitude - from.longitude), - altitude = interpolatedAltitude!!, - ) - } - - // 球面線形補間(Slerp) - val sinAngle = sin(angle) - val weightFrom = sin((1 - fraction) * angle) / sinAngle - val weightTo = sin(fraction * angle) / sinAngle - - val vectorX = weightFrom * x1 + weightTo * x2 - val vectorY = weightFrom * y1 + weightTo * y2 - val vectorZ = weightFrom * z1 + weightTo * z2 - - // 3Dベクトルから緯度経度に変換 - val lat = asin(vectorZ) * RAD_TO_DEG - val lng = atan2(vectorY, vectorX) * RAD_TO_DEG - - val interpolatedAltitude = - when { - from.altitude != null && to.altitude != null -> - from.altitude!! + fraction * (to.altitude!! - from.altitude!!) - from.altitude != null -> from.altitude - to.altitude != null -> to.altitude - else -> 0.0 - } - - return GeoPoint( - latitude = lat, - longitude = lng, - altitude = interpolatedAltitude!!, - ) - } - - // `linearInterpolate` moved to `Planar.interpolate` (the straight-line model)。 - // 説明もそちらの KDoc にある。 - - /** - * Clamps latitude to the range [-90, 90]. - */ - private fun clampLat(lat: Double): Double = lat.coerceIn(-90.0, 90.0) -} +package com.mapconductor.core.spherical + +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.features.GeoPointInterface +import com.mapconductor.core.projection.Earth +import kotlin.math.abs +import kotlin.math.acos +import kotlin.math.asin +import kotlin.math.atan2 +import kotlin.math.cos +import kotlin.math.sin +import kotlin.math.sqrt + +/** + * Spherical geometry utility functions for calculating distances, headings, + * and positions on Earth's surface using the spherical Earth model. + * + * This is a Kotlin port of the Cordova Google Maps plugin spherical.js utilities. + * Uses GeoPointInterface instead of LatLng for coordinate representation. + */ +object Spherical { + // Mathematical constants + private const val PI = Math.PI + private const val RAD_TO_DEG = 180.0 / PI + private const val DEG_TO_RAD = PI / 180.0 + + /** + * Returns the distance, in meters, between two GeoPointInterface locations. + * Uses the haversine formula. + * + * @param from Starting point + * @param to Ending point + * @return Distance in meters + */ + fun computeDistanceBetween( + from: GeoPointInterface, + to: GeoPointInterface, + ): Double { + val lat1Rad = from.latitude * DEG_TO_RAD + val lat2Rad = to.latitude * DEG_TO_RAD + val deltaLat = (to.latitude - from.latitude) * DEG_TO_RAD + val deltaLng = (to.longitude - from.longitude) * DEG_TO_RAD + + val haversineA = + sin(deltaLat / 2) * sin(deltaLat / 2) + + cos(lat1Rad) * cos(lat2Rad) * + sin(deltaLng / 2) * sin(deltaLng / 2) + + val centralAngle = 2 * atan2(sqrt(haversineA), sqrt(1 - haversineA)) + + return Earth.RADIUS_METERS * centralAngle + } + + /** + * Returns the heading from one GeoPointInterface to another GeoPointInterface. + * Headings are expressed in degrees clockwise from North within the range (-180, 180). + * + * @param from Starting point + * @param to Ending point + * @return Heading in degrees + */ + fun computeHeading( + from: GeoPointInterface, + to: GeoPointInterface, + ): Double { + val lat1Rad = from.latitude * DEG_TO_RAD + val lat2Rad = to.latitude * DEG_TO_RAD + val deltaLng = (to.longitude - from.longitude) * DEG_TO_RAD + + val deltaY = sin(deltaLng) * cos(lat2Rad) + val deltaX = cos(lat1Rad) * sin(lat2Rad) - sin(lat1Rad) * cos(lat2Rad) * cos(deltaLng) + + var heading = atan2(deltaY, deltaX) * RAD_TO_DEG + + // Normalize to (-180, 180] + while (heading > 180) heading -= 360 + while (heading <= -180) heading += 360 + + return heading + } + + /** + * Returns the GeoPointInterface resulting from moving a distance from an origin + * in the specified heading (expressed in degrees clockwise from north). + * + * @param origin Starting point + * @param distance Distance to travel in meters + * @param heading Direction to travel in degrees (0 = North, 90 = East) + * @return New GeoPointInterface position + */ + fun computeOffset( + origin: GeoPointInterface, + distance: Double, + heading: Double, + ): GeoPoint { + val distanceRad = distance / Earth.RADIUS_METERS + val headingRad = heading * DEG_TO_RAD + val lat1Rad = origin.latitude * DEG_TO_RAD + val lng1Rad = origin.longitude * DEG_TO_RAD + + val lat2Rad = + asin( + sin(lat1Rad) * cos(distanceRad) + + cos(lat1Rad) * sin(distanceRad) * cos(headingRad), + ) + + val lng2Rad = + lng1Rad + + atan2( + sin(headingRad) * sin(distanceRad) * cos(lat1Rad), + cos(distanceRad) - sin(lat1Rad) * sin(lat2Rad), + ) + + return GeoPoint( + latitude = lat2Rad * RAD_TO_DEG, + longitude = lng2Rad * RAD_TO_DEG, + altitude = origin.altitude ?: 0.0, + ) + } + + /** + * Returns the location of origin when provided with a GeoPointInterface destination, + * meters travelled and original heading. + * Headings are expressed in degrees clockwise from North. + * + * @param to Destination point + * @param distance Distance travelled in meters + * @param heading Original heading in degrees + * @return Origin GeoPointInterface position, or null if no solution is available + */ + fun computeOffsetOrigin( + to: GeoPointInterface, + distance: Double, + heading: Double, + ): GeoPoint? { + // Calculate the reverse heading + val reverseHeading = (heading + 180) % 360 + + return try { + computeOffset(to, distance, reverseHeading) + } catch (e: Exception) { + null + } + } + + /** + * Returns the length of the given path in meters. + * + * @param path List of GeoPointInterface locations defining the path + * @return Length in meters + */ + fun computeLength(path: List): Double { + if (path.size < 2) return 0.0 + + var length = 0.0 + for (i in 1 until path.size) { + length += computeDistanceBetween(path[i - 1], path[i]) + } + + return length + } + + /** + * Returns the area of a closed path in square meters. + * The path should form a closed polygon. + * + * @param path List of GeoPointInterface locations defining the closed path + * @return Area in square meters + */ + fun computeArea(path: List): Double = abs(computeSignedArea(path)) + + /** + * Returns the signed area of a closed path in square meters. + * The signed area may be used to determine the orientation of the path. + * Positive values indicate clockwise orientation, + * negative values indicate counter-clockwise orientation + * (as seen on a north-up map, e.g. SW -> NW -> NE -> SE is clockwise and positive). + * + * @param path List of GeoPointInterface locations defining the closed path + * @return Signed area in square meters + */ + fun computeSignedArea(path: List): Double { + if (path.size < 3) return 0.0 + + var area = 0.0 + val pointCount = path.size + + for (i in path.indices) { + val j = (i + 1) % pointCount + val lat1 = path[i].latitude * DEG_TO_RAD + val lat2 = path[j].latitude * DEG_TO_RAD + val deltaLng = (path[j].longitude - path[i].longitude) * DEG_TO_RAD + + area += deltaLng * (2 + sin(lat1) + sin(lat2)) + } + + return area * Earth.RADIUS_METERS * Earth.RADIUS_METERS / 2.0 + } + + /** + * Interpolates between two GeoPointInterface locations along the great circle path using spherical linear interpolation (Slerp). + * This method considers Earth's curvature and provides high accuracy for any distance. + * + * @param from Starting point + * @param to Ending point + * @param fraction Interpolation fraction (0.0 = from, 1.0 = to) + * @return Interpolated GeoPointInterface position + */ + fun interpolate( + from: GeoPointInterface, + to: GeoPointInterface, + fraction: Double, + ): GeoPoint { + // ラジアンに変換 + val lat1 = from.latitude * DEG_TO_RAD + val lng1 = from.longitude * DEG_TO_RAD + val lat2 = to.latitude * DEG_TO_RAD + val lng2 = to.longitude * DEG_TO_RAD + + // 3D単位ベクトルに変換 + val x1 = cos(lat1) * cos(lng1) + val y1 = cos(lat1) * sin(lng1) + val z1 = sin(lat1) + + val x2 = cos(lat2) * cos(lng2) + val y2 = cos(lat2) * sin(lng2) + val z2 = sin(lat2) + + // 内積から角度を求める + val dot = x1 * x2 + y1 * y2 + z1 * z2 + val angle = acos(dot.coerceIn(-1.0, 1.0)) + + // 非常に近い点は線形補間 + if (angle < 1e-6) { + val interpolatedAltitude = + when { + from.altitude != null && to.altitude != null -> + from.altitude!! + fraction * (to.altitude!! - from.altitude!!) + from.altitude != null -> from.altitude + to.altitude != null -> to.altitude + else -> 0.0 + } + + return GeoPoint( + latitude = from.latitude + fraction * (to.latitude - from.latitude), + longitude = from.longitude + fraction * (to.longitude - from.longitude), + altitude = interpolatedAltitude!!, + ) + } + + // 球面線形補間(Slerp) + val sinAngle = sin(angle) + val weightFrom = sin((1 - fraction) * angle) / sinAngle + val weightTo = sin(fraction * angle) / sinAngle + + val vectorX = weightFrom * x1 + weightTo * x2 + val vectorY = weightFrom * y1 + weightTo * y2 + val vectorZ = weightFrom * z1 + weightTo * z2 + + // 3Dベクトルから緯度経度に変換 + val lat = asin(vectorZ) * RAD_TO_DEG + val lng = atan2(vectorY, vectorX) * RAD_TO_DEG + + val interpolatedAltitude = + when { + from.altitude != null && to.altitude != null -> + from.altitude!! + fraction * (to.altitude!! - from.altitude!!) + from.altitude != null -> from.altitude + to.altitude != null -> to.altitude + else -> 0.0 + } + + return GeoPoint( + latitude = lat, + longitude = lng, + altitude = interpolatedAltitude!!, + ) + } + + // `linearInterpolate` moved to `Planar.interpolate` (the straight-line model)。 + // 説明もそちらの KDoc にある。 + + /** + * Clamps latitude to the range [-90, 90]. + */ + private fun clampLat(lat: Double): Double = lat.coerceIn(-90.0, 90.0) +} diff --git a/src/main/java/com/mapconductor/core/spherical/WGS84Geodesic.kt b/src/main/java/com/mapconductor/core/spherical/WGS84Geodesic.kt index 35a3521..198dd01 100644 --- a/src/main/java/com/mapconductor/core/spherical/WGS84Geodesic.kt +++ b/src/main/java/com/mapconductor/core/spherical/WGS84Geodesic.kt @@ -1,323 +1,326 @@ -package com.mapconductor.core.spherical - -import com.mapconductor.core.features.GeoPoint -import com.mapconductor.core.features.GeoPointInterface -import com.mapconductor.core.projection.Earth -import kotlin.math.abs -import kotlin.math.atan -import kotlin.math.atan2 -import kotlin.math.cos -import kotlin.math.ln -import kotlin.math.sin -import kotlin.math.sqrt - -/** - * WGS84 ellipsoid geodesic distance/interpolation via Vincenty's formulae. - * Ported from the react-sdk/ios-sdk implementations so all platforms agree - * without depending on an external geographiclib library. Vincenty can fail - * to converge for near-antipodal point pairs; in that (rare, map-rendering- - * irrelevant) case this falls back to a spherical (haversine) approximation, - * matching react/ios behavior exactly. - */ -object WGS84Geodesic { - private const val FLATTENING = Earth.FLATTENING - private const val SEMI_MAJOR_AXIS = Earth.RADIUS_METERS - private const val SEMI_MINOR_AXIS = Earth.SEMI_MINOR_AXIS_METERS - - // Authalic-sphere constants for ellipsoidal polygon area (see computeSignedArea). - private val ECCENTRICITY_SQ = FLATTENING * (2 - FLATTENING) - private val ECCENTRICITY = sqrt(ECCENTRICITY_SQ) - private val AUTHALIC_QP = - 1 - ((1 - ECCENTRICITY_SQ) / (2 * ECCENTRICITY)) * - ln((1 - ECCENTRICITY) / (1 + ECCENTRICITY)) - private val AUTHALIC_RADIUS = SEMI_MAJOR_AXIS * sqrt(AUTHALIC_QP / 2) - - private data class InverseResult( - val distanceMeters: Double, - val initialBearingRad: Double, - ) - - fun computeDistanceBetween( - from: GeoPointInterface, - to: GeoPointInterface, - ): Double = inverse(from, to).distanceMeters - - fun computeHeading( - from: GeoPointInterface, - to: GeoPointInterface, - ): Double = Math.toDegrees(inverse(from, to).initialBearingRad) - - fun computeOffset( - origin: GeoPointInterface, - distance: Double, - heading: Double, - ): GeoPoint { - val destination = direct(origin, Math.toRadians(heading), distance) - return GeoPoint(destination.first, destination.second, origin.altitude ?: 0.0) - } - - fun computeOffsetOrigin( - to: GeoPointInterface, - distance: Double, - heading: Double, - ): GeoPoint? = computeOffset(to, distance, (heading + 180.0) % 360.0) - - fun computeLength(path: List): Double { - if (path.size < 2) return 0.0 - var length = 0.0 - for (i in 1 until path.size) { - length += computeDistanceBetween(path[i - 1], path[i]) - } - return length - } - - /** Densify a path by inserting points along the geodesic. */ - fun createInterpolatePoints( - points: List, - maxSegmentLength: Double = 10000.0, - ): List = densifyAlongGeodesic(points, maxSegmentLength) - - /** Closest point on the geodesic segment within [thresholdMeters], or null. */ - fun pointOnLineOrNull( - from: GeoPointInterface, - to: GeoPointInterface, - position: GeoPointInterface, - thresholdMeters: Double, - ): Pair? = geodesicPointOnLineOrNull(from, to, position, thresholdMeters) - - /** - * Ellipsoidal (authalic-sphere) polygon area. Maps geodetic latitudes to - * authalic latitudes on the equal-area sphere of radius [AUTHALIC_RADIUS] - * (which reproduces the exact WGS84 surface area), then applies the - * spherical-excess formula. Accounts for flattening — unlike the sphere-based - * [Spherical.computeSignedArea] — matching the ellipsoidal area to well under - * 0.01% for typical polygons. Edges are treated as authalic-sphere arcs; the - * higher-order geodesic-edge terms of Karney's exact method are omitted. - */ - fun computeSignedArea(path: List): Double { - if (path.size < 3) return 0.0 - var area = 0.0 - val pointCount = path.size - for (i in 0 until pointCount) { - val j = (i + 1) % pointCount - val sinXi1 = authalicSinLatitude(path[i].latitude) - val sinXi2 = authalicSinLatitude(path[j].latitude) - val deltaLng = Math.toRadians(path[j].longitude - path[i].longitude) - area += deltaLng * (2 + sinXi1 + sinXi2) - } - return area * AUTHALIC_RADIUS * AUTHALIC_RADIUS / 2.0 - } - - fun computeArea(path: List): Double = abs(computeSignedArea(path)) - - private fun authalicSinLatitude(latitudeDeg: Double): Double { - val sinPhi = sin(Math.toRadians(latitudeDeg)) - val q = - (1 - ECCENTRICITY_SQ) * - ( - sinPhi / (1 - ECCENTRICITY_SQ * sinPhi * sinPhi) - - (1 / (2 * ECCENTRICITY)) * - ln((1 - ECCENTRICITY * sinPhi) / (1 + ECCENTRICITY * sinPhi)) - ) - return q / AUTHALIC_QP - } - - fun interpolate( - from: GeoPointInterface, - to: GeoPointInterface, - fraction: Double, - ): GeoPoint { - val line = inverse(from, to) - val destination = direct(from, line.initialBearingRad, line.distanceMeters * fraction) - - val altitude = - when { - from.altitude != null && to.altitude != null -> - from.altitude!! + fraction * (to.altitude!! - from.altitude!!) - from.altitude != null -> from.altitude!! - to.altitude != null -> to.altitude!! - else -> 0.0 - } - - return GeoPoint(destination.first, destination.second, altitude) - } - - private fun inverse( - from: GeoPointInterface, - to: GeoPointInterface, - ): InverseResult { - val lat1 = Math.toRadians(from.latitude) - val lat2 = Math.toRadians(to.latitude) - val lon1 = Math.toRadians(from.longitude) - val lon2 = Math.toRadians(to.longitude) - val longitudeDifference = lon2 - lon1 - - val u1 = atan((1 - FLATTENING) * Math.tan(lat1)) - val u2 = atan((1 - FLATTENING) * Math.tan(lat2)) - val sinU1 = sin(u1) - val cosU1 = cos(u1) - val sinU2 = sin(u2) - val cosU2 = cos(u2) - - var lambda = longitudeDifference - var lambdaPrev: Double - var iterLimit = 100 - var cosSqAlpha = 0.0 - var sinSigma = 0.0 - var cos2SigmaM = 0.0 - var cosSigma = 0.0 - var sigma = 0.0 - - do { - val sinLambda = sin(lambda) - val cosLambda = cos(lambda) - sinSigma = - sqrt( - (cosU2 * sinLambda) * (cosU2 * sinLambda) + - (cosU1 * sinU2 - sinU1 * cosU2 * cosLambda) * - (cosU1 * sinU2 - sinU1 * cosU2 * cosLambda), - ) - - if (sinSigma == 0.0) { - return InverseResult(0.0, 0.0) - } - - cosSigma = sinU1 * sinU2 + cosU1 * cosU2 * cosLambda - sigma = atan2(sinSigma, cosSigma) - val sinAlpha = cosU1 * cosU2 * sinLambda / sinSigma - cosSqAlpha = 1 - sinAlpha * sinAlpha - cos2SigmaM = cosSigma - 2 * sinU1 * sinU2 / cosSqAlpha - if (!cos2SigmaM.isFinite()) cos2SigmaM = 0.0 - - val correctionFactor = FLATTENING / 16 * cosSqAlpha * (4 + FLATTENING * (4 - 3 * cosSqAlpha)) - lambdaPrev = lambda - lambda = - longitudeDifference + - (1 - correctionFactor) * FLATTENING * sinAlpha * - ( - sigma + - correctionFactor * sinSigma * - (cos2SigmaM + correctionFactor * cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM)) - ) - iterLimit -= 1 - } while (abs(lambda - lambdaPrev) > 1e-12 && iterLimit > 0) - - if (iterLimit == 0) return sphericalFallbackInverse(from, to) - - val uSq = - cosSqAlpha * (SEMI_MAJOR_AXIS * SEMI_MAJOR_AXIS - SEMI_MINOR_AXIS * SEMI_MINOR_AXIS) / - (SEMI_MINOR_AXIS * SEMI_MINOR_AXIS) - val ellipsoidFactor = 1 + uSq / 16384 * (4096 + uSq * (-768 + uSq * (320 - 175 * uSq))) - val correctionTerm = uSq / 1024 * (256 + uSq * (-128 + uSq * (74 - 47 * uSq))) - val deltaSigma = - correctionTerm * sinSigma * ( - cos2SigmaM + correctionTerm / 4 * ( - cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM) - - correctionTerm / 6 * cos2SigmaM * (-3 + 4 * sinSigma * sinSigma) * - (-3 + 4 * cos2SigmaM * cos2SigmaM) - ) - ) - - val distance = SEMI_MINOR_AXIS * ellipsoidFactor * (sigma - deltaSigma) - val initialBearing = - atan2( - cosU2 * sin(lambda), - cosU1 * sinU2 - sinU1 * cosU2 * cos(lambda), - ) - - return InverseResult(distance, initialBearing) - } - - private fun direct( - origin: GeoPointInterface, - initialBearingRad: Double, - distanceMeters: Double, - ): Pair { - val lat1 = Math.toRadians(origin.latitude) - val lon1 = Math.toRadians(origin.longitude) - val sinAlpha1 = sin(initialBearingRad) - val cosAlpha1 = cos(initialBearingRad) - - val tanU1 = (1 - FLATTENING) * Math.tan(lat1) - val cosU1 = 1 / sqrt(1 + tanU1 * tanU1) - val sinU1 = tanU1 * cosU1 - val sigma1 = atan2(tanU1, cosAlpha1) - val sinAlpha = cosU1 * sinAlpha1 - val cosSqAlpha = 1 - sinAlpha * sinAlpha - val uSq = - cosSqAlpha * (SEMI_MAJOR_AXIS * SEMI_MAJOR_AXIS - SEMI_MINOR_AXIS * SEMI_MINOR_AXIS) / - (SEMI_MINOR_AXIS * SEMI_MINOR_AXIS) - val ellipsoidFactor = 1 + uSq / 16384 * (4096 + uSq * (-768 + uSq * (320 - 175 * uSq))) - val correctionTerm = uSq / 1024 * (256 + uSq * (-128 + uSq * (74 - 47 * uSq))) - - var sigma = distanceMeters / (SEMI_MINOR_AXIS * ellipsoidFactor) - var sigmaPrev: Double - var cos2SigmaM = 0.0 - var sinSigma = 0.0 - var cosSigma = 0.0 - // ios-sdk と同じく非収束の病的入力での無限ループを防ぐ反復上限。 - var iterLimit = 1000 - - do { - cos2SigmaM = cos(2 * sigma1 + sigma) - sinSigma = sin(sigma) - cosSigma = cos(sigma) - val deltaSigma = - correctionTerm * sinSigma * ( - cos2SigmaM + correctionTerm / 4 * ( - cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM) - - correctionTerm / 6 * cos2SigmaM * (-3 + 4 * sinSigma * sinSigma) * - (-3 + 4 * cos2SigmaM * cos2SigmaM) - ) - ) - sigmaPrev = sigma - sigma = distanceMeters / (SEMI_MINOR_AXIS * ellipsoidFactor) + deltaSigma - iterLimit-- - } while (abs(sigma - sigmaPrev) > 1e-12 && iterLimit > 0) - - val tmp = sinU1 * sinSigma - cosU1 * cosSigma * cosAlpha1 - val lat2 = - atan2( - sinU1 * cosSigma + cosU1 * sinSigma * cosAlpha1, - (1 - FLATTENING) * sqrt(sinAlpha * sinAlpha + tmp * tmp), - ) - val lambda = - atan2( - sinSigma * sinAlpha1, - cosU1 * cosSigma - sinU1 * sinSigma * cosAlpha1, - ) - val correctionFactor = FLATTENING / 16 * cosSqAlpha * (4 + FLATTENING * (4 - 3 * cosSqAlpha)) - val longitudeDifference = - lambda - (1 - correctionFactor) * FLATTENING * sinAlpha * - ( - sigma + - correctionFactor * sinSigma * - (cos2SigmaM + correctionFactor * cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM)) - ) - val lon2 = lon1 + longitudeDifference - - return Pair(Math.toDegrees(lat2), normalizeLng(Math.toDegrees(lon2))) - } - - private fun sphericalFallbackInverse( - from: GeoPointInterface, - to: GeoPointInterface, - ): InverseResult { - val lat1 = Math.toRadians(from.latitude) - val lat2 = Math.toRadians(to.latitude) - val deltaLat = Math.toRadians(to.latitude - from.latitude) - val deltaLng = Math.toRadians(to.longitude - from.longitude) - val a = - sin(deltaLat / 2) * sin(deltaLat / 2) + - cos(lat1) * cos(lat2) * sin(deltaLng / 2) * sin(deltaLng / 2) - val centralAngle = 2 * atan2(sqrt(a), sqrt(1 - a)) - val y = sin(deltaLng) * cos(lat2) - val x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(deltaLng) - return InverseResult( - distanceMeters = SEMI_MAJOR_AXIS * centralAngle, - initialBearingRad = atan2(y, x), - ) - } - - private fun normalizeLng(lng: Double): Double = ((((lng + 180.0) % 360.0) + 360.0) % 360.0) - 180.0 -} +package com.mapconductor.core.spherical + +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.features.GeoPointInterface +import com.mapconductor.core.projection.Earth +import kotlin.math.abs +import kotlin.math.atan +import kotlin.math.atan2 +import kotlin.math.cos +import kotlin.math.ln +import kotlin.math.sin +import kotlin.math.sqrt + +/** + * WGS84 ellipsoid geodesic distance/interpolation via Vincenty's formulae. + * Ported from the react-sdk/ios-sdk implementations so all platforms agree + * without depending on an external geographiclib library. Vincenty can fail + * to converge for near-antipodal point pairs; in that (rare, map-rendering- + * irrelevant) case this falls back to a spherical (haversine) approximation, + * matching react/ios behavior exactly. + */ +object WGS84Geodesic { + private const val FLATTENING = Earth.FLATTENING + private const val SEMI_MAJOR_AXIS = Earth.RADIUS_METERS + private const val SEMI_MINOR_AXIS = Earth.SEMI_MINOR_AXIS_METERS + + // Authalic-sphere constants for ellipsoidal polygon area (see computeSignedArea). + private val ECCENTRICITY_SQ = FLATTENING * (2 - FLATTENING) + private val ECCENTRICITY = sqrt(ECCENTRICITY_SQ) + private val AUTHALIC_QP = + 1 - ((1 - ECCENTRICITY_SQ) / (2 * ECCENTRICITY)) * + ln((1 - ECCENTRICITY) / (1 + ECCENTRICITY)) + private val AUTHALIC_RADIUS = SEMI_MAJOR_AXIS * sqrt(AUTHALIC_QP / 2) + + private data class InverseResult( + val distanceMeters: Double, + val initialBearingRad: Double, + ) + + fun computeDistanceBetween( + from: GeoPointInterface, + to: GeoPointInterface, + ): Double = inverse(from, to).distanceMeters + + fun computeHeading( + from: GeoPointInterface, + to: GeoPointInterface, + ): Double = Math.toDegrees(inverse(from, to).initialBearingRad) + + fun computeOffset( + origin: GeoPointInterface, + distance: Double, + heading: Double, + ): GeoPoint { + val destination = direct(origin, Math.toRadians(heading), distance) + return GeoPoint(destination.first, destination.second, origin.altitude ?: 0.0) + } + + fun computeOffsetOrigin( + to: GeoPointInterface, + distance: Double, + heading: Double, + ): GeoPoint? = computeOffset(to, distance, (heading + 180.0) % 360.0) + + fun computeLength(path: List): Double { + if (path.size < 2) return 0.0 + var length = 0.0 + for (i in 1 until path.size) { + length += computeDistanceBetween(path[i - 1], path[i]) + } + return length + } + + /** Densify a path by inserting points along the geodesic. */ + fun createInterpolatePoints( + points: List, + maxSegmentLength: Double = 10000.0, + ): List = densifyAlongGeodesic(points, maxSegmentLength) + + /** Closest point on the geodesic segment within [thresholdMeters], or null. */ + fun pointOnLineOrNull( + from: GeoPointInterface, + to: GeoPointInterface, + position: GeoPointInterface, + thresholdMeters: Double, + ): Pair? = geodesicPointOnLineOrNull(from, to, position, thresholdMeters) + + /** + * Ellipsoidal (authalic-sphere) polygon area. Maps geodetic latitudes to + * authalic latitudes on the equal-area sphere of radius [AUTHALIC_RADIUS] + * (which reproduces the exact WGS84 surface area), then applies the + * spherical-excess formula. Accounts for flattening — unlike the sphere-based + * [Spherical.computeSignedArea] — matching the ellipsoidal area to well under + * 0.01% for typical polygons. Edges are treated as authalic-sphere arcs; the + * higher-order geodesic-edge terms of Karney's exact method are omitted. + * + * The sign follows [Spherical.computeSignedArea]: positive for a clockwise + * ring, negative for a counter-clockwise ring (as seen on a north-up map). + */ + fun computeSignedArea(path: List): Double { + if (path.size < 3) return 0.0 + var area = 0.0 + val pointCount = path.size + for (i in 0 until pointCount) { + val j = (i + 1) % pointCount + val sinXi1 = authalicSinLatitude(path[i].latitude) + val sinXi2 = authalicSinLatitude(path[j].latitude) + val deltaLng = Math.toRadians(path[j].longitude - path[i].longitude) + area += deltaLng * (2 + sinXi1 + sinXi2) + } + return area * AUTHALIC_RADIUS * AUTHALIC_RADIUS / 2.0 + } + + fun computeArea(path: List): Double = abs(computeSignedArea(path)) + + private fun authalicSinLatitude(latitudeDeg: Double): Double { + val sinPhi = sin(Math.toRadians(latitudeDeg)) + val q = + (1 - ECCENTRICITY_SQ) * + ( + sinPhi / (1 - ECCENTRICITY_SQ * sinPhi * sinPhi) - + (1 / (2 * ECCENTRICITY)) * + ln((1 - ECCENTRICITY * sinPhi) / (1 + ECCENTRICITY * sinPhi)) + ) + return q / AUTHALIC_QP + } + + fun interpolate( + from: GeoPointInterface, + to: GeoPointInterface, + fraction: Double, + ): GeoPoint { + val line = inverse(from, to) + val destination = direct(from, line.initialBearingRad, line.distanceMeters * fraction) + + val altitude = + when { + from.altitude != null && to.altitude != null -> + from.altitude!! + fraction * (to.altitude!! - from.altitude!!) + from.altitude != null -> from.altitude!! + to.altitude != null -> to.altitude!! + else -> 0.0 + } + + return GeoPoint(destination.first, destination.second, altitude) + } + + private fun inverse( + from: GeoPointInterface, + to: GeoPointInterface, + ): InverseResult { + val lat1 = Math.toRadians(from.latitude) + val lat2 = Math.toRadians(to.latitude) + val lon1 = Math.toRadians(from.longitude) + val lon2 = Math.toRadians(to.longitude) + val longitudeDifference = lon2 - lon1 + + val u1 = atan((1 - FLATTENING) * Math.tan(lat1)) + val u2 = atan((1 - FLATTENING) * Math.tan(lat2)) + val sinU1 = sin(u1) + val cosU1 = cos(u1) + val sinU2 = sin(u2) + val cosU2 = cos(u2) + + var lambda = longitudeDifference + var lambdaPrev: Double + var iterLimit = 100 + var cosSqAlpha = 0.0 + var sinSigma = 0.0 + var cos2SigmaM = 0.0 + var cosSigma = 0.0 + var sigma = 0.0 + + do { + val sinLambda = sin(lambda) + val cosLambda = cos(lambda) + sinSigma = + sqrt( + (cosU2 * sinLambda) * (cosU2 * sinLambda) + + (cosU1 * sinU2 - sinU1 * cosU2 * cosLambda) * + (cosU1 * sinU2 - sinU1 * cosU2 * cosLambda), + ) + + if (sinSigma == 0.0) { + return InverseResult(0.0, 0.0) + } + + cosSigma = sinU1 * sinU2 + cosU1 * cosU2 * cosLambda + sigma = atan2(sinSigma, cosSigma) + val sinAlpha = cosU1 * cosU2 * sinLambda / sinSigma + cosSqAlpha = 1 - sinAlpha * sinAlpha + cos2SigmaM = cosSigma - 2 * sinU1 * sinU2 / cosSqAlpha + if (!cos2SigmaM.isFinite()) cos2SigmaM = 0.0 + + val correctionFactor = FLATTENING / 16 * cosSqAlpha * (4 + FLATTENING * (4 - 3 * cosSqAlpha)) + lambdaPrev = lambda + lambda = + longitudeDifference + + (1 - correctionFactor) * FLATTENING * sinAlpha * + ( + sigma + + correctionFactor * sinSigma * + (cos2SigmaM + correctionFactor * cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM)) + ) + iterLimit -= 1 + } while (abs(lambda - lambdaPrev) > 1e-12 && iterLimit > 0) + + if (iterLimit == 0) return sphericalFallbackInverse(from, to) + + val uSq = + cosSqAlpha * (SEMI_MAJOR_AXIS * SEMI_MAJOR_AXIS - SEMI_MINOR_AXIS * SEMI_MINOR_AXIS) / + (SEMI_MINOR_AXIS * SEMI_MINOR_AXIS) + val ellipsoidFactor = 1 + uSq / 16384 * (4096 + uSq * (-768 + uSq * (320 - 175 * uSq))) + val correctionTerm = uSq / 1024 * (256 + uSq * (-128 + uSq * (74 - 47 * uSq))) + val deltaSigma = + correctionTerm * sinSigma * ( + cos2SigmaM + correctionTerm / 4 * ( + cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM) - + correctionTerm / 6 * cos2SigmaM * (-3 + 4 * sinSigma * sinSigma) * + (-3 + 4 * cos2SigmaM * cos2SigmaM) + ) + ) + + val distance = SEMI_MINOR_AXIS * ellipsoidFactor * (sigma - deltaSigma) + val initialBearing = + atan2( + cosU2 * sin(lambda), + cosU1 * sinU2 - sinU1 * cosU2 * cos(lambda), + ) + + return InverseResult(distance, initialBearing) + } + + private fun direct( + origin: GeoPointInterface, + initialBearingRad: Double, + distanceMeters: Double, + ): Pair { + val lat1 = Math.toRadians(origin.latitude) + val lon1 = Math.toRadians(origin.longitude) + val sinAlpha1 = sin(initialBearingRad) + val cosAlpha1 = cos(initialBearingRad) + + val tanU1 = (1 - FLATTENING) * Math.tan(lat1) + val cosU1 = 1 / sqrt(1 + tanU1 * tanU1) + val sinU1 = tanU1 * cosU1 + val sigma1 = atan2(tanU1, cosAlpha1) + val sinAlpha = cosU1 * sinAlpha1 + val cosSqAlpha = 1 - sinAlpha * sinAlpha + val uSq = + cosSqAlpha * (SEMI_MAJOR_AXIS * SEMI_MAJOR_AXIS - SEMI_MINOR_AXIS * SEMI_MINOR_AXIS) / + (SEMI_MINOR_AXIS * SEMI_MINOR_AXIS) + val ellipsoidFactor = 1 + uSq / 16384 * (4096 + uSq * (-768 + uSq * (320 - 175 * uSq))) + val correctionTerm = uSq / 1024 * (256 + uSq * (-128 + uSq * (74 - 47 * uSq))) + + var sigma = distanceMeters / (SEMI_MINOR_AXIS * ellipsoidFactor) + var sigmaPrev: Double + var cos2SigmaM = 0.0 + var sinSigma = 0.0 + var cosSigma = 0.0 + // ios-sdk と同じく非収束の病的入力での無限ループを防ぐ反復上限。 + var iterLimit = 1000 + + do { + cos2SigmaM = cos(2 * sigma1 + sigma) + sinSigma = sin(sigma) + cosSigma = cos(sigma) + val deltaSigma = + correctionTerm * sinSigma * ( + cos2SigmaM + correctionTerm / 4 * ( + cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM) - + correctionTerm / 6 * cos2SigmaM * (-3 + 4 * sinSigma * sinSigma) * + (-3 + 4 * cos2SigmaM * cos2SigmaM) + ) + ) + sigmaPrev = sigma + sigma = distanceMeters / (SEMI_MINOR_AXIS * ellipsoidFactor) + deltaSigma + iterLimit-- + } while (abs(sigma - sigmaPrev) > 1e-12 && iterLimit > 0) + + val tmp = sinU1 * sinSigma - cosU1 * cosSigma * cosAlpha1 + val lat2 = + atan2( + sinU1 * cosSigma + cosU1 * sinSigma * cosAlpha1, + (1 - FLATTENING) * sqrt(sinAlpha * sinAlpha + tmp * tmp), + ) + val lambda = + atan2( + sinSigma * sinAlpha1, + cosU1 * cosSigma - sinU1 * sinSigma * cosAlpha1, + ) + val correctionFactor = FLATTENING / 16 * cosSqAlpha * (4 + FLATTENING * (4 - 3 * cosSqAlpha)) + val longitudeDifference = + lambda - (1 - correctionFactor) * FLATTENING * sinAlpha * + ( + sigma + + correctionFactor * sinSigma * + (cos2SigmaM + correctionFactor * cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM)) + ) + val lon2 = lon1 + longitudeDifference + + return Pair(Math.toDegrees(lat2), normalizeLng(Math.toDegrees(lon2))) + } + + private fun sphericalFallbackInverse( + from: GeoPointInterface, + to: GeoPointInterface, + ): InverseResult { + val lat1 = Math.toRadians(from.latitude) + val lat2 = Math.toRadians(to.latitude) + val deltaLat = Math.toRadians(to.latitude - from.latitude) + val deltaLng = Math.toRadians(to.longitude - from.longitude) + val a = + sin(deltaLat / 2) * sin(deltaLat / 2) + + cos(lat1) * cos(lat2) * sin(deltaLng / 2) * sin(deltaLng / 2) + val centralAngle = 2 * atan2(sqrt(a), sqrt(1 - a)) + val y = sin(deltaLng) * cos(lat2) + val x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(deltaLng) + return InverseResult( + distanceMeters = SEMI_MAJOR_AXIS * centralAngle, + initialBearingRad = atan2(y, x), + ) + } + + private fun normalizeLng(lng: Double): Double = ((((lng + 180.0) % 360.0) + 360.0) % 360.0) - 180.0 +} diff --git a/src/main/java/com/mapconductor/core/tileserver/LocalTileServer.kt b/src/main/java/com/mapconductor/core/tileserver/LocalTileServer.kt index 23cce36..5fdee31 100644 --- a/src/main/java/com/mapconductor/core/tileserver/LocalTileServer.kt +++ b/src/main/java/com/mapconductor/core/tileserver/LocalTileServer.kt @@ -1,465 +1,844 @@ -package com.mapconductor.core.tileserver - -import java.io.BufferedReader -import java.io.InputStreamReader -import java.net.ServerSocket -import java.net.Socket -import java.util.concurrent.ArrayBlockingQueue -import java.util.concurrent.ConcurrentHashMap -import java.util.concurrent.RejectedExecutionException -import java.util.concurrent.ThreadPoolExecutor -import java.util.concurrent.TimeUnit -import java.util.concurrent.atomic.AtomicBoolean -import java.util.concurrent.atomic.AtomicLong -import android.util.Log - -class LocalTileServer private constructor( - private val serverSocket: ServerSocket, - forceNoStoreCache: Boolean, -) { - private val providers = ConcurrentHashMap() - private val loggedRoutes = ConcurrentHashMap.newKeySet() - private val running = AtomicBoolean(false) - private val acceptThread = Thread { acceptLoop() } - private val shedConnections = AtomicLong(0) - - // Bounded worker pool: excess connections beyond the queue capacity are - // rejected and closed instead of spawning unbounded threads. - private val clientExecutor = - ThreadPoolExecutor( - MAX_WORKER_THREADS, - MAX_WORKER_THREADS, - WORKER_KEEP_ALIVE_SECONDS, - TimeUnit.SECONDS, - ArrayBlockingQueue(MAX_QUEUED_CONNECTIONS), - { runnable -> Thread(runnable).apply { isDaemon = true } }, - ).apply { allowCoreThreadTimeOut(true) } - - @Volatile - private var forceNoStoreCache: Boolean = forceNoStoreCache - - val baseUrl: String = "http://127.0.0.1:${serverSocket.localPort}" - - fun setForceNoStoreCache(value: Boolean) { - forceNoStoreCache = value - } - - fun register( - routeId: String, - provider: TileProviderInterface, - ) { - providers[routeId] = provider - } - - fun unregister(routeId: String) { - providers.remove(routeId) - } - - fun urlTemplate( - routeId: String, - tileSize: Int, - ): String = "$baseUrl/tiles/$routeId/$tileSize/{z}/{x}/{y}.png" - - fun urlTemplate( - routeId: String, - tileSize: Int, - cacheKey: String, - ): String = "$baseUrl/tiles/$routeId/$tileSize/$cacheKey/{z}/{x}/{y}.png" - - /** - * URL template with cache key as query parameter instead of path segment. - * Some map SDKs (like HERE) may have stricter URL template parsing. - */ - fun urlTemplateWithQueryCacheKey( - routeId: String, - tileSize: Int, - cacheKey: String, - ): String = "$baseUrl/tiles/$routeId/$tileSize/{z}/{x}/{y}.png?v=$cacheKey" - - /** - * Whether the server is accepting connections. A stopped server cannot be - * restarted (its socket and worker pool are closed) — create a new one. - */ - fun isRunning(): Boolean = running.get() - - fun start() { - if (running.compareAndSet(false, true)) { - acceptThread.isDaemon = true - acceptThread.start() - } - } - - fun stop() { - if (running.compareAndSet(true, false)) { - serverSocket.close() - clientExecutor.shutdownNow() - } - } - - private fun acceptLoop() { - while (running.get()) { - val socket = - try { - serverSocket.accept() - } catch (_: Exception) { - if (running.get()) { - continue - } - return - } - // Only serve device-internal clients: a remote peer cannot complete - // a TCP handshake with a spoofed loopback source address. - if (socket.inetAddress?.isLoopbackAddress != true) { - Log.w(TAG, "Rejected non-loopback connection from ${socket.inetAddress}") - try { - socket.close() - } catch (_: Exception) { - } - continue - } - try { - clientExecutor.execute { handleClient(socket) } - } catch (_: RejectedExecutionException) { - // Saturated: shed the connection; the map SDK will retry the tile. - val shed = shedConnections.incrementAndGet() - Log.w( - TAG, - "Shed connection (pool saturated) total=$shed " + - "active=${clientExecutor.activeCount} queued=${clientExecutor.queue.size}", - ) - try { - socket.close() - } catch (_: Exception) { - } - } - } - } - - private fun handleClient(socket: Socket) { - socket.use { client -> - try { - client.soTimeout = 5000 - val reader = BufferedReader(InputStreamReader(client.getInputStream())) - var handled = 0 - while (handled < MAX_KEEP_ALIVE_REQUESTS) { - val request = readRequest(reader) ?: break - if (!request.valid) { - writeResponse(client, "400 Bad Request", "text/plain", "Bad request".toByteArray()) - break - } - - val startNs = System.nanoTime() - val method = request.method - val path = request.path.substringBefore('?').trim('/') - val keepAlive = shouldKeepAlive(request) - Log.d("Server", "---->$path") - - if (method != "GET") { - writeResponse( - client, - "405 Method Not Allowed", - "text/plain", - "Method not allowed".toByteArray(), - keepAlive = false, - extraHeaders = mapOf("Allow" to "GET", "Cache-Control" to "no-store"), - ) - break - } - - val tileResponse = resolveTile(path) - val status: String - val contentType: String - val body: ByteArray - val headers: Map - if (tileResponse == null) { - status = "404 Not Found" - contentType = "text/plain" - body = "Not found".toByteArray() - headers = cacheHeaders(NO_STORE_CACHE_CONTROL) - } else { - status = "200 OK" - contentType = "image/png" - body = tileResponse.body - headers = cacheHeaders(tileResponse.cacheControl) - } - - val ok = - writeResponse( - client, - status, - contentType, - body, - keepAlive = keepAlive, - extraHeaders = headers, - ) - - val tookMs = (System.nanoTime() - startNs) / 1_000_000 - if (!ok) { - Log.w(TAG, "Write failed (client canceled?) status=$status path=${request.path}") - break - } - if (tookMs >= SLOW_RESPONSE_WARN_MS) { - val key = parseTileKey(path) - if (key != null) { - Log.w( - TAG, - "Slow tile response took=${tookMs}ms route=${key.routeId} " + - "tileSize=${key.tileSize} z=${key.z} x=${key.x} y=${key.y} status=$status", - ) - } else { - Log.w(TAG, "Slow response took=${tookMs}ms status=$status path=${request.path}") - } - } - - handled += 1 - if (!keepAlive) { - break - } - } - } catch (_: Exception) { - // Ignore per-connection errors to avoid crashing the server. - } - } - } - - private fun readRequest(reader: BufferedReader): Request? { - var requestLine: String? = null - - // prevent too big header - var headerLineCnt = 30 - while (requestLine == null && headerLineCnt > 0) { - val line = readLineBounded(reader) ?: return null - if (line.isNotEmpty()) { - requestLine = line - } - headerLineCnt-- - } - if (requestLine == null) return null - - val parts = requestLine.split(" ") - val valid = parts.size >= 2 - val method = parts.getOrNull(0) ?: "" - val path = parts.getOrNull(1) ?: "" - val httpVersion = parts.getOrNull(2) ?: "HTTP/1.0" - - val headers = HashMap() - var remainingHeaders = MAX_HEADER_COUNT - while (remainingHeaders > 0) { - remainingHeaders-- - val line = readLineBounded(reader) ?: break - if (line.isEmpty()) { - break - } - val index = line.indexOf(':') - if (index <= 0) continue - val key = line.substring(0, index).trim().lowercase() - val value = line.substring(index + 1).trim() - headers[key] = value - } - - val req = - Request( - method = method, - path = path, - httpVersion = httpVersion, - headers = headers, - valid = valid, - ) - return req - } - - /** - * Reads one CRLF/LF-terminated line, giving up (null) if it exceeds - * [MAX_LINE_LENGTH] — unlike BufferedReader.readLine(), which buffers an - * arbitrarily long line in memory. - */ - private fun readLineBounded(reader: BufferedReader): String? { - val sb = StringBuilder() - while (true) { - val ch = reader.read() - if (ch == -1) { - return if (sb.isEmpty()) null else sb.toString() - } - when (ch.toChar()) { - '\n' -> return sb.toString() - '\r' -> { - // Swallow the CR; the LF (if any) terminates on the next read. - } - else -> { - if (sb.length >= MAX_LINE_LENGTH) return null - sb.append(ch.toChar()) - } - } - } - } - - private fun shouldKeepAlive(request: Request): Boolean { - val connection = request.headers["connection"]?.lowercase() - return when (request.httpVersion) { - "HTTP/1.1" -> connection != "close" - "HTTP/1.0" -> connection == "keep-alive" - else -> false - } - } - - private fun resolveTile(path: String): TileResponse? { - val key = parseTileKey(path) ?: return null - val routeId = key.routeId - val z = key.z - val x = key.x - val y = key.y - - if (loggedRoutes.add(routeId)) { - Log.d("LocalTileServer", "First tile request route=$routeId tileSize=${key.tileSize} z=$z x=$x y=$y") - } - - val provider = providers[routeId] ?: return null - val bytes = - provider.renderTile( - TileRequest(x = x, y = y, z = z, pixelRatio = key.pixelRatio), - ) ?: return null - val cacheControl = - if (forceNoStoreCache) { - NO_STORE_CACHE_CONTROL - } else { - LONG_CACHE_CONTROL - } - return TileResponse(bytes, cacheControl) - } - - private fun parseTileKey(path: String): TileKey? { - if (path.isEmpty()) return null - val segments = path.split("/").filter { it.isNotEmpty() } - if (segments.size < 6 || segments[0] != "tiles") return null - val routeId = segments[1] - val tileSize = segments[2].toIntOrNull() ?: return null - val withCacheKey = segments.size >= 7 - val zIndex = if (withCacheKey) 4 else 3 - val xIndex = if (withCacheKey) 5 else 4 - val yIndex = if (withCacheKey) 6 else 5 - val z = segments.getOrNull(zIndex)?.toIntOrNull() ?: return null - val x = segments.getOrNull(xIndex)?.toIntOrNull() ?: return null - val tileCoordinate = segments.getOrNull(yIndex)?.let(::parseTileCoordinate) ?: return null - return TileKey( - routeId = routeId, - tileSize = tileSize, - z = z, - x = x, - y = tileCoordinate.y, - pixelRatio = tileCoordinate.pixelRatio, - ) - } - - private fun cacheHeaders(cacheControl: String): Map = - mapOf( - "Cache-Control" to cacheControl, - "Pragma" to "no-cache", - "Expires" to "0", - ) - - private fun writeResponse( - client: Socket, - status: String, - contentType: String, - body: ByteArray, - keepAlive: Boolean = false, - extraHeaders: Map = emptyMap(), - ): Boolean { - try { - val output = client.getOutputStream() - val headers = StringBuilder() - headers.append("HTTP/1.1 ").append(status).append("\r\n") - headers.append("Content-Type: ").append(contentType).append("\r\n") - headers.append("Content-Length: ").append(body.size).append("\r\n") - headers.append("Connection: ").append(if (keepAlive) "keep-alive" else "close").append("\r\n") - // WebView ベースの地図 SDK(Longdo / MapTiler 等)は MapLibre GL JS の fetch でタイルを取得する。 - // ローカルサーバは https のページから見て別オリジンのため、CORS を許可しないと取得がブロックされる。 - headers.append("Access-Control-Allow-Origin: *\r\n") - for ((key, value) in extraHeaders) { - headers - .append(key) - .append(": ") - .append(value) - .append("\r\n") - } - headers.append("\r\n") - output.write(headers.toString().toByteArray()) - output.write(body) - output.flush() - return true - } catch (_: Exception) { - // Client closed the connection early or canceled; ignore. - return false - } - } - - private data class Request( - val method: String, - val path: String, - val httpVersion: String, - val headers: Map, - val valid: Boolean, - ) - - private data class TileResponse( - val body: ByteArray, - val cacheControl: String, - ) - - private data class TileKey( - val routeId: String, - val tileSize: Int, - val z: Int, - val x: Int, - val y: Int, - val pixelRatio: Int, - ) - - companion object { - private const val TAG = "LocalTileServer" - private const val MAX_KEEP_ALIVE_REQUESTS = 200 - private const val MAX_HEADER_COUNT = 64 - private const val MAX_LINE_LENGTH = 8192 - - // Tile rendering is CPU-bound (canvas + PNG encode), so more workers than - // cores adds contention, not throughput. The deep queue absorbs request - // bursts (e.g. ArcGIS fetching several LODs during a zoom animation) - // without shedding connections. - private const val MAX_WORKER_THREADS = 8 - private const val MAX_QUEUED_CONNECTIONS = 256 - private const val WORKER_KEEP_ALIVE_SECONDS = 60L - private const val LONG_CACHE_CONTROL = "public, max-age=31536000, immutable" - private const val NO_STORE_CACHE_CONTROL = "no-store, no-cache, must-revalidate, max-age=0" - private const val SLOW_RESPONSE_WARN_MS = 250L - private const val HTTP_PORT = 0 - private const val HTTP_SERVER_BACKLOG = 100 - - fun startServer(forceNoStoreCache: Boolean = false): LocalTileServer { - // Bind to the wildcard address (dual-stack) so clients can reach the - // server via either 127.0.0.1 or ::1 — binding to a single loopback - // address breaks HTTP stacks that resolve localhost to the other IP - // family (e.g. Mapbox). Device-internal access is enforced in - // acceptLoop by rejecting non-loopback source addresses. - val socket = ServerSocket(HTTP_PORT, HTTP_SERVER_BACKLOG) - val server = LocalTileServer(socket, forceNoStoreCache = forceNoStoreCache) - server.start() - return server - } - } -} - -internal data class TileCoordinate( - val y: Int, - val pixelRatio: Int, -) - -internal fun parseTileCoordinate(fileName: String): TileCoordinate? { - val match = TILE_FILE_NAME_PATTERN.matchEntire(fileName) ?: return null - val y = match.groupValues[1].toIntOrNull() ?: return null - val pixelRatio = match.groupValues[2].toIntOrNull() ?: 1 - if (pixelRatio !in 1..MAX_TILE_PIXEL_RATIO) return null - return TileCoordinate(y = y, pixelRatio = pixelRatio) -} - -private val TILE_FILE_NAME_PATTERN = Regex("""^(\d+)(?:@(\d+)x)?\.png$""") -private const val MAX_TILE_PIXEL_RATIO = 3 +package com.mapconductor.core.tileserver + +import java.io.BufferedReader +import java.io.InputStreamReader +import java.net.ServerSocket +import java.net.Socket +import java.util.concurrent.ArrayBlockingQueue +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.RejectedExecutionException +import java.util.concurrent.ThreadPoolExecutor +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicBoolean +import java.util.concurrent.atomic.AtomicLong +import android.util.Log + +class LocalTileServer private constructor( + private val serverSocket: ServerSocket, + forceNoStoreCache: Boolean, +) { + private val providers = ConcurrentHashMap() + + /** + * ルートごとの「このレベルは透明でよい」判定。 + * + * ArcGIS の 3D ビューは画面のレベルより上の全レベルも要求し、画面のレベルが + * 載れば一枚も描かない。要求ごとのフックを持たない Android の + * `WebTiledLayer` では、ここで provider を呼ぶ前に透明を返すのが唯一の手。 + * 透明は `no-store` で返す。ArcGIS 側のキャッシュは別で、それは呼び手が + * レイヤーを作り直して捨てる。 + */ + private val levelGates = ConcurrentHashMap Boolean>() + + /** + * Whole documents served by id, beside the tiles: a style JSON that a + * vector-capable map is to read directly, for one. Served `no-store` -- + * the id changes when the content does, so there is nothing to revalidate, + * and a map holding on to a stale document is harder to notice than one + * refetching a small one. + */ + private val documents = ConcurrentHashMap() + + /** + * Directories served by route, for a map that reads its style's tiles, + * glyphs and sprite straight from the device: an offline package. A path + * that is not in the directory is offered to the route's fallback, which + * is how "online" and "offline" differ for the same package -- online, + * the fallback fetches upstream; offline, there is none, and the map is + * told there is no such tile. + */ + private val fileRoutes = ConcurrentHashMap() + + /** Requests dropped because the map had stopped waiting for them. */ + private val abandoned = AtomicLong() + private val loggedRoutes = ConcurrentHashMap.newKeySet() + private val running = AtomicBoolean(false) + private val acceptThread = Thread { acceptLoop() } + private val shedConnections = AtomicLong(0) + private val renderPermits = java.util.concurrent.Semaphore(MAX_CONCURRENT_RENDERS) + + // Bounded worker pool: excess connections beyond the queue capacity are + // rejected and closed instead of spawning unbounded threads. + private val clientExecutor = + ThreadPoolExecutor( + MAX_WORKER_THREADS, + MAX_WORKER_THREADS, + WORKER_KEEP_ALIVE_SECONDS, + TimeUnit.SECONDS, + ArrayBlockingQueue(MAX_QUEUED_CONNECTIONS), + { runnable -> + Thread({ + android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND) + runnable.run() + }, "MapConductorTileWorker").apply { isDaemon = true } + }, + ).apply { allowCoreThreadTimeOut(true) } + + @Volatile + private var forceNoStoreCache: Boolean = forceNoStoreCache + + val baseUrl: String = "http://127.0.0.1:${serverSocket.localPort}" + + fun setForceNoStoreCache(value: Boolean) { + forceNoStoreCache = value + } + + fun register( + routeId: String, + provider: TileProviderInterface, + ) { + providers[routeId] = provider + } + + fun unregister(routeId: String) { + providers.remove(routeId) + levelGates.remove(routeId) + } + + /** + * [gate] が true を返すレベルの要求は、provider を呼ばずに透明タイルで答える。 + * null で解除。 + */ + fun setLevelGate( + routeId: String, + gate: ((level: Int) -> Boolean)?, + ) { + if (gate == null) levelGates.remove(routeId) else levelGates[routeId] = gate + } + + /** + * Serves [body] at [documentUrl] until [unregisterDocument]. + * + * [id] must be URL-safe as given; it is matched against the request path + * verbatim. + */ + fun registerDocument( + id: String, + contentType: String, + body: ByteArray, + ) { + documents[id] = Document(contentType, body) + } + + fun unregisterDocument(id: String) { + documents.remove(id) + } + + fun documentUrl(id: String): String = "$baseUrl/$DOCS_PREFIX/$id" + + /** + * Serves the files under [directory] at [filesUrl]`/`. + * + * The content type follows the extension (`.mvt`, `.pbf`, `.json`, + * `.png`); a file is served as immutable, since a package does not change + * under a map. A path with no file is answered by [fallback] -- served + * `no-store`, so what came from upstream is not mistaken for the package + * -- or, when that is null or answers null, with 404, which the map takes + * as "no such tile" and does not retry. + */ + fun registerFiles( + routeId: String, + directory: java.io.File, + fallback: ((relativePath: String) -> ByteArray?)? = null, + ) { + fileRoutes[routeId] = FileRoute(directory, fallback) + } + + fun unregisterFiles(routeId: String) { + fileRoutes.remove(routeId) + } + + fun filesUrl(routeId: String): String = "$baseUrl/$FILES_PREFIX/$routeId" + + fun urlTemplate( + routeId: String, + tileSize: Int, + ): String = "$baseUrl/tiles/$routeId/$tileSize/{z}/{x}/{y}.png" + + fun urlTemplate( + routeId: String, + tileSize: Int, + cacheKey: String, + ): String = "$baseUrl/tiles/$routeId/$tileSize/$cacheKey/{z}/{x}/{y}.png" + + /** + * URL template with cache key as query parameter instead of path segment. + * Some map SDKs (like HERE) may have stricter URL template parsing. + */ + fun urlTemplateWithQueryCacheKey( + routeId: String, + tileSize: Int, + cacheKey: String, + ): String = "$baseUrl/tiles/$routeId/$tileSize/{z}/{x}/{y}.png?v=$cacheKey" + + /** + * Draws the tile a local URL names, in this process, without the HTTP hop. + * + * A map SDK that fetches through its own network stack may refuse to + * while the device reports no connectivity -- HERE will not even ask + * 127.0.0.1 -- so its layer hands the request here instead. Same + * providers, same answers: the bytes of a drawn tile, a transparent tile + * where the provider has nothing, and null when the route is unknown or + * the render failed, which the caller reports as a failure the map may + * retry. The URL is one this server's own templates produced. + */ + fun renderLocalTile( + url: String, + isCancelled: () -> Boolean = { false }, + ): ByteArray? { + if (!url.startsWith("$baseUrl/")) return null + val path = url.removePrefix("$baseUrl/").substringBefore('?') + return when (val outcome = resolveTile(path, isCancelled)) { + is TileOutcome.Tile -> outcome.body + is TileOutcome.Empty -> TransparentTilePng.bytes(outcome.pixelSize) + TileOutcome.NotFound, TileOutcome.Failed -> null + } + } + + /** + * Whether the server is accepting connections. A stopped server cannot be + * restarted (its socket and worker pool are closed) — create a new one. + */ + fun isRunning(): Boolean = running.get() + + fun start() { + if (running.compareAndSet(false, true)) { + acceptThread.isDaemon = true + acceptThread.start() + } + } + + fun stop() { + if (running.compareAndSet(true, false)) { + serverSocket.close() + clientExecutor.shutdownNow() + } + } + + private fun acceptLoop() { + while (running.get()) { + val socket = + try { + serverSocket.accept() + } catch (_: Exception) { + if (running.get()) { + continue + } + return + } + // Only serve device-internal clients: a remote peer cannot complete + // a TCP handshake with a spoofed loopback source address. + if (socket.inetAddress?.isLoopbackAddress != true) { + Log.w(TAG, "Rejected non-loopback connection from ${socket.inetAddress}") + try { + socket.close() + } catch (_: Exception) { + } + continue + } + try { + if (Log.isLoggable(TAG, Log.DEBUG)) { + Log.d( + TAG, + "accepted a connection; workers busy=${clientExecutor.activeCount} " + + "queued=${clientExecutor.queue.size}", + ) + } + clientExecutor.execute { handleClient(socket) } + } catch (_: RejectedExecutionException) { + // Saturated: shed the connection; the map SDK will retry the tile. + val shed = shedConnections.incrementAndGet() + Log.w( + TAG, + "Shed connection (pool saturated) total=$shed " + + "active=${clientExecutor.activeCount} queued=${clientExecutor.queue.size}", + ) + try { + socket.close() + } catch (_: Exception) { + } + } + } + } + + private fun handleClient(socket: Socket) { + socket.use { client -> + try { + client.soTimeout = SOCKET_TIMEOUT_MS + // Unbuffered on purpose: the liveness check reads a byte from + // here, and a buffer between the two would hide it. + val peek = java.io.PushbackInputStream(client.getInputStream(), 1) + val reader = BufferedReader(InputStreamReader(peek)) + var handled = 0 + while (handled < MAX_KEEP_ALIVE_REQUESTS) { + // Idle keep-alive clients must not occupy all request + // handlers while newer tiles wait in the connection queue. + client.soTimeout = if (handled == 0) SOCKET_TIMEOUT_MS else KEEP_ALIVE_IDLE_TIMEOUT_MS + val request = readRequest(reader) ?: break + if (!request.valid) { + writeResponse(client, "400 Bad Request", "text/plain", "Bad request".toByteArray()) + break + } + + val startNs = System.nanoTime() + val method = request.method + val path = request.path.substringBefore('?').trim('/') + val keepAlive = shouldKeepAlive(request) + Log.d("Server", "---->$path") + + if (method != "GET") { + writeResponse( + client, + "405 Method Not Allowed", + "text/plain", + "Method not allowed".toByteArray(), + keepAlive = false, + extraHeaders = mapOf("Allow" to "GET", "Cache-Control" to "no-store"), + ) + break + } + + if (path.startsWith("$DOCS_PREFIX/")) { + val document = documents[path.removePrefix("$DOCS_PREFIX/")] + val ok = + if (document == null) { + writeResponse( + client, + "404 Not Found", + "text/plain", + "Not found".toByteArray(), + keepAlive = keepAlive, + extraHeaders = cacheHeaders(NO_STORE_CACHE_CONTROL), + ) + } else { + writeResponse( + client, + "200 OK", + document.contentType, + document.body, + keepAlive = keepAlive, + extraHeaders = cacheHeaders(NO_STORE_CACHE_CONTROL), + ) + } + if (!ok) break + handled += 1 + if (!keepAlive) break + continue + } + + if (path.startsWith("$FILES_PREFIX/")) { + val ok = serveFile(client, path.removePrefix("$FILES_PREFIX/"), keepAlive) + if (!ok) break + handled += 1 + if (!keepAlive) break + continue + } + + // The map may have moved on since this request was + // queued -- a pinch or a fling abandons whole screens of + // tiles -- and drawing one it no longer wants puts it in + // front of the tiles it does. Rendering is where the time + // goes, so the cheapest thing that helps is not starting. + if (clientGone(client, peek)) { + val total = abandoned.incrementAndGet() + if (Log.isLoggable(TAG, Log.DEBUG)) { + Log.d(TAG, "Gone before we started: $path (total=$total)") + } + break + } + + // Renderers check cancellation every few hundred shapes. + // A socket read per check turns 72万 circles into seconds + // of timeout waits. Poll the connection by elapsed time. + var lastProbeNs = System.nanoTime() + val cancelled = { + if (Thread.currentThread().isInterrupted || client.isClosed) true + else { + val now = System.nanoTime() + if (now - lastProbeNs < CANCELLATION_POLL_NS) false + else { lastProbeNs = now; clientGone(client, peek) } + } + } + val outcome = resolveTile(path, cancelled) + // A tile that was abandoned mid-render comes back from the + // provider looking empty, and the difference matters: an + // "empty" answer is a picture the map would cache. Nothing + // is answered at all -- the connection simply ends, which + // the map reads as a failure it may retry. + val fromProvider = outcome is TileOutcome.Empty || outcome is TileOutcome.Failed + if (fromProvider && clientGone(client, peek)) { + val total = abandoned.incrementAndGet() + if (Log.isLoggable(TAG, Log.DEBUG)) { + Log.d(TAG, "Abandoned mid-render, no answer sent: $path (total=$total)") + } + break + } + val status: String + val contentType: String + val body: ByteArray + val headers: Map + when (outcome) { + TileOutcome.NotFound -> { + status = "404 Not Found" + contentType = "text/plain" + body = "Not found".toByteArray() + headers = cacheHeaders(NO_STORE_CACHE_CONTROL) + } + TileOutcome.Failed -> { + // 503: the map will retry. If these repeat for the + // same path, the provider is the place to look. + status = "503 Service Unavailable" + contentType = "text/plain" + body = "Tile render failed".toByteArray() + headers = cacheHeaders(NO_STORE_CACHE_CONTROL) + ("Retry-After" to "1") + } + is TileOutcome.Empty -> { + status = "200 OK" + contentType = "image/png" + body = TransparentTilePng.bytes(outcome.pixelSize) + headers = cacheHeaders(outcome.cacheControl) + } + is TileOutcome.Tile -> { + status = "200 OK" + contentType = "image/png" + body = outcome.body + headers = cacheHeaders(outcome.cacheControl) + } + } + + val ok = + writeResponse( + client, + status, + contentType, + body, + keepAlive = keepAlive, + extraHeaders = headers, + ) + + val tookMs = (System.nanoTime() - startNs) / 1_000_000 + if (!ok) { + Log.w(TAG, "Write failed (client canceled?) status=$status path=${request.path}") + break + } + if (tookMs >= SLOW_RESPONSE_WARN_MS) { + val key = parseTileKey(path) + if (key != null) { + Log.w( + TAG, + "Slow tile response took=${tookMs}ms route=${key.routeId} " + + "tileSize=${key.tileSize} z=${key.z} x=${key.x} y=${key.y} status=$status", + ) + } else { + Log.w(TAG, "Slow response took=${tookMs}ms status=$status path=${request.path}") + } + } + + handled += 1 + if (!keepAlive) { + break + } + } + } catch (_: Exception) { + // Ignore per-connection errors to avoid crashing the server. + } + } + } + + private fun readRequest(reader: BufferedReader): Request? { + var requestLine: String? = null + + // prevent too big header + var headerLineCnt = 30 + while (requestLine == null && headerLineCnt > 0) { + val line = readLineBounded(reader) ?: return null + if (line.isNotEmpty()) { + requestLine = line + } + headerLineCnt-- + } + if (requestLine == null) return null + + val parts = requestLine.split(" ") + val valid = parts.size >= 2 + val method = parts.getOrNull(0) ?: "" + val path = parts.getOrNull(1) ?: "" + val httpVersion = parts.getOrNull(2) ?: "HTTP/1.0" + + val headers = HashMap() + var remainingHeaders = MAX_HEADER_COUNT + while (remainingHeaders > 0) { + remainingHeaders-- + val line = readLineBounded(reader) ?: break + if (line.isEmpty()) { + break + } + val index = line.indexOf(':') + if (index <= 0) continue + val key = line.substring(0, index).trim().lowercase() + val value = line.substring(index + 1).trim() + headers[key] = value + } + + val req = + Request( + method = method, + path = path, + httpVersion = httpVersion, + headers = headers, + valid = valid, + ) + return req + } + + /** + * Reads one CRLF/LF-terminated line, giving up (null) if it exceeds + * [MAX_LINE_LENGTH] — unlike BufferedReader.readLine(), which buffers an + * arbitrarily long line in memory. + */ + private fun readLineBounded(reader: BufferedReader): String? { + val sb = StringBuilder() + while (true) { + val ch = reader.read() + if (ch == -1) { + return if (sb.isEmpty()) null else sb.toString() + } + when (ch.toChar()) { + '\n' -> return sb.toString() + '\r' -> { + // Swallow the CR; the LF (if any) terminates on the next read. + } + else -> { + if (sb.length >= MAX_LINE_LENGTH) return null + sb.append(ch.toChar()) + } + } + } + } + + private fun shouldKeepAlive(request: Request): Boolean { + val connection = request.headers["connection"]?.lowercase() + return when (request.httpVersion) { + "HTTP/1.1" -> connection != "close" + "HTTP/1.0" -> connection == "keep-alive" + else -> false + } + } + + /** + * Whether the other end has gone away. + * + * There is no portable way to ask a socket whether the peer is still + * there, so this asks the only question a socket does answer: is there + * anything to read. A closed connection reads end-of-stream at once; a + * live idle one times out, which is the answer we want. + * + * The first version sent a byte of urgent data instead, which fails on a + * dead connection and is discarded by any client that does not ask for it. + * That is true of every HTTP client, and it is still a byte pushed into a + * live connection at a moment of its choosing -- a poor thing to do to a + * stream we also have to parse. Reading cannot corrupt anything, and the + * byte is pushed back for the parser when there is one. + */ + private fun clientGone( + client: Socket, + peek: java.io.PushbackInputStream, + ): Boolean { + if (client.isClosed || !client.isConnected) return true + val timeout = runCatching { client.soTimeout }.getOrDefault(SOCKET_TIMEOUT_MS) + return try { + client.soTimeout = 1 + val byte = peek.read() + if (byte == -1) { + true + } else { + // A pipelined request, which is the parser's business. + peek.unread(byte) + false + } + } catch (_: java.net.SocketTimeoutException) { + false + } catch (_: java.io.IOException) { + true + } finally { + runCatching { client.soTimeout = timeout } + } + } + + private fun resolveTile( + path: String, + isCancelled: () -> Boolean, + ): TileOutcome { + val key = parseTileKey(path) ?: return TileOutcome.NotFound + val routeId = key.routeId + val z = key.z + val x = key.x + val y = key.y + + if (loggedRoutes.add(routeId)) { + Log.d("LocalTileServer", "First tile request route=$routeId tileSize=${key.tileSize} z=$z x=$x y=$y") + } + + val provider = providers[routeId] ?: return TileOutcome.NotFound + levelGates[routeId]?.let { gate -> + if (gate(z)) return TileOutcome.Empty(key.tileSize * key.pixelRatio, NO_STORE_CACHE_CONTROL) + } + val cacheControl = + if (forceNoStoreCache) { + NO_STORE_CACHE_CONTROL + } else { + LONG_CACHE_CONTROL + } + val bytes = + try { + // Connection handling and idle sockets are separate from the + // memory-intensive bitmap/PNG work. Keep only two renders live. + while (!renderPermits.tryAcquire(16, TimeUnit.MILLISECONDS)) { + if (isCancelled()) return TileOutcome.Failed + } + try { + if (isCancelled()) return TileOutcome.Failed + provider.renderTile( + TileRequest(x = x, y = y, z = z, pixelRatio = key.pixelRatio), + isCancelled, + ) + } finally { renderPermits.release() } + } catch (error: Exception) { + Log.w(TAG, "Tile render failed route=$routeId z=$z x=$x y=$y", error) + return TileOutcome.Failed + } ?: return TileOutcome.Empty(key.tileSize * key.pixelRatio, cacheControl) + return TileOutcome.Tile(bytes, cacheControl) + } + + private fun parseTileKey(path: String): TileKey? { + if (path.isEmpty()) return null + val segments = path.split("/").filter { it.isNotEmpty() } + if (segments.size < 6 || segments[0] != "tiles") return null + val routeId = segments[1] + val tileSize = segments[2].toIntOrNull() ?: return null + val withCacheKey = segments.size >= 7 + val zIndex = if (withCacheKey) 4 else 3 + val xIndex = if (withCacheKey) 5 else 4 + val yIndex = if (withCacheKey) 6 else 5 + val z = segments.getOrNull(zIndex)?.toIntOrNull() ?: return null + val x = segments.getOrNull(xIndex)?.toIntOrNull() ?: return null + val tileCoordinate = segments.getOrNull(yIndex)?.let(::parseTileCoordinate) ?: return null + return TileKey( + routeId = routeId, + tileSize = tileSize, + z = z, + x = x, + y = tileCoordinate.y, + pixelRatio = tileCoordinate.pixelRatio, + ) + } + + /** `/` under the files prefix. */ + private fun serveFile( + client: Socket, + routePath: String, + keepAlive: Boolean, + ): Boolean { + val routeId = routePath.substringBefore('/') + val relative = + runCatching { java.net.URLDecoder.decode(routePath.substringAfter('/', ""), "UTF-8") } + .getOrDefault("") + val route = fileRoutes[routeId] + // No escaping the directory, whatever the request says. + val safe = relative.isNotEmpty() && relative.split('/').none { it == ".." || it.isEmpty() } + val file = if (route != null && safe) java.io.File(route.directory, relative) else null + if (file != null && file.isFile) { + return writeResponse( + client, + "200 OK", + contentTypeFor(relative), + file.readBytes(), + keepAlive = keepAlive, + extraHeaders = cacheHeaders(LONG_CACHE_CONTROL), + ) + } + val fetched = + if (route?.fallback != null && safe) { + runCatching { route.fallback.invoke(relative) } + .onFailure { Log.w(TAG, "file fallback failed: $relative", it) } + .getOrNull() + } else { + null + } + return if (fetched != null) { + writeResponse( + client, + "200 OK", + contentTypeFor(relative), + fetched, + keepAlive = keepAlive, + extraHeaders = cacheHeaders(NO_STORE_CACHE_CONTROL), + ) + } else { + writeResponse( + client, + "404 Not Found", + "text/plain", + "Not found".toByteArray(), + keepAlive = keepAlive, + extraHeaders = cacheHeaders(NO_STORE_CACHE_CONTROL), + ) + } + } + + private fun contentTypeFor(path: String): String = + when (path.substringAfterLast('.', "").lowercase()) { + "mvt" -> "application/vnd.mapbox-vector-tile" + "pbf" -> "application/x-protobuf" + "json" -> "application/json" + "png" -> "image/png" + else -> "application/octet-stream" + } + + private fun cacheHeaders(cacheControl: String): Map = + mapOf( + "Cache-Control" to cacheControl, + "Pragma" to "no-cache", + "Expires" to "0", + ) + + private fun writeResponse( + client: Socket, + status: String, + contentType: String, + body: ByteArray, + keepAlive: Boolean = false, + extraHeaders: Map = emptyMap(), + ): Boolean { + try { + val output = client.getOutputStream() + val headers = StringBuilder() + headers.append("HTTP/1.1 ").append(status).append("\r\n") + headers.append("Content-Type: ").append(contentType).append("\r\n") + headers.append("Content-Length: ").append(body.size).append("\r\n") + headers.append("Connection: ").append(if (keepAlive) "keep-alive" else "close").append("\r\n") + // WebView ベースの地図 SDK(Longdo / MapTiler 等)は MapLibre GL JS の fetch でタイルを取得する。 + // ローカルサーバは https のページから見て別オリジンのため、CORS を許可しないと取得がブロックされる。 + headers.append("Access-Control-Allow-Origin: *\r\n") + for ((key, value) in extraHeaders) { + headers + .append(key) + .append(": ") + .append(value) + .append("\r\n") + } + headers.append("\r\n") + output.write(headers.toString().toByteArray()) + output.write(body) + output.flush() + return true + } catch (_: Exception) { + // Client closed the connection early or canceled; ignore. + return false + } + } + + private data class Request( + val method: String, + val path: String, + val httpVersion: String, + val headers: Map, + val valid: Boolean, + ) + + /** + * What a request resolved to. The distinctions matter because map SDKs + * remember the answers differently: 404 is taken as permanent, so it is + * reserved for requests that name nothing — a bad path, an unregistered + * route. A provider with nothing to draw gets a transparent picture (an + * empty spot is a real answer, cacheable and later replaced when the data + * version moves the URL), and a provider that threw gets a 503 the map + * knows to retry. + */ + private sealed interface TileOutcome { + class Tile( + val body: ByteArray, + val cacheControl: String, + ) : TileOutcome + + class Empty( + val pixelSize: Int, + val cacheControl: String, + ) : TileOutcome + + object NotFound : TileOutcome + + object Failed : TileOutcome + } + + private class Document( + val contentType: String, + val body: ByteArray, + ) + + private class FileRoute( + val directory: java.io.File, + val fallback: ((String) -> ByteArray?)?, + ) + + private data class TileKey( + val routeId: String, + val tileSize: Int, + val z: Int, + val x: Int, + val y: Int, + val pixelRatio: Int, + ) + + companion object { + private const val TAG = "LocalTileServer" + private const val DOCS_PREFIX = "docs" + private const val FILES_PREFIX = "files" + private const val MAX_KEEP_ALIVE_REQUESTS = 200 + private const val SOCKET_TIMEOUT_MS = 5000 + private const val KEEP_ALIVE_IDLE_TIMEOUT_MS = 250 + private const val CANCELLATION_POLL_NS = 50_000_000L + private const val MAX_CONCURRENT_RENDERS = 2 + private const val MAX_HEADER_COUNT = 64 + private const val MAX_LINE_LENGTH = 8192 + + // Serve independent connections without letting idle keep-alives block + // the viewport. Bitmap/PNG concurrency is limited separately above. + private const val MAX_WORKER_THREADS = 8 + private const val MAX_QUEUED_CONNECTIONS = 256 + private const val WORKER_KEEP_ALIVE_SECONDS = 60L + private const val LONG_CACHE_CONTROL = "public, max-age=31536000, immutable" + private const val NO_STORE_CACHE_CONTROL = "no-store, no-cache, must-revalidate, max-age=0" + private const val SLOW_RESPONSE_WARN_MS = 250L + private const val HTTP_PORT = 0 + private const val HTTP_SERVER_BACKLOG = 100 + + fun startServer(forceNoStoreCache: Boolean = false): LocalTileServer { + // Bind to the wildcard address (dual-stack) so clients can reach the + // server via either 127.0.0.1 or ::1 — binding to a single loopback + // address breaks HTTP stacks that resolve localhost to the other IP + // family (e.g. Mapbox). Device-internal access is enforced in + // acceptLoop by rejecting non-loopback source addresses. + val socket = ServerSocket(HTTP_PORT, HTTP_SERVER_BACKLOG) + val server = LocalTileServer(socket, forceNoStoreCache = forceNoStoreCache) + server.start() + return server + } + } +} + +internal data class TileCoordinate( + val y: Int, + val pixelRatio: Int, +) + +internal fun parseTileCoordinate(fileName: String): TileCoordinate? { + val match = TILE_FILE_NAME_PATTERN.matchEntire(fileName) ?: return null + val y = match.groupValues[1].toIntOrNull() ?: return null + val pixelRatio = match.groupValues[2].toIntOrNull() ?: 1 + if (pixelRatio !in 1..MAX_TILE_PIXEL_RATIO) return null + return TileCoordinate(y = y, pixelRatio = pixelRatio) +} + +private val TILE_FILE_NAME_PATTERN = Regex("""^(\d+)(?:@(\d+)x)?\.png$""") +private const val MAX_TILE_PIXEL_RATIO = 3 diff --git a/src/main/java/com/mapconductor/core/tileserver/ScratchPool.kt b/src/main/java/com/mapconductor/core/tileserver/ScratchPool.kt new file mode 100644 index 0000000..dcfd778 --- /dev/null +++ b/src/main/java/com/mapconductor/core/tileserver/ScratchPool.kt @@ -0,0 +1,49 @@ +package com.mapconductor.core.tileserver + +/** + * A few reusable scratch objects (pixel buffers, bitmaps, output streams) for + * code that renders tiles on threads it does not own. + * + * Use this instead of a `ThreadLocal`. Tile callbacks run on the map SDK's + * threads, and some SDKs start new ones for every map and never stop them: + * Google Maps keeps an `androidmapsapi-tileoverlay` pool of three live threads + * per map it ever created. A thread-local scratch pins one object on each such + * thread for good, so every map switch added a few megabytes that nothing + * could free. A pool holds at most [capacity] objects whatever the threads do. + * + * [acquire] hands out a pooled object or null (the caller makes a fresh one); + * [release] takes it back, or drops it when the pool is full. + */ +internal class ScratchPool( + private val capacity: Int = DEFAULT_CAPACITY, +) { + private val items = ArrayDeque(capacity) + + /** A pooled object that [accept] takes, or null. Others are dropped. */ + fun acquire(accept: (T) -> Boolean = { true }): T? { + synchronized(items) { + while (items.isNotEmpty()) { + val item = items.removeLast() + if (accept(item)) return item + } + } + return null + } + + /** Returns [item]. False if the pool was full and did not keep it. */ + fun release(item: T): Boolean = + synchronized(items) { + if (items.size >= capacity) return false + items.addLast(item) + true + } + + /** Pooled objects right now. For tests. */ + val size: Int + get() = synchronized(items) { items.size } + + companion object { + /** About how many tiles are drawn at the same time. */ + val DEFAULT_CAPACITY: Int = Runtime.getRuntime().availableProcessors().coerceIn(2, 8) + } +} diff --git a/src/main/java/com/mapconductor/core/tileserver/TilePngEncoder.kt b/src/main/java/com/mapconductor/core/tileserver/TilePngEncoder.kt new file mode 100644 index 0000000..4bea4ca --- /dev/null +++ b/src/main/java/com/mapconductor/core/tileserver/TilePngEncoder.kt @@ -0,0 +1,108 @@ +package com.mapconductor.core.tileserver + +import java.nio.ByteBuffer +import java.nio.ByteOrder +import android.graphics.Bitmap + +/** + * PNG encoding in Rust, for tiles the SDK rasterises itself. + * + * Worth having because the platform encoders vary enormously: on a Pixel 5a + * `Bitmap.compress` spends 133-165 ms on a tile this encodes in 7-14 ms. The + * tiles are ephemeral payloads for a local tile server, so it trades ratio for + * speed and produces files roughly 2-3x larger — which never reach a network, + * though they do take proportionally more room in a tile cache. + * + * Lives in the core so there is one copy of the encoder in an app rather than + * one per module that draws tiles. + * + * Every failure path returns null rather than throwing. A device whose ABI is + * not in the library, a bitmap in an unexpected format, a panic in Rust: all of + * them should mean a slower tile, never a broken one, so every caller is + * expected to have a platform fallback. + */ +object TilePngEncoder { + /** + * Scratch pixel buffers, shared by the calling threads. + * + * Tile rendering runs concurrently across several threads, and a tile at + * this SDK's densities is around 7 MB of RGBA — allocating that per call + * would cost more than the encoding it is meant to speed up. Not one per + * thread: the callers include map SDK threads that outlive their map (see + * [ScratchPool]), and each would keep its buffer for good. + */ + private val scratch = ScratchPool() + + /** False where the native library is missing for this device's ABI. */ + val isAvailable: Boolean = + try { + System.loadLibrary("tile_png_jni") + true + } catch (error: UnsatisfiedLinkError) { + false + } + + /** + * Encodes a bitmap. Returns null if the native path is unavailable or + * declined the input, in which case use `Bitmap.compress`. + */ + fun encode(bitmap: Bitmap): ByteArray? { + if (!isAvailable) return null + // Any other config has a different byte layout, and guessing at one is + // how a fast encoder produces wrong colours. + if (bitmap.config != Bitmap.Config.ARGB_8888) return null + + val width = bitmap.width + val height = bitmap.height + if (width <= 0 || height <= 0) return null + val needed = width * height * 4 + + val buffer = + scratch.acquire { it.capacity() >= needed } + ?: ByteBuffer.allocateDirect(needed).order(ByteOrder.nativeOrder()) + try { + buffer.clear() + bitmap.copyPixelsToBuffer(buffer) + buffer.rewind() + return encode(buffer, width, height, premultiplied = bitmap.isPremultiplied) + } finally { + scratch.release(buffer) + } + } + + /** + * Encodes RGBA8 pixels from a **direct** buffer, whose pointer crosses JNI + * without a copy. + * + * Set [premultiplied] when the colour channels are scaled by alpha — an + * `ARGB_8888` bitmap's are, a `glReadPixels` result's usually are not. PNG + * stores straight alpha, so encoding premultiplied pixels unchanged darkens + * every partly transparent one. The buffer is un-premultiplied in place + * when this is set, so its contents are not reusable afterwards. + */ + fun encode( + buffer: ByteBuffer, + width: Int, + height: Int, + premultiplied: Boolean, + ): ByteArray? { + if (!isAvailable) return null + if (width <= 0 || height <= 0) return null + if (!buffer.isDirect) return null + if (buffer.capacity() < width * height * 4) return null + + return try { + nativeEncode(buffer, width, height, premultiplied) + } catch (error: UnsatisfiedLinkError) { + null + } + } + + @JvmStatic + private external fun nativeEncode( + buffer: ByteBuffer, + width: Int, + height: Int, + premultiplied: Boolean, + ): ByteArray? +} diff --git a/src/main/java/com/mapconductor/core/tileserver/TileProviderInterface.kt b/src/main/java/com/mapconductor/core/tileserver/TileProviderInterface.kt index 9bef60d..347f623 100644 --- a/src/main/java/com/mapconductor/core/tileserver/TileProviderInterface.kt +++ b/src/main/java/com/mapconductor/core/tileserver/TileProviderInterface.kt @@ -1,5 +1,30 @@ package com.mapconductor.core.tileserver interface TileProviderInterface { + /** + * Draws one tile, or returns null when there is nothing to draw there. + * + * Null is "this spot is empty", and the server answers it with a + * transparent tile — not a 404, which map SDKs remember as permanent. A + * render that cannot be completed right now should throw instead; the + * server turns that into a 503 the map knows to retry. + */ fun renderTile(request: TileRequest): ByteArray? + + /** + * Renders a tile, giving up if the map stops wanting it. + * + * The map asks for tiles it may abandon a moment later: a pinch or a fling + * changes which ones matter while the old ones are still being drawn, and + * it closes those connections. Without somewhere to notice that, a + * provider draws every tile it was ever asked for and the ones still on + * screen wait their turn behind them. + * + * [isCancelled] is cheap to call and safe to ignore -- the default does, + * so a provider that renders quickly needs no changes. + */ + fun renderTile( + request: TileRequest, + isCancelled: () -> Boolean, + ): ByteArray? = renderTile(request) } diff --git a/src/main/java/com/mapconductor/core/tileserver/TransparentTilePng.kt b/src/main/java/com/mapconductor/core/tileserver/TransparentTilePng.kt new file mode 100644 index 0000000..b1cc465 --- /dev/null +++ b/src/main/java/com/mapconductor/core/tileserver/TransparentTilePng.kt @@ -0,0 +1,94 @@ +package com.mapconductor.core.tileserver + +import java.io.ByteArrayOutputStream +import java.util.zip.CRC32 +import java.util.zip.Deflater + +/** + * A fully transparent tile, encoded once per pixel size and reused. + * + * This is what the server answers when a provider has nothing to draw. "No + * markers here" and "no such tile" are different answers, and map SDKs + * remember them differently: a 404 is taken as permanent, so a tile that was + * empty for a moment — data still loading, a layer mid-switch — leaves a hole + * that is never asked about again, with the neighbouring tiles' overhang cut + * off at its edge. A transparent picture is the truthful answer, and it costs + * a few hundred bytes once. + * + * Written by hand rather than through [android.graphics.Bitmap] so it does not + * allocate a bitmap it never draws into, and so plain JVM tests can decode it. + */ +internal object TransparentTilePng { + private val cache = HashMap() + + fun bytes(size: Int): ByteArray { + val clamped = size.coerceIn(1, MAX_SIZE) + synchronized(cache) { + return cache.getOrPut(clamped) { encode(clamped) } + } + } + + private fun encode(size: Int): ByteArray { + val out = ByteArrayOutputStream() + out.write(byteArrayOf(0x89.toByte(), 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A)) + + val ihdr = ByteArray(13) + writeIntBE(ihdr, 0, size) + writeIntBE(ihdr, 4, size) + ihdr[8] = 8 // bit depth + ihdr[9] = 6 // colour type: RGBA + writeChunk(out, "IHDR", ihdr) + + // Each row is a zero filter byte followed by RGBA pixels, all zero — + // which is exactly what a fresh ByteArray is. + val raw = ByteArray(size * (1 + size * 4)) + val deflater = Deflater(Deflater.BEST_SPEED) + deflater.setInput(raw) + deflater.finish() + val idat = ByteArrayOutputStream() + val buffer = ByteArray(64 * 1024) + while (!deflater.finished()) { + val n = deflater.deflate(buffer) + idat.write(buffer, 0, n) + } + deflater.end() + writeChunk(out, "IDAT", idat.toByteArray()) + + writeChunk(out, "IEND", ByteArray(0)) + return out.toByteArray() + } + + private fun writeChunk( + out: ByteArrayOutputStream, + type: String, + data: ByteArray, + ) { + val length = ByteArray(4) + writeIntBE(length, 0, data.size) + out.write(length) + val typeBytes = type.toByteArray(Charsets.US_ASCII) + out.write(typeBytes) + out.write(data) + val crc = CRC32() + crc.update(typeBytes) + crc.update(data) + val crcBytes = ByteArray(4) + writeIntBE(crcBytes, 0, crc.value.toInt()) + out.write(crcBytes) + } + + private fun writeIntBE( + target: ByteArray, + at: Int, + value: Int, + ) { + target[at] = (value ushr 24).toByte() + target[at + 1] = (value ushr 16).toByte() + target[at + 2] = (value ushr 8).toByte() + target[at + 3] = value.toByte() + } + + // Big enough for a 4096px tile; anything larger is a corrupt request, and + // the row buffer above is quadratic in this. + private const val MAX_SIZE = 4096 +} diff --git a/src/main/jniLibs/arm64-v8a/libtile_png_jni.so b/src/main/jniLibs/arm64-v8a/libtile_png_jni.so new file mode 100755 index 0000000..82864d5 Binary files /dev/null and b/src/main/jniLibs/arm64-v8a/libtile_png_jni.so differ diff --git a/src/main/jniLibs/armeabi-v7a/libtile_png_jni.so b/src/main/jniLibs/armeabi-v7a/libtile_png_jni.so new file mode 100755 index 0000000..76bd3cd Binary files /dev/null and b/src/main/jniLibs/armeabi-v7a/libtile_png_jni.so differ diff --git a/src/main/jniLibs/x86_64/libtile_png_jni.so b/src/main/jniLibs/x86_64/libtile_png_jni.so new file mode 100755 index 0000000..f77b5ac Binary files /dev/null and b/src/main/jniLibs/x86_64/libtile_png_jni.so differ diff --git a/src/test/java/com/mapconductor/core/OverlayClearOrderTest.kt b/src/test/java/com/mapconductor/core/OverlayClearOrderTest.kt new file mode 100644 index 0000000..f26fed2 --- /dev/null +++ b/src/test/java/com/mapconductor/core/OverlayClearOrderTest.kt @@ -0,0 +1,302 @@ +package com.mapconductor.core + +import com.mapconductor.core.circle.CircleController +import com.mapconductor.core.circle.CircleEntityInterface +import com.mapconductor.core.circle.CircleManager +import com.mapconductor.core.circle.CircleOverlayRendererInterface +import com.mapconductor.core.circle.CircleState +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.features.GeoRectBounds +import com.mapconductor.core.groundimage.GroundImageController +import com.mapconductor.core.groundimage.GroundImageEntityInterface +import com.mapconductor.core.groundimage.GroundImageManager +import com.mapconductor.core.groundimage.GroundImageOverlayRendererInterface +import com.mapconductor.core.groundimage.GroundImageState +import com.mapconductor.core.map.MapViewHolderInterface +import com.mapconductor.core.marker.AbstractMarkerController +import com.mapconductor.core.marker.MarkerEntity +import com.mapconductor.core.marker.MarkerEntityInterface +import com.mapconductor.core.marker.MarkerManager +import com.mapconductor.core.marker.MarkerOverlayRendererInterface +import com.mapconductor.core.marker.MarkerState +import com.mapconductor.core.marker.OnMarkerEventHandler +import com.mapconductor.core.polygon.PolygonController +import com.mapconductor.core.polygon.PolygonEntityInterface +import com.mapconductor.core.polygon.PolygonManager +import com.mapconductor.core.polygon.PolygonOverlayRendererInterface +import com.mapconductor.core.polygon.PolygonState +import com.mapconductor.core.polyline.PolylineController +import com.mapconductor.core.polyline.PolylineEntityInterface +import com.mapconductor.core.polyline.PolylineManager +import com.mapconductor.core.polyline.PolylineOverlayRendererInterface +import com.mapconductor.core.polyline.PolylineState +import com.mapconductor.core.raster.RasterLayerController +import com.mapconductor.core.raster.RasterLayerEntityInterface +import com.mapconductor.core.raster.RasterLayerManager +import com.mapconductor.core.raster.RasterLayerOverlayRendererInterface +import com.mapconductor.core.raster.RasterLayerSource +import com.mapconductor.core.raster.RasterLayerState +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.runTest +import org.junit.Assert.assertEquals +import org.junit.Test + +/** + * clear() の後、地図に何も残らないこと。 + * + * MapLibre / Mapbox / Mappls / OMM などの GL 系の描画担当は、remove では何もせず、 + * onPostProcess で manager の全部を描き直す。ここの偽レンダラも同じ作りにしてあり、 + * `drawn` は最後の onPostProcess で描いたもの(=地図に見えているもの)を表す。 + * + * clear() が manager を空にする前に onPostProcess を呼ぶと、全部を描き直して残る。 + * 呼ばなければ、前に描いたものが残る。 + */ +class OverlayClearOrderTest { + private val a = GeoPoint(35.0, 139.0) + private val b = GeoPoint(35.1, 139.1) + private val c = GeoPoint(35.0, 139.1) + + /** GL 系の描画担当の作り: onPostProcess で [all] の全部を描き直す。 */ + private class Drawn( + private val all: () -> List, + ) { + var ids: List = emptyList() + private set + + fun redraw() { + ids = all().sorted() + } + } + + // ── Polygon ───────────────────────────────────────────────────────── + + private class PolygonGl( + manager: PolygonManager, + ) : PolygonOverlayRendererInterface { + val drawn = Drawn { manager.allEntities().map { it.state.id } } + + override suspend fun onAdd(data: List) = data.map { it.state.id } + + override suspend fun onChange(data: List>) = + data.map { it.current.state.id } + + override suspend fun onRemove(data: List>) = Unit + + override suspend fun onPostProcess() = drawn.redraw() + } + + @Test + fun `polygon の clear 後は何も描かれていない`() = + runTest { + val manager = PolygonManager() + val renderer = PolygonGl(manager) + val controller = object : PolygonController(manager, renderer) {} + controller.add(listOf(PolygonState(points = listOf(a, b, c), id = "p1"), PolygonState(points = listOf(a, b, c), id = "p2"))) + assertEquals(listOf("p1", "p2"), renderer.drawn.ids) + + controller.clear() + + assertEquals(emptyList(), renderer.drawn.ids) + } + + // ── Polyline ──────────────────────────────────────────────────────── + + private class PolylineGl( + manager: PolylineManager, + ) : PolylineOverlayRendererInterface { + val drawn = Drawn { manager.allEntities().map { it.state.id } } + + override suspend fun onAdd(data: List) = data.map { it.state.id } + + override suspend fun onChange(data: List>) = + data.map { it.current.state.id } + + override suspend fun onRemove(data: List>) = Unit + + override suspend fun onPostProcess() = drawn.redraw() + } + + @Test + fun `polyline の clear 後は何も描かれていない`() = + runTest { + val manager = PolylineManager() + val renderer = PolylineGl(manager) + val controller = object : PolylineController(manager, renderer) {} + controller.add(listOf(PolylineState(points = listOf(a, b), id = "l1"), PolylineState(points = listOf(b, c), id = "l2"))) + assertEquals(listOf("l1", "l2"), renderer.drawn.ids) + + controller.clear() + + assertEquals(emptyList(), renderer.drawn.ids) + } + + // ── Circle ────────────────────────────────────────────────────────── + + private class CircleGl( + manager: CircleManager, + ) : CircleOverlayRendererInterface { + val drawn = Drawn { manager.allEntities().map { it.state.id } } + + override suspend fun onAdd(data: List) = data.map { it.state.id } + + override suspend fun onChange(data: List>) = + data.map { it.current.state.id } + + override suspend fun onRemove(data: List>) = Unit + + override suspend fun onPostProcess() = drawn.redraw() + } + + @Test + fun `circle の clear 後は何も描かれていない`() = + runTest { + val manager = CircleManager() + val renderer = CircleGl(manager) + val controller = object : CircleController(manager, renderer) {} + controller.add( + listOf(CircleState(center = a, radiusMeters = 100.0, id = "c1"), CircleState(center = b, radiusMeters = 50.0, id = "c2")), + ) + assertEquals(listOf("c1", "c2"), renderer.drawn.ids) + + controller.clear() + + assertEquals(emptyList(), renderer.drawn.ids) + } + + // ── GroundImage ───────────────────────────────────────────────────── + + private class GroundImageGl( + manager: GroundImageManager, + ) : GroundImageOverlayRendererInterface { + val drawn = Drawn { manager.allEntities().map { it.state.id } } + + override suspend fun onAdd(data: List) = data.map { it.state.id } + + override suspend fun onChange(data: List>) = + data.map { it.current.state.id } + + override suspend fun onRemove(data: List>) = Unit + + override suspend fun onPostProcess() = drawn.redraw() + } + + /** GroundImageState は Drawable を要求するが、ここでは中身を使わない。 */ + private class FakeDrawable : android.graphics.drawable.Drawable() { + override fun draw(canvas: android.graphics.Canvas) = Unit + + override fun setAlpha(alpha: Int) = Unit + + override fun setColorFilter(colorFilter: android.graphics.ColorFilter?) = Unit + + @Deprecated("Deprecated in Java") + override fun getOpacity(): Int = android.graphics.PixelFormat.OPAQUE + } + + @Test + fun `groundImage の clear 後は何も描かれていない`() = + runTest { + val manager = GroundImageManager() + val renderer = GroundImageGl(manager) + val controller = object : GroundImageController(manager, renderer) {} + val bounds = + GeoRectBounds().apply { + extend(a) + extend(b) + } + controller.add( + listOf( + GroundImageState(bounds = bounds, image = FakeDrawable(), id = "g1"), + GroundImageState(bounds = bounds, image = FakeDrawable(), id = "g2"), + ), + ) + assertEquals(listOf("g1", "g2"), renderer.drawn.ids) + + controller.clear() + + assertEquals(emptyList(), renderer.drawn.ids) + } + + // ── RasterLayer ───────────────────────────────────────────────────── + + private class RasterGl( + manager: RasterLayerManager, + override val coroutine: CoroutineScope, + ) : RasterLayerOverlayRendererInterface { + val drawn = Drawn { manager.allEntities().map { it.state.id } } + + override suspend fun onAdd(data: List) = data.map { it.state.id } + + override suspend fun onChange(data: List>) = + data.map { it.current.state.id } + + override suspend fun onRemove(data: List>) = Unit + + override suspend fun onPostProcess() = drawn.redraw() + } + + @Test + fun `rasterLayer の clear 後は何も描かれていない`() = + runTest { + val manager = RasterLayerManager() + val renderer = RasterGl(manager, CoroutineScope(StandardTestDispatcher(testScheduler))) + val controller = object : RasterLayerController(manager, renderer) {} + controller.add( + listOf( + RasterLayerState(source = RasterLayerSource.UrlTemplate("https://example.com/a/{z}/{x}/{y}.png"), id = "r1"), + RasterLayerState(source = RasterLayerSource.UrlTemplate("https://example.com/b/{z}/{x}/{y}.png"), id = "r2"), + ), + ) + assertEquals(listOf("r1", "r2"), renderer.drawn.ids) + + controller.clear() + + assertEquals(emptyList(), renderer.drawn.ids) + } + + // ── Marker ────────────────────────────────────────────────────────── + + /** + * MapLibre / Mapbox / Mappls のマーカーの描画担当と同じ作り: onRemove はアイコンの参照数を + * 減らすだけで、地図のソースは onPostProcess が manager の中身から描き直す。 + */ + private class MarkerGl( + manager: MarkerManager, + ) : MarkerOverlayRendererInterface { + val drawn = Drawn { manager.allEntities().map { it.state.id } } + override var animateStartListener: OnMarkerEventHandler? = null + override var animateEndListener: OnMarkerEventHandler? = null + override val holder: MapViewHolderInterface<*, *> + get() = throw UnsupportedOperationException("not used") + + override suspend fun onAdd(data: List) = data.map { it.state.id } + + override suspend fun onChange(data: List>) = + data.map { it.current.state.id } + + override suspend fun onRemove(data: List>) = Unit + + override suspend fun onAnimate(entity: MarkerEntityInterface) = Unit + + override suspend fun onPostProcess() = drawn.redraw() + } + + @Test + fun `marker の clear 後は何も描かれていない`() = + runTest { + val manager = MarkerManager.defaultManager() + val renderer = MarkerGl(manager) + val controller = object : AbstractMarkerController(manager, renderer) {} + // add() は既定アイコン(Android の Bitmap)を焼くので素の JVM では呼べない。 + // 描かれた状態は manager へ直接登録して作る。 + listOf("m1", "m2").forEach { id -> + manager.registerEntity(MarkerEntity(marker = id, state = MarkerState(position = a, id = id), isRendered = true)) + } + renderer.onPostProcess() + assertEquals(listOf("m1", "m2"), renderer.drawn.ids) + + controller.clear() + + assertEquals(emptyList(), renderer.drawn.ids) + } +} diff --git a/src/test/java/com/mapconductor/core/OverlayCollectorMutationTest.kt b/src/test/java/com/mapconductor/core/OverlayCollectorMutationTest.kt new file mode 100644 index 0000000..08f4f40 --- /dev/null +++ b/src/test/java/com/mapconductor/core/OverlayCollectorMutationTest.kt @@ -0,0 +1,190 @@ +package com.mapconductor.core + +import androidx.compose.runtime.getValue +import androidx.compose.runtime.setValue +import org.junit.Assert.assertEquals +import org.junit.Test +import kotlin.time.Duration.Companion.milliseconds +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.TestDispatcher +import kotlinx.coroutines.test.advanceTimeBy +import kotlinx.coroutines.test.advanceUntilIdle +import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.test.runCurrent + +/** + * In-place changes to a collected state have to reach the update handler. + * + * The collector used to find them by reading every state's fingerprint inside a + * `snapshotFlow`, which cost the size of the collection on every snapshot + * commit anywhere in the app — 270 to 380 ms a frame during a drag with 144k + * markers. States now report their own writes. The failure mode of that swap is + * silent: a field whose setter forgets to report leaves the renderer drawing + * the old value, with nothing logged and nothing thrown. + */ +@OptIn(ExperimentalCoroutinesApi::class) +class OverlayCollectorMutationTest { + private class Thing( + override val id: String, + label: String, + ) : ComponentState { + override val mutations = StateMutationSignal() + var label: String by mutations.notifying(label) + } + + private val window = 5.milliseconds + + @Test + fun bulkRemovalStopsListeningAndReinsertionRestoresIt() = runTest { + val collector = collector(StandardTestDispatcher(testScheduler)) + val seen = mutableListOf() + collector.setUpdateHandler { seen.add(it.label) } + val state = Thing("bulk", "before") + collector.flow.value = copyOverlayStates(mapOf(state.id to state)) + advanceUntilIdle() + state.label = "visible" + advanceUntilIdle() + collector.flow.value = copyOverlayStates(emptyMap()) + advanceUntilIdle() + state.label = "hidden" + advanceUntilIdle() + collector.flow.value = copyOverlayStates(mapOf(state.id to state)) + advanceUntilIdle() + state.label = "restored" + advanceUntilIdle() + assertEquals(listOf("visible", "restored"), seen) + } + + @Test + fun bulkPublicationKeepsPendingDirectAddsListening() = runTest { + val collector = collector(StandardTestDispatcher(testScheduler)) + val seen = mutableListOf() + collector.setUpdateHandler { seen.add(it.id) } + val pending = Thing("single", "before") + val bulk = Thing("bulk", "before") + runCurrent() + collector.add(pending) + collector.flow.value = copyOverlayStates(mapOf(bulk.id to bulk)) + runCurrent() // Collect the bulk map before the direct add's debounce expires. + pending.label = "after" + advanceUntilIdle() + assertEquals(listOf("single"), seen) + assertEquals(setOf("single", "bulk"), collector.flow.value.keys) + } + + private fun collector(dispatcher: TestDispatcher) = + OverlayCollector( + updateDebounce = window, + scope = kotlinx.coroutines.CoroutineScope(dispatcher), + ) + + @Test + fun writingAFieldReachesTheHandler() = + runTest { + val dispatcher = StandardTestDispatcher(testScheduler) + val collector = collector(dispatcher) + val seen = mutableListOf() + collector.setUpdateHandler { seen.add(it.id) } + + val thing = Thing("a", "before") + collector.add(thing) + advanceUntilIdle() + + thing.label = "after" + advanceTimeBy(window.inWholeMilliseconds * 2) + advanceUntilIdle() + + assertEquals(listOf("a"), seen) + } + + /** Writing the same value is not a change, and the old diff ignored it too. */ + @Test + fun writingTheSameValueIsNotReported() = + runTest { + val dispatcher = StandardTestDispatcher(testScheduler) + val collector = collector(dispatcher) + val seen = mutableListOf() + collector.setUpdateHandler { seen.add(it.id) } + + val thing = Thing("a", "same") + collector.add(thing) + advanceUntilIdle() + + thing.label = "same" + advanceTimeBy(window.inWholeMilliseconds * 2) + advanceUntilIdle() + + assertEquals(emptyList(), seen) + } + + /** + * A state written several times inside one window is delivered once, with + * the latest value — the sampling the update channel has always promised. + */ + @Test + fun repeatedWritesInOneWindowAreDeliveredOnce() = + runTest { + val dispatcher = StandardTestDispatcher(testScheduler) + val collector = collector(dispatcher) + val seen = mutableListOf() + collector.setUpdateHandler { seen.add(it.label) } + + val thing = Thing("a", "0") + collector.add(thing) + advanceUntilIdle() + + thing.label = "1" + thing.label = "2" + thing.label = "3" + advanceTimeBy(window.inWholeMilliseconds * 2) + advanceUntilIdle() + + assertEquals(listOf("3"), seen) + } + + /** A removed state is nobody's business any more. */ + @Test + fun aRemovedStateStopsReporting() = + runTest { + val dispatcher = StandardTestDispatcher(testScheduler) + val collector = collector(dispatcher) + val seen = mutableListOf() + collector.setUpdateHandler { seen.add(it.id) } + + val thing = Thing("a", "before") + collector.add(thing) + advanceUntilIdle() + collector.remove("a") + advanceUntilIdle() + + thing.label = "after" + advanceTimeBy(window.inWholeMilliseconds * 2) + advanceUntilIdle() + + assertEquals(emptyList(), seen) + } + + /** Two states changing in the same window both arrive. */ + @Test + fun everyChangedStateIsDelivered() = + runTest { + val dispatcher = StandardTestDispatcher(testScheduler) + val collector = collector(dispatcher) + val seen = mutableListOf() + collector.setUpdateHandler { seen.add(it.id) } + + val a = Thing("a", "0") + val b = Thing("b", "0") + collector.add(a) + collector.add(b) + advanceUntilIdle() + + a.label = "1" + b.label = "1" + advanceTimeBy(window.inWholeMilliseconds * 2) + advanceUntilIdle() + + assertEquals(listOf("a", "b"), seen.sorted()) + } +} diff --git a/src/test/java/com/mapconductor/core/OverlayOnAddedTest.kt b/src/test/java/com/mapconductor/core/OverlayOnAddedTest.kt new file mode 100644 index 0000000..5c58c3d --- /dev/null +++ b/src/test/java/com/mapconductor/core/OverlayOnAddedTest.kt @@ -0,0 +1,434 @@ +package com.mapconductor.core + +import com.mapconductor.core.circle.CircleCapableInterface +import com.mapconductor.core.circle.CircleOverlay +import com.mapconductor.core.circle.CircleState +import com.mapconductor.core.circle.OnCircleEventHandler +import com.mapconductor.core.controller.MapViewControllerInterface +import com.mapconductor.core.controller.OverlayControllerInterface +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.features.GeoPointInterface +import com.mapconductor.core.features.GeoRectBounds +import com.mapconductor.core.groundimage.GroundImageCapableInterface +import com.mapconductor.core.groundimage.GroundImageOverlay +import com.mapconductor.core.groundimage.GroundImageState +import com.mapconductor.core.groundimage.OnGroundImageEventHandler +import com.mapconductor.core.map.MapCameraPosition +import com.mapconductor.core.map.MapViewHolderInterface +import com.mapconductor.core.marker.MarkerAnimationOverlayHost +import com.mapconductor.core.marker.MarkerCapableInterface +import com.mapconductor.core.marker.MarkerOverlay +import com.mapconductor.core.marker.MarkerState +import com.mapconductor.core.marker.OnMarkerEventHandler +import com.mapconductor.core.polygon.OnPolygonEventHandler +import com.mapconductor.core.polygon.PolygonCapableInterface +import com.mapconductor.core.polygon.PolygonController +import com.mapconductor.core.polygon.PolygonEntityInterface +import com.mapconductor.core.polygon.PolygonManager +import com.mapconductor.core.polygon.PolygonOverlay +import com.mapconductor.core.polygon.PolygonOverlayRendererInterface +import com.mapconductor.core.polygon.PolygonOverlayRendererInterface.AddParamsInterface +import com.mapconductor.core.polygon.PolygonOverlayRendererInterface.ChangeParamsInterface +import com.mapconductor.core.polygon.PolygonState +import com.mapconductor.core.polyline.OnPolylineEventHandler +import com.mapconductor.core.polyline.PolylineCapableInterface +import com.mapconductor.core.polyline.PolylineOverlay +import com.mapconductor.core.polyline.PolylineState +import com.mapconductor.core.raster.RasterLayerCapableInterface +import com.mapconductor.core.raster.RasterLayerOverlay +import com.mapconductor.core.raster.RasterLayerSource +import com.mapconductor.core.raster.RasterLayerState +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.runBlocking +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * `onAdded` of the overlay states. + * + * Driven the way a map drives it: the overlay hands its states to the + * controller (`compositionXxx`), and `onAdded` runs for the states the map now + * has that it did not have before. The polygon controller here is the real + * core one, so the native path (renderer.onAdd) is the code providers run. + * The tile path needs android.util.LruCache (PolygonTileRenderer) and is in + * androidTest: OverlayOnAddedDeviceTest. + */ +class OverlayOnAddedTest { + private val events = mutableListOf() + + /** A polygon renderer that draws nothing and records what it was asked. */ + private inner class FakeRenderer : PolygonOverlayRendererInterface { + var failIds: Set = emptySet() + + override suspend fun onAdd(data: List): List = + data.map { params -> + val id = params.state.id + if (id in failIds) { + null + } else { + events += "native:$id" + "native-$id" + } + } + + override suspend fun onChange(data: List>): List = + data.map { + events += "change:${it.current.state.id}" + it.prev.polygon + } + + override suspend fun onRemove(data: List>) { + data.forEach { events += "remove:${it.state.id}" } + } + + override suspend fun onPostProcess() = Unit + } + + private inner class FakePolygonController( + renderer: FakeRenderer, + ) : PolygonController(PolygonManager(), renderer) + + /** Just enough of a map: polygons go through the real core controller. */ + private inner class FakeMap : + MapViewControllerInterface, + PolygonCapableInterface { + val renderer = FakeRenderer() + val polygons = FakePolygonController(renderer) + + override suspend fun compositionPolygons(data: List) = polygons.add(data) + + override suspend fun updatePolygon(state: PolygonState) = polygons.update(state) + + @Deprecated("Use PolygonState.onClick instead.") + override fun setOnPolygonClickListener(listener: OnPolygonEventHandler?) = Unit + + override fun hasPolygon(state: PolygonState): Boolean = polygons.has(state.id) + + override val holder: MapViewHolderInterface<*, *> get() = error("not used") + + override suspend fun clearOverlays() = polygons.clear() + + override fun moveCamera(position: MapCameraPosition) = Unit + + override fun animateCamera( + position: MapCameraPosition, + duration: Long, + ) = Unit + + override fun fitBounds( + bounds: GeoRectBounds, + padding: Int, + ) = Unit + + override fun registerOverlayController(controller: OverlayControllerInterface<*, *>) = Unit + + override fun destroy() { + polygons.destroy() + } + } + + private val maps = mutableListOf() + + @After + fun tearDown() { + maps.forEach { it.destroy() } + } + + private fun map() = FakeMap().also { maps += it } + + private fun square( + i: Int, + onAdded: ((PolygonState) -> Unit)? = null, + ): PolygonState { + val lat = (i / 100) * 0.01 + val lng = (i % 100) * 0.01 + val points: List = + listOf( + GeoPoint.fromLatLong(lat, lng), + GeoPoint.fromLatLong(lat, lng + 0.005), + GeoPoint.fromLatLong(lat + 0.005, lng + 0.005), + GeoPoint.fromLatLong(lat + 0.005, lng), + ) + return PolygonState(points = points, id = "p$i", onAdded = onAdded) + } + + private val recorder: (PolygonState) -> Unit = { events += "onAdded:${it.id}" } + + private fun PolygonOverlay.show( + map: FakeMap, + states: List, + ) = runBlocking { render(states.associateBy { it.id }.toMutableMap(), map) } + + private fun overlay() = PolygonOverlay(MutableStateFlow(mutableMapOf())) + + @Test + fun `native drawing - called once each, after the renderer made the object`() { + val map = map() + val overlay = overlay() + val states = List(3) { square(it, recorder) } + + overlay.show(map, states) + + assertEquals( + listOf("native:p0", "native:p1", "native:p2", "onAdded:p0", "onAdded:p1", "onAdded:p2"), + events, + ) + } + + @Test + fun `an in-place update or the same list again calls nothing`() { + val map = map() + val overlay = overlay() + val states = List(2) { square(it, recorder) } + overlay.show(map, states) + events.clear() + + states[0].fillColor = androidx.compose.ui.graphics.Color.Red + runBlocking { map.updatePolygon(states[0]) } + overlay.show(map, states) + // Replacing the callback redraws nothing and calls nothing either. + states[1].onAdded = { events += "replaced:${it.id}" } + overlay.show(map, states) + + assertEquals(listOf("change:p0"), events) + } + + @Test + fun `removed and added again - called again`() { + val map = map() + val overlay = overlay() + val a = square(0, recorder) + val b = square(1, recorder) + overlay.show(map, listOf(a, b)) + overlay.show(map, listOf(a)) + events.clear() + + overlay.show(map, listOf(a, b)) + + assertEquals(listOf("native:p1", "onAdded:p1"), events) + } + + @Test + fun `a callback that throws does not stop the others`() { + val map = map() + val overlay = overlay() + val states = + listOf( + square(0, recorder), + square(1) { throw IllegalStateException("app bug") }, + square(2, recorder), + ) + + overlay.show(map, states) + + assertEquals(listOf("onAdded:p0", "onAdded:p2"), events.filter { it.startsWith("onAdded") }) + } + + @Test + fun `not called for what the map could not add, until it does`() { + val map = map() + val overlay = overlay() + map.renderer.failIds = setOf("p1") + val states = List(2) { square(it, recorder) } + + overlay.show(map, states) + assertEquals(listOf("onAdded:p0"), events.filter { it.startsWith("onAdded") }) + + events.clear() + map.renderer.failIds = emptySet() + overlay.show(map, states) + assertEquals(listOf("native:p1", "onAdded:p1"), events) + } + + @Test + fun `clearing the map calls nothing, and a new map starts from nothing`() { + val overlay = overlay() + val states = List(2) { square(it, recorder) } + val first = map() + overlay.show(first, states) + runBlocking { first.clearOverlays() } + assertEquals(2, events.count { it.startsWith("onAdded") }) + + events.clear() + overlay.show(map(), states) + assertEquals(listOf("onAdded:p0", "onAdded:p1"), events.filter { it.startsWith("onAdded") }) + } + + @Test + fun `a listener hears the states that reached the map, with or without onAdded, before their onAdded`() { + val map = map() + val overlay = overlay() + val remove = OverlayAddedListeners.add { states -> events += "heard:" + states.joinToString(",") { it.id } } + try { + val states = listOf(square(0, recorder), square(1)) + overlay.show(map, states) + overlay.show(map, states) // nothing new + remove() + overlay.show(map, states + square(2)) + } finally { + remove() + } + + assertEquals( + listOf("heard:p0,p1", "onAdded:p0"), + events.filter { it.startsWith("heard") || it.startsWith("onAdded") }, + ) + } + + // ── the other overlay types use the same tracker; check each is wired ── + + private class RecordingMap : + MapViewControllerInterface, + MarkerCapableInterface, + CircleCapableInterface, + PolylineCapableInterface, + GroundImageCapableInterface, + RasterLayerCapableInterface { + val ids = mutableSetOf() + + override suspend fun compositionMarkers(data: List) = data.forEach { ids += it.id } + + override suspend fun updateMarker(state: MarkerState) = Unit + + override fun hasMarker(state: MarkerState) = state.id in ids + + @Deprecated("x") + override fun setOnMarkerDragStart(listener: OnMarkerEventHandler?) = Unit + + @Deprecated("x") + override fun setOnMarkerDrag(listener: OnMarkerEventHandler?) = Unit + + @Deprecated("x") + override fun setOnMarkerDragEnd(listener: OnMarkerEventHandler?) = Unit + + @Deprecated("x") + override fun setOnMarkerAnimateStart(listener: OnMarkerEventHandler?) = Unit + + @Deprecated("x") + override fun setOnMarkerAnimateEnd(listener: OnMarkerEventHandler?) = Unit + + @Deprecated("x") + override fun setOnMarkerClickListener(listener: OnMarkerEventHandler?) = Unit + + override fun setMarkerAnimationOverlayHost(host: MarkerAnimationOverlayHost?) = Unit + + override suspend fun compositionCircles(data: List) = data.forEach { ids += it.id } + + override suspend fun updateCircle(state: CircleState) = Unit + + @Deprecated("x") + override fun setOnCircleClickListener(listener: OnCircleEventHandler?) = Unit + + override fun hasCircle(state: CircleState) = state.id in ids + + override suspend fun compositionPolylines(data: List) = data.forEach { ids += it.id } + + override suspend fun updatePolyline(state: PolylineState) = Unit + + @Deprecated("x") + override fun setOnPolylineClickListener(listener: OnPolylineEventHandler?) = Unit + + override fun hasPolyline(state: PolylineState) = state.id in ids + + override suspend fun compositionGroundImages(data: List) = data.forEach { ids += it.id } + + override suspend fun updateGroundImage(state: GroundImageState) = Unit + + @Deprecated("x") + override fun setOnGroundImageClickListener(listener: OnGroundImageEventHandler?) = Unit + + override fun hasGroundImage(state: GroundImageState) = state.id in ids + + override suspend fun compositionRasterLayers(data: List) = data.forEach { ids += it.id } + + override suspend fun updateRasterLayer(state: RasterLayerState) = Unit + + override fun hasRasterLayer(state: RasterLayerState) = state.id in ids + + override val holder: MapViewHolderInterface<*, *> get() = error("not used") + + override suspend fun clearOverlays() = Unit + + override fun moveCamera(position: MapCameraPosition) = Unit + + override fun animateCamera( + position: MapCameraPosition, + duration: Long, + ) = Unit + + override fun fitBounds( + bounds: GeoRectBounds, + padding: Int, + ) = Unit + + override fun registerOverlayController(controller: OverlayControllerInterface<*, *>) = Unit + + override fun destroy() = Unit + } + + @Test + fun `markers, circles, polylines, ground images and raster layers call onAdded too`() { + val map = RecordingMap() + val here = GeoPoint.fromLatLong(35.0, 139.0) + val marker = MarkerState(position = here, id = "m", onAdded = { events += "marker:${it.id}" }) + val circle = + CircleState(center = here, radiusMeters = 10.0, id = "c", onAdded = { events += "circle:${it.id}" }) + val polyline = + PolylineState( + points = listOf(here, GeoPoint.fromLatLong(35.1, 139.1)), + id = "l", + onAdded = { events += "polyline:${it.id}" }, + ) + val groundImage = + GroundImageState( + bounds = + GeoRectBounds().apply { + extend(here) + extend(GeoPoint.fromLatLong(35.1, 139.1)) + }, + image = FakeDrawable(), + id = "g", + onAdded = { events += "groundImage:${it.id}" }, + ) + val raster = + RasterLayerState( + source = RasterLayerSource.UrlTemplate(template = "https://example.com/{z}/{x}/{y}.png"), + id = "r", + onAdded = { events += "raster:${it.id}" }, + ) + runBlocking { + MarkerOverlay(MutableStateFlow(mutableMapOf())).render(mutableMapOf("m" to marker), map) + CircleOverlay(MutableStateFlow(mutableMapOf())).render(mutableMapOf("c" to circle), map) + PolylineOverlay(MutableStateFlow(mutableMapOf())).render(mutableMapOf("l" to polyline), map) + GroundImageOverlay(MutableStateFlow(mutableMapOf())).render(mutableMapOf("g" to groundImage), map) + RasterLayerOverlay(MutableStateFlow(mutableMapOf())).render(mutableMapOf("r" to raster), map) + } + assertEquals(listOf("marker:m", "circle:c", "polyline:l", "groundImage:g", "raster:r"), events) + } + + /** GroundImageState needs a Drawable; nothing here draws it. */ + private class FakeDrawable : android.graphics.drawable.Drawable() { + override fun draw(canvas: android.graphics.Canvas) = Unit + + override fun setAlpha(alpha: Int) = Unit + + override fun setColorFilter(colorFilter: android.graphics.ColorFilter?) = Unit + + @Deprecated("Deprecated in Java") + override fun getOpacity(): Int = android.graphics.PixelFormat.OPAQUE + } + + @Test + fun `copy carries onAdded, and it is not part of equality`() { + val callback: (PolygonState) -> Unit = {} + val a = square(0, callback) + assertTrue(a.copy().onAdded === callback) + assertEquals(a, square(0, null)) + assertEquals(a.fingerPrint(), square(0, null).fingerPrint()) + val marker = MarkerState(position = GeoPoint.fromLatLong(0.0, 0.0), id = "m", onAdded = { }) + assertTrue(marker.copy().onAdded === marker.onAdded) + assertEquals(marker.fingerPrint(), marker.copy(onAdded = null).fingerPrint()) + } +} diff --git a/src/test/java/com/mapconductor/core/OverlayStateMapsTest.kt b/src/test/java/com/mapconductor/core/OverlayStateMapsTest.kt new file mode 100644 index 0000000..1ea6fa9 --- /dev/null +++ b/src/test/java/com/mapconductor/core/OverlayStateMapsTest.kt @@ -0,0 +1,21 @@ +package com.mapconductor.core + +import org.junit.Assert.* +import org.junit.Test + +class OverlayStateMapsTest { + @Test + fun generationsKeepValuesAndInsertionOrderIndependent() { + val first = copyOverlayStates(mapOf("a" to Any(), "b" to Any(), "c" to Any())) + val second = copyOverlayStates(first) + second.remove("b") + second["d"] = Any() + val third = copyOverlayStates(second) + third["b"] = first.getValue("b") + assertEquals(listOf("a", "b", "c"), first.keys.toList()) + assertEquals(listOf("a", "c", "d"), second.keys.toList()) + assertEquals(listOf("a", "c", "d", "b"), third.keys.toList()) + assertSame(first["a"], second["a"]) + assertSame(second["a"], third["a"]) + } +} diff --git a/src/test/java/com/mapconductor/core/ShapeDefaultsTest.kt b/src/test/java/com/mapconductor/core/ShapeDefaultsTest.kt new file mode 100644 index 0000000..5965017 --- /dev/null +++ b/src/test/java/com/mapconductor/core/ShapeDefaultsTest.kt @@ -0,0 +1,60 @@ +package com.mapconductor.core + +import androidx.compose.ui.unit.dp +import com.mapconductor.core.circle.CircleState +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.features.GeoRectBounds +import com.mapconductor.core.groundimage.GroundImageState +import com.mapconductor.core.polygon.PolygonState +import com.mapconductor.core.polyline.PolylineState +import org.junit.Assert.assertEquals +import org.junit.Test + +/** + * 図形・地表画像の既定値。コンポーネント形(android-sdk-compose の `Circle(center, ...)` など)と + * state 形で同じ値になるよう 3 プラットフォームで揃えている: + * Circle / Polygon / Polyline の strokeWidth = 1.dp、GroundImage の opacity = 1.0f。 + * js-sdk-core の `ShapeDefaults.test.mjs`、ios-sdk の `ShapeDefaultsTests` と同じ観点。 + */ +class ShapeDefaultsTest { + private val p1 = GeoPoint.fromLatLong(35.0, 139.0) + private val p2 = GeoPoint.fromLatLong(35.0, 140.0) + private val p3 = GeoPoint.fromLatLong(36.0, 140.0) + + @Test + fun circleStrokeWidthDefaultsTo1dp() { + assertEquals(1.dp, CircleState(center = p1, radiusMeters = 100.0).strokeWidth) + } + + @Test + fun polygonStrokeWidthDefaultsTo1dp() { + assertEquals(1.dp, PolygonState(points = listOf(p1, p2, p3)).strokeWidth) + } + + @Test + fun polylineStrokeWidthDefaultsTo1dp() { + assertEquals(1.dp, PolylineState(points = listOf(p1, p2)).strokeWidth) + } + + @Test + fun groundImageOpacityDefaultsTo1() { + val bounds = + GeoRectBounds().apply { + extend(p1) + extend(p3) + } + assertEquals(1.0f, GroundImageState(bounds = bounds, image = FakeDrawable()).opacity) + } + + /** GroundImageState は Drawable を要求するが、テストでは中身を使わない。 */ + private class FakeDrawable : android.graphics.drawable.Drawable() { + override fun draw(canvas: android.graphics.Canvas) = Unit + + override fun setAlpha(alpha: Int) = Unit + + override fun setColorFilter(colorFilter: android.graphics.ColorFilter?) = Unit + + @Deprecated("Deprecated in Java") + override fun getOpacity(): Int = android.graphics.PixelFormat.OPAQUE + } +} diff --git a/src/test/java/com/mapconductor/core/circle/CircleHitTest.kt b/src/test/java/com/mapconductor/core/circle/CircleHitTest.kt new file mode 100644 index 0000000..f957974 --- /dev/null +++ b/src/test/java/com/mapconductor/core/circle/CircleHitTest.kt @@ -0,0 +1,133 @@ +package com.mapconductor.core.circle + +import androidx.compose.ui.unit.dp +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.map.MapCameraPosition +import com.mapconductor.core.spherical.Spherical +import com.mapconductor.core.spherical.calculateMetersPerPixel +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test +import kotlin.random.Random + +/** + * 円のタップ判定。タイルで描いていてもネイティブで描いていても同じ(元の円に対して見る)。 + * + * 当たるのは「中心からの距離 ≤ 半径 + 縁幅 / 2(画面上の大きさ、カメラのズームで)」。カメラが + * 無ければ半径だけ。指の大きさは足さない(面はポリゴンと同じく中だけ)。複数当たれば実効 zIndex の + * 大きいもの、同じなら中心の近いもの。clickable = false は素通り。緯度の事前判定で結果は変わらない。 + * + * js-sdk-core の `CircleHit.test.mjs`、ios-sdk の `CircleHitTests` と 1 対 1 で対応する。 + */ +class CircleHitTest { + private val lat = 42.3550 + private val lng = -71.0600 + private val camera = MapCameraPosition(position = GeoPoint.fromLatLong(lat, lng), zoom = 16.0) + private val metersPerPixel = calculateMetersPerPixel(lat, 16.0) + + /** 北へ [meters] m(球面、Spherical.computeOffset と同じ)。 */ + private fun north( + meters: Double, + from: GeoPoint = GeoPoint.fromLatLong(lat, lng), + ) = Spherical.computeOffset(from, meters, 0.0) + + private fun circle( + id: String, + radius: Double = 10.0, + center: GeoPoint = GeoPoint.fromLatLong(lat, lng), + strokeWidth: Float = 1f, + zIndex: Int? = 0, + clickable: Boolean = true, + ) = CircleState( + center = center, + radiusMeters = radius, + id = id, + strokeWidth = strokeWidth.dp, + zIndex = zIndex, + clickable = clickable, + ) + + private fun managerWith(vararg states: CircleState): CircleManager = + CircleManager().apply { states.forEach { registerEntity(CircleEntity(circle = Unit, state = it)) } } + + @Test + fun `半径と縁幅の半分の内なら当たり、外なら外れ`() { + // 縁幅 10 dp: z16 で 5 px ≒ 8.9 m 外まで + val m = managerWith(circle("a", radius = 10.0, strokeWidth = 10f)) + val edge = 10.0 + 5.0 * metersPerPixel + assertEquals("a", m.find(north(edge - 0.2), camera)?.state?.id) + assertNull(m.find(north(edge + 0.2), camera)) + assertEquals("a", m.find(north(0.0), camera)?.state?.id) + } + + @Test + fun `カメラが無ければ半径だけ`() { + val m = managerWith(circle("a", radius = 10.0, strokeWidth = 10f)) + assertEquals("a", m.find(north(9.9))?.state?.id) + assertNull(m.find(north(10.1))) + assertNull(m.find(north(10.1), null)) + } + + @Test + fun `指の大きさは足さない`() { + // 縁幅 0: 半径のすぐ外は外れ(tapTolerance 14 dp ≒ 25 m を足していない) + val m = managerWith(circle("a", radius = 10.0, strokeWidth = 0f)) + assertNull(m.find(north(10.5), camera)) + } + + @Test + fun `同じ zIndex なら中心の近いもの`() { + val a = circle("a", radius = 20.0, center = north(-5.0)) + val b = circle("b", radius = 20.0, center = north(5.0)) + assertEquals("b", managerWith(a, b).find(north(3.0), camera)?.state?.id) + assertEquals("b", managerWith(b, a).find(north(3.0), camera)?.state?.id) + assertEquals("a", managerWith(a, b).find(north(-3.0), camera)?.state?.id) + } + + @Test + fun `zIndex の大きいものが先`() { + val near = circle("near", radius = 20.0, center = north(5.0), zIndex = 0) + val far = circle("far", radius = 20.0, center = north(-5.0), zIndex = 1) + assertEquals("far", managerWith(near, far).find(north(3.0), camera)?.state?.id) + // 未指定は中心からの自動値(南ほど大きい) + val autoNorth = circle("autoNorth", radius = 20.0, center = north(5.0), zIndex = null) + val autoSouth = circle("autoSouth", radius = 20.0, center = north(-5.0), zIndex = null) + assertEquals("autoSouth", managerWith(autoNorth, autoSouth).find(north(3.0), camera)?.state?.id) + } + + @Test + fun `clickable = false は素通りして下の円に当たる`() { + val top = circle("top", radius = 20.0, zIndex = 5, clickable = false) + val under = circle("under", radius = 20.0, zIndex = 0) + assertEquals("under", managerWith(top, under).find(north(1.0), camera)?.state?.id) + assertNull(managerWith(top).find(north(1.0), camera)) + } + + @Test + fun `緯度の事前判定で結果は変わらない`() { + val random = Random(42) + val states = + List(3000) { i -> + circle( + "c$i", + radius = 1.0 + random.nextDouble() * 14.0, + center = GeoPoint.fromLatLong(lat + (random.nextDouble() - 0.5) * 0.01, lng + (random.nextDouble() - 0.5) * 0.01), + strokeWidth = random.nextInt(0, 6).toFloat(), + zIndex = random.nextInt(0, 3), + ) + } + val m = managerWith(*states.toTypedArray()) + repeat(500) { + val tap = GeoPoint.fromLatLong(lat + (random.nextDouble() - 0.5) * 0.01, lng + (random.nextDouble() - 0.5) * 0.01) + val expected = + states + .map { it to Spherical.computeDistanceBetween(it.center, tap) } + .filter { (s, d) -> d <= s.radiusMeters + metersPerPixel * s.strokeWidth.value / 2.0 } + .sortedWith(compareByDescending> { it.first.zIndex!! }.thenBy { it.second }) + .firstOrNull() + ?.first + ?.id + assertEquals(expected, m.find(tap, camera)?.state?.id) + } + } +} diff --git a/src/test/java/com/mapconductor/core/circle/CircleTileFileStorageTest.kt b/src/test/java/com/mapconductor/core/circle/CircleTileFileStorageTest.kt new file mode 100644 index 0000000..f63df05 --- /dev/null +++ b/src/test/java/com/mapconductor/core/circle/CircleTileFileStorageTest.kt @@ -0,0 +1,228 @@ +package com.mapconductor.core.circle + +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.dp +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.shapetile.ShapeGridIndex +import com.mapconductor.core.shapetile.StorageOrder +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Assert.fail +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import java.io.IOException +import java.util.concurrent.CancellationException + +class CircleTileFileStorageTest { + @get:Rule val temporary = TemporaryFolder() + + private fun state( + index: Int = 0, + geodesic: Boolean = true, + ) = CircleState( + center = GeoPoint(42.0 + index * 0.00001, -71.0), radiusMeters = 500.0 + index, + geodesic = geodesic, fillColor = Color(0x802563EB), strokeColor = Color.Red, strokeWidth = 0.5.dp, + ) + + @Test fun exactGeometryRoundTripAcrossBlockBoundaries() { + val storage = + CircleTileFileStorage.create(temporary.root, 1025, { + if (it == 511) null else TileCircle.from(state(it, it % 2 == 0)) + }) + try { + assertEquals(16L + 80L * 1025, storage.cacheFile.length()) + for (index in listOf(0, 510, 512, 1023, 1024)) { + val source = state(index, index % 2 == 0) + val decoded = storage[index]!! + assertTrue(decoded.matches(source)) + assertArrayEquals(TileCircle.from(source)!!.bbox, storage.bbox(index), 0.0) + } + assertNull(storage[511]) + assertNull(storage.bbox(511)) + assertNull(storage[-1]) + assertNull(storage[1025]) + } finally { + storage.release() + } + assertTrue(temporary.root.listFiles()!!.isEmpty()) + } + + @Test fun blockCacheRemainsBoundedAndEvictedRecordsReload() { + val storage = CircleTileFileStorage.create(temporary.root, 512 * 60, { TileCircle.from(state(it / 512)) }) + try { + for (block in 0 until 60) assertTrue(storage[block * 512]!!.matches(state(block))) + assertTrue(storage.cachedBytes <= 48 * 512 * 80) + assertTrue(storage[0]!!.matches(state())) + assertEquals(48, storage.allocatedReadBuffers) + } finally { + storage.release() + } + } + + @Test fun snapshotsShareFilesWithoutSharingUpdatedValuesOrReaderLifetimes() { + val before = CircleTileFileStorage.create(temporary.root, 3, { TileCircle.from(state(it)) }) + val path = before.cacheFile + before.retain() // A tile request that outlives replacement of the model. + val changed = TileCircle.from(state(40, false))!! + val after = before.updated(listOf(0 to changed, 1 to null)) + before.release() // Retire the old renderer owner. + try { + assertTrue(before[0]!!.matches(state())) + assertTrue(after[0]!!.matches(state(40, false))) + assertNull(after[1]) + assertNotNull(before[1]) + after.release() + assertTrue(path.exists()) + } finally { + before.release() + } + assertFalse(path.exists()) + } + + @Test fun largeUpdateCompactsWithoutModifyingOldSnapshots() { + val before = CircleTileFileStorage.create(temporary.root, 2100, { TileCircle.from(state()) }) + val oldPath = before.cacheFile + val changed = TileCircle.from(state(20, false))!! + val after = before.updated(List(2050) { it to if (it == 10) null else changed }) as CircleTileFileStorage + try { + assertNotEquals(oldPath, after.cacheFile) + assertTrue(before[0]!!.matches(state())) + assertTrue(after[0]!!.matches(state(20, false))) + assertNull(after[10]) + assertTrue(after[2099]!!.matches(state())) + before.release() + assertFalse(oldPath.exists()) + assertNotNull(after[1]) + } finally { + after.release() + } + assertTrue(temporary.root.listFiles()!!.isEmpty()) + } + + @Test fun updatingExistingSlotsAtTheOverrideLimitStillSharesTheFile() { + val before = CircleTileFileStorage.create(temporary.root, 3000, { TileCircle.from(state()) }) + val changed = TileCircle.from(state(30, false))!! + val atLimit = before.updated(List(2048) { it to changed }) as CircleTileFileStorage + val after = atLimit.updated(listOf(0 to null, 1 to changed)) as CircleTileFileStorage + try { + assertEquals(before.cacheFile, after.cacheFile) + assertNull(after[0]) + assertNotNull(atLimit[0]) + assertTrue(after[1]!!.matches(state(30, false))) + } finally { before.release(); atLimit.release(); after.release() } + assertTrue(temporary.root.listFiles()!!.isEmpty()) + } + + @Test fun cancelledOrFailedWritesDeletePartialCacheFiles() { + val active = CircleTileFileStorage.create(temporary.root, 2, { TileCircle.from(state()) }) + try { + for (cancel in listOf(false, true)) { + try { + CircleTileFileStorage.create(temporary.root, 10000, { + if (!cancel && it == 600) throw IOException("simulated write source failure") + TileCircle.from(state()) + }, { if (cancel) throw CancellationException("cancelled") }) + fail("Expected write failure") + } catch (_: IOException) { + } catch (_: CancellationException) { + } + assertEquals(listOf(active.cacheFile), temporary.root.listFiles()!!.toList()) + assertNotNull(active[0]) + } + } finally { + active.release() + } + } + + /** Every fourth one here, the rest far away and spread out: in index order the ones here span every block. */ + private fun scattered(count: Int) = + List(count) { i -> + if (i % 4 == 0) { + CircleState(center = GeoPoint(42.0 + i * 0.000001, -71.0), radiusMeters = 100.0 + i, fillColor = Color.Blue) + } else { + CircleState(center = GeoPoint(30.0 + (i % 50), -120.0 + (i % 97) * 0.5), radiusMeters = 100.0 + i, fillColor = Color.Red) + } + } + + private fun byPlace(states: List) = + StorageOrder.sortedBy(states.size) { StorageOrder.mortonCellKey(states[it].center.latitude, states[it].center.longitude) } + + @Test fun storedByPlaceReadsAndIndexesByTheListsIndices() { + val states = scattered(2048) + val order = byPlace(states) + val storage = CircleTileFileStorage.create(temporary.root, states.size, { TileCircle.from(states[it]) }, order = order) + try { + assertEquals(order, storage.storageOrder) + // The ones here, before anything else is read: contiguous in storage, + // so at most the two blocks they straddle (all four in index order), + // and each call says which it is. + val here = IntArray(512) { it * 4 } + val seen = BooleanArray(here.size) + storage.forEachRecord(here, {}) { k, bytes, offset, _ -> + seen[k] = true + assertEquals(TileCircle.from(states[here[k]])!!.bbox[0], bytes!!.getDouble(offset + 24) - bytes.getDouble(offset + 40), 1e-12) + } + assertTrue(seen.all { it }) + assertTrue("blocks read: ${storage.allocatedReadBuffers}", storage.allocatedReadBuffers <= 2) + val plain = CircleTileFileStorage.create(temporary.newFolder(), states.size, { TileCircle.from(states[it]) }) + try { + plain.forEachRecord(here, {}) { _, _, _, _ -> } + assertEquals("blocks read in index order", 4, plain.allocatedReadBuffers) + } finally { + plain.release() + } + for (i in states.indices) { + assertTrue("index $i", storage[i]!!.matches(states[i])) + assertArrayEquals(TileCircle.from(states[i])!!.bbox, storage.bbox(i), 0.0) + } + } finally { + storage.release() + } + } + + @Test fun storedByPlaceKeepsIndicesThroughUpdatesAndCompaction() { + val states = scattered(4096) + val storage = CircleTileFileStorage.create(temporary.root, states.size, { TileCircle.from(states[it]) }, order = byPlace(states)) + // More than the override limit: compacts into a new file in the same order. + val changed = (0 until 3000).map { it to TileCircle.from(CircleState(center = GeoPoint(10.0, 10.0 + it * 0.001), radiusMeters = 7.0)) } + val after = storage.updated(changed) + storage.release() + try { + assertNotEquals(null, after.storageOrder) + for (i in 0 until 3000) assertEquals("index $i", 7.0, after[i]!!.radiusMeters, 0.0) + for (i in 3000 until 4096) assertTrue("index $i", after[i]!!.matches(states[i])) + } finally { + after.release() + } + } + + @Test fun theGridAnswersTheSameInStorageOrder() { + val states = scattered(3000) + val boxes = states.map { TileCircle.from(it)!!.bbox } + val order = byPlace(states) + val plain = ShapeGridIndex.build(boxes.size) { boxes[it] } + val read = ArrayList() + val ordered = ShapeGridIndex.build(boxes.size, order) { read.add(it); boxes[it] } + assertEquals("built in storage order", order.indexAt.toList(), read) + for ((x, y, size) in listOf(Triple(0.3, 0.37, 0.001), Triple(0.0, 0.0, 1.0), Triple(0.16, 0.38, 0.05))) { + val inspected = ArrayList() + val answer = ordered.query({ inspected.add(it); boxes[it] }, x, y, x + size, y + size, order) + assertArrayEquals(plain.query({ boxes[it] }, x, y, x + size, y + size), answer) + assertEquals("boxes read in storage order", inspected.sortedBy { order.positionOf[it] }, inspected) + } + } + + @Test fun mortonKeysAndTheOrderAreStable() { + // Cell (2048, 2048): bit 11 of x and of y. + assertEquals((1 shl 22) or (1 shl 23), StorageOrder.mortonCellKey(0.0, 0.0)) + val order = StorageOrder.sortedBy(6) { intArrayOf(5, 1, 5, 0, 1, 5)[it] } + assertArrayEquals(intArrayOf(3, 1, 4, 0, 2, 5), order.indexAt) + assertArrayEquals(intArrayOf(3, 1, 4, 0, 2, 5).let { a -> IntArray(6).also { p -> a.forEachIndexed { pos, i -> p[i] = pos } } }, order.positionOf) + } +} diff --git a/src/test/java/com/mapconductor/core/circle/CircleTilingTest.kt b/src/test/java/com/mapconductor/core/circle/CircleTilingTest.kt new file mode 100644 index 0000000..ac398e5 --- /dev/null +++ b/src/test/java/com/mapconductor/core/circle/CircleTilingTest.kt @@ -0,0 +1,268 @@ +package com.mapconductor.core.circle + +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.dp +import com.mapconductor.core.calculateZIndex +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.geometry.circleToRing +import com.mapconductor.core.polygon.toMercatorRing +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import kotlin.math.abs +import kotlin.math.max + +/** + * 円のタイル描画を支える部品(画素を見ない部分)。 + * + * js-sdk-core の `CircleTiling.test.mjs`、ios-sdk の `CircleTilingTests` と 1 対 1 で対応する。 + * 画素そのものは端末で見る(androidTest の `CircleTileRendererDeviceTest`)。 + * + * - しきい値: 円の数だけ(頂点が無い)。判定はここ 1 か所。 + * - タイルにできないもの: 半径 0 以下・非有限、極(とメルカトルの外)にかかる、日付変更線をまたぐ。 + * geodesic はどちらでもタイルにできる。 + * - 外接範囲はネイティブの 128 角形(circleToRing)と同じ式。 + * - ズームごとの形: 直径 1 px 未満は点、メルカトルのゆがみが 0.25 px 以内なら真円、それ以外は 128 角形。 + */ +class CircleTilingTest { + private val boston = GeoPoint.fromLatLong(42.3555, -71.0605) + + private fun circle( + center: GeoPoint = boston, + radius: Double = 5.0, + geodesic: Boolean = true, + zIndex: Int? = null, + fill: Color = Color(0x80E8590C), + stroke: Color = Color(0xFFE8590C), + strokeWidth: Float = 1f, + ) = CircleState( + center = center, + radiusMeters = radius, + geodesic = geodesic, + zIndex = zIndex, + fillColor = fill, + strokeColor = stroke, + strokeWidth = strokeWidth.dp, + ) + + @Test + fun `円の数が届けばタイルにする`() { + val o = CircleTilingOptions.Default + assertFalse(o.shouldUseTiles(1999)) + assertFalse(o.shouldUseTiles(2000)) + assertTrue(o.shouldUseTiles(2001)) + assertFalse(CircleTilingOptions.Disabled.shouldUseTiles(1_000_000)) + assertTrue(CircleTilingOptions(minCircleCount = 3).shouldUseTiles(3)) + } + + @Test + fun `compact state preserves snapshot isolation and mutation notifications`() { + val state = circle() + var notifications = 0 + state.mutations.listen { notifications++ } + val before = state.radiusMeters + val snapshot = androidx.compose.runtime.snapshots.Snapshot.takeMutableSnapshot() + try { + snapshot.enter { + state.radiusMeters = before + 1 + state.extra = 42L + assertEquals(before + 1, state.radiusMeters, 0.0) + } + assertEquals(before, state.radiusMeters, 0.0) + snapshot.apply().check() + assertEquals(before + 1, state.radiusMeters, 0.0) + assertEquals(42L, state.extra) + assertEquals(2, notifications) + state.extra = 42L + assertEquals(2, notifications) + } finally { snapshot.dispose() } + } + + @Test + fun `change flags preserve independent readers and replacement states`() { + val state = circle() + val first = CircleEntity(Unit, state) + val original = first.fingerPrint + state.radiusMeters = 6.0 + assertEquals(2, first.changeMask(state)) + val second = CircleEntity(Unit, state) + assertEquals(0, second.changeMask(state)) + assertEquals(2, first.changeMask(state)) + assertEquals("legacy provider snapshot stays stable", original, first.fingerPrint) + assertEquals(0, second.changeMask(state.copy())) + assertTrue(second.changeMask(state.copy(fillColor = Color.Red)) != 0) + state.fillColor = Color.Red + assertTrue(first.changeMask(state) and 64 != 0) + assertTrue(second.changeMask(state) and 64 != 0) + } + + + @Test + fun `半径 0 以下・非有限はタイルにしない`() { + assertTrue(CircleTileSet.canTile(circle(radius = 0.1))) + assertFalse(CircleTileSet.canTile(circle(radius = 0.0))) + assertFalse(CircleTileSet.canTile(circle(radius = -1.0))) + assertFalse(CircleTileSet.canTile(circle(radius = Double.NaN))) + assertFalse(CircleTileSet.canTile(circle(radius = Double.POSITIVE_INFINITY))) + } + + @Test + fun `極・メルカトルの外・日付変更線にかかる円はタイルにしない`() { + // 北緯 85 度、半径 10 km: メルカトルの端(85.0511 度)を越える + assertFalse(CircleTileSet.canTile(circle(center = GeoPoint.fromLatLong(85.0, 0.0), radius = 10_000.0))) + assertFalse(CircleTileSet.canTile(circle(center = GeoPoint.fromLatLong(-85.0, 0.0), radius = 10_000.0))) + // 北緯 70 度、半径 200 km: 届かない + assertTrue(CircleTileSet.canTile(circle(center = GeoPoint.fromLatLong(70.0, 20.0), radius = 200_000.0))) + // 日付変更線: 東経 179.99 度、半径 2 km は東へ 180 度を越える + assertFalse(CircleTileSet.canTile(circle(center = GeoPoint.fromLatLong(0.0, 179.99), radius = 2_000.0))) + assertFalse(CircleTileSet.canTile(circle(center = GeoPoint.fromLatLong(0.0, -179.99), radius = 2_000.0))) + assertTrue(CircleTileSet.canTile(circle(center = GeoPoint.fromLatLong(0.0, 179.9), radius = 2_000.0))) + // 中心の経度は [-180, 180] に正規化して見る: 190 度は -170 度 + assertTrue(CircleTileSet.canTile(circle(center = GeoPoint.fromLatLong(0.0, 190.0), radius = 2_000.0))) + // 局所平面(geodesic = false)でも同じ + assertFalse( + CircleTileSet.canTile(circle(center = GeoPoint.fromLatLong(0.0, 179.99), radius = 2_000.0, geodesic = false)), + ) + } + + @Test + fun `geodesic で極を含む円はタイルにしない`() { + // 北緯 60 度、半径 3400 km: 極(30 度 ≒ 3340 km 先)を含む + val c = circle(center = GeoPoint.fromLatLong(60.0, 0.0), radius = 3_400_000.0) + assertFalse(CircleTileSet.canTile(c)) + assertNull(TileCircle.from(c)) + } + + @Test + fun `外接範囲はネイティブの 128 角形と同じ`() { + for (geodesic in listOf(true, false)) { + for ((lat, radius) in listOf(42.3555 to 15.0, 42.3555 to 5_000.0, 70.0 to 200_000.0, -33.0 to 50_000.0)) { + val state = circle(center = GeoPoint.fromLatLong(lat, 10.0), radius = radius, geodesic = geodesic) + val tile = TileCircle.from(state)!! + val ring = toMercatorRing(circleToRing(state.center, radius, geodesic, 1024)) + var minX = Double.POSITIVE_INFINITY + var maxX = Double.NEGATIVE_INFINITY + var minY = Double.POSITIVE_INFINITY + var maxY = Double.NEGATIVE_INFINITY + for (i in ring.indices step 2) { + minX = minOf(minX, ring[i]) + maxX = maxOf(maxX, ring[i]) + minY = minOf(minY, ring[i + 1]) + maxY = maxOf(maxY, ring[i + 1]) + } + val width = maxX - minX + // 1024 角形の外接範囲と、幅の 0.1 % 以内で一致する(多角形は円の内側) + val tolerance = width * 1e-3 + val label = "geodesic=$geodesic lat=$lat r=$radius" + assertEquals(label, minX, tile.bbox[0], tolerance) + assertEquals(label, minY, tile.bbox[1], tolerance) + assertEquals(label, maxX, tile.bbox[2], tolerance) + assertEquals(label, maxY, tile.bbox[3], tolerance) + } + } + } + + @Test + fun `直径 1 px 未満は 1 px の点、その位置は中心の画素`() { + val tile = TileCircle.from(circle(radius = 5.0))!! + // z10: 世界 262144 px。ボストンで 1 px ≒ 113 m + val scale = 256.0 * (1 shl 10) + val shape = simplifyCircle(tile, scale) + assertTrue(shape is CircleTileShape.Dot) + shape as CircleTileShape.Dot + assertEquals(kotlin.math.floor(tile.x * scale), shape.x, 0.0) + assertEquals(kotlin.math.floor(tile.y * scale), shape.y, 0.0) + } + + @Test + fun `街路樹はどのズームでも真円で、半径の画素数はズーム 1 段で 2 倍`() { + val tile = TileCircle.from(circle(radius = 15.0))!! + var previous = 0.0 + for (z in 16..22) { + val shape = simplifyCircle(tile, 256.0 * (1 shl z)) + assertTrue("z$z", shape is CircleTileShape.Arc) + shape as CircleTileShape.Arc + if (previous > 0) assertEquals("z$z", previous * 2, shape.radius, 1e-9) + previous = shape.radius + } + // z22 で 15 m は 1 m ≒ 0.028 m/px … 半径 500 px 前後(ボストンの緯度で) + assertTrue("radius=$previous", previous in 400.0..800.0) + } + + @Test + fun `直径 4 px 未満は縁を描かない`() { + val tile = TileCircle.from(circle(radius = 5.0))!! + // z16 のボストンで 1 px ≒ 1.77 m: 半径 5 m は 2.8 px、直径 5.6 px + val z16 = simplifyCircle(tile, 256.0 * (1 shl 16)) as CircleTileShape.Arc + assertTrue(z16.outlined) + // z15: 直径 2.8 px + val z15 = simplifyCircle(tile, 256.0 * (1 shl 15)) as CircleTileShape.Arc + assertFalse(z15.outlined) + } + + @Test + fun `高緯度の大きな円は 128 角形で、点は circleToRing の点`() { + val state = circle(center = GeoPoint.fromLatLong(70.0, 20.0), radius = 200_000.0) + val tile = TileCircle.from(state)!! + val scale = 256.0 * (1 shl 6) + val shape = simplifyCircle(tile, scale) + assertTrue(shape is CircleTileShape.Ring) + shape as CircleTileShape.Ring + assertTrue(shape.outlined) + // 北側の半径が南側より長い(メルカトルのゆがみ) + val ryN = (tile.y - tile.northY) * scale + val ryS = (tile.southY - tile.y) * scale + assertTrue("ryN=$ryN ryS=$ryS", ryN - ryS > 1.0) + // 残った点は、ネイティブの 128 角形の点を画素格子に丸めたもの + val native = toMercatorRing(circleToRing(state.center, 200_000.0, true, 128)) + for (i in shape.points.indices step 2) { + val px = shape.points[i] + val py = shape.points[i + 1] + var nearest = Double.POSITIVE_INFINITY + for (j in native.indices step 2) { + nearest = minOf(nearest, max(abs(native[j] * scale - px), abs(native[j + 1] * scale - py))) + } + assertTrue("($px, $py) は 128 角形の点から $nearest px", nearest <= 0.5) + } + } + + @Test + fun `真円と 128 角形の切り替えはメルカトルのゆがみが 4 分の 1 px を越えたとき`() { + val tile = TileCircle.from(circle(center = GeoPoint.fromLatLong(42.3555, -71.0605), radius = 5_000.0))!! + // 5 km の円: 低いズームでは真円、高いズームでは 128 角形 + assertTrue(simplifyCircle(tile, 256.0 * (1 shl 8)) is CircleTileShape.Arc) + assertTrue(simplifyCircle(tile, 256.0 * (1 shl 16)) is CircleTileShape.Ring) + } + + @Test + fun `並びは実効 zIndex(未指定は中心からの自動値)`() { + val south = circle(center = GeoPoint.fromLatLong(42.0, -71.0)) + val north = circle(center = GeoPoint.fromLatLong(43.0, -71.0)) + assertEquals(calculateZIndex(south.center), effectiveZIndex(south)) + // 自動値では南が上(大きい) + assertTrue(effectiveZIndex(south) > effectiveZIndex(north)) + assertEquals(7, effectiveZIndex(circle(zIndex = 7))) + } + + @Test + fun `見えない縁(透明・幅 0)は余白にも数えない`() { + val noStroke = TileCircle.from(circle(stroke = Color.Transparent, strokeWidth = 6f))!! + assertFalse(noStroke.strokeVisible) + assertEquals(0f, CircleTilePainter.strokeWidth(noStroke)) + val zeroWidth = TileCircle.from(circle(strokeWidth = 0f))!! + assertEquals(0f, CircleTilePainter.strokeWidth(zeroWidth)) + val visible = TileCircle.from(circle(strokeWidth = 6f)) + assertNotNull(visible) + assertEquals(6f, CircleTilePainter.strokeWidth(visible!!)) + } + + @Test + fun `タイルのレイヤーは決まった id`() { + val state = circleTileRasterLayerState("http://127.0.0.1/tiles/c/256/1/{z}/{x}/{y}.png") + assertEquals(CIRCLE_TILE_LAYER_ID, state.id) + assertEquals("mc-circle-tiles", state.id) + } +} diff --git a/src/test/java/com/mapconductor/core/controller/ClearStrategyMarkerControllersTest.kt b/src/test/java/com/mapconductor/core/controller/ClearStrategyMarkerControllersTest.kt new file mode 100644 index 0000000..f20fb69 --- /dev/null +++ b/src/test/java/com/mapconductor/core/controller/ClearStrategyMarkerControllersTest.kt @@ -0,0 +1,167 @@ +package com.mapconductor.core.controller + +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.features.GeoPointInterface +import com.mapconductor.core.features.GeoRectBounds +import com.mapconductor.core.map.MapCameraPosition +import com.mapconductor.core.map.MapViewHolderInterface +import com.mapconductor.core.map.VisibleRegion +import com.mapconductor.core.marker.MarkerEntity +import com.mapconductor.core.marker.MarkerEntityInterface +import com.mapconductor.core.marker.MarkerManager +import com.mapconductor.core.marker.MarkerOverlayRendererInterface +import com.mapconductor.core.marker.MarkerRenderingStrategyInterface +import com.mapconductor.core.marker.MarkerState +import com.mapconductor.core.marker.OnMarkerEventHandler +import com.mapconductor.core.marker.StrategyMarkerController +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.test.runTest +import org.junit.Assert.assertEquals +import org.junit.Test + +/** + * `clearOverlays()` が、拡張モジュールが [BaseMapViewController.registerOverlayController] で + * 登録した [StrategyMarkerController](クラスタリングなど)も消すこと。 + * + * プロバイダの `clearOverlays()` は自分のフィールドのコントローラしか clear しておらず、 + * Strategy で描いたマーカーは clearOverlays() の後も地図に残っていた。 + */ +class ClearStrategyMarkerControllersTest { + private val bounds = GeoRectBounds(GeoPoint(34.0, 138.0), GeoPoint(36.0, 140.0)) + private val camera = + MapCameraPosition( + position = GeoPoint(35.0, 139.0), + zoom = 10.0, + visibleRegion = VisibleRegion(bounds, null, null, null, null), + ) + + /** GL 系の描画担当: onPostProcess で manager の全部を描き直す。 */ + private class GlRenderer( + private val manager: MarkerManager, + ) : MarkerOverlayRendererInterface { + var drawn: List = emptyList() + override var animateStartListener: OnMarkerEventHandler? = null + override var animateEndListener: OnMarkerEventHandler? = null + override val holder: MapViewHolderInterface<*, *> + get() = throw UnsupportedOperationException("not used") + + override suspend fun onAdd(data: List) = data.map { it.state.id } + + override suspend fun onChange(data: List>) = + data.map { it.current.state.id } + + override suspend fun onRemove(data: List>) = Unit + + override suspend fun onAnimate(entity: MarkerEntityInterface) = Unit + + override suspend fun onPostProcess() { + drawn = manager.allEntities().map { it.state.id }.sorted() + } + } + + private class DrawAllStrategy : MarkerRenderingStrategyInterface { + override val markerManager: MarkerManager = MarkerManager.defaultManager() + + override fun clear() = markerManager.clear() + + override suspend fun onUpdate( + state: MarkerState, + viewport: GeoRectBounds, + renderer: MarkerOverlayRendererInterface, + ): Boolean = true + + override suspend fun onAdd( + data: List, + viewport: GeoRectBounds, + renderer: MarkerOverlayRendererInterface, + ): Boolean { + data.forEach { markerManager.registerEntity(MarkerEntity(marker = it.id, state = it, isRendered = true)) } + renderer.onPostProcess() + return true + } + + override suspend fun onCameraChanged( + cameraPosition: MapCameraPosition, + renderer: MarkerOverlayRendererInterface, + ) = Unit + } + + /** カメラだけ購読する拡張(android-heatmap のような)。clearOverlays で触られてはいけない。 */ + private class CameraOnlyController : OverlayControllerInterface { + var cleared = 0 + override val zIndex = 0 + + override suspend fun add(data: List) = Unit + + override suspend fun update(state: Unit) = Unit + + override suspend fun clear() { + cleared++ + } + + override fun find(position: GeoPointInterface): Unit? = null + + override fun destroy() = Unit + } + + /** プロバイダの clearOverlays() と同じ形: 自分のコントローラを消してから共通部分を呼ぶ。 */ + private class Driver : BaseMapViewController() { + override val holder get() = throw UnsupportedOperationException() + override val defaultCoroutine = CoroutineScope(Dispatchers.Unconfined) + override val mainCoroutine = defaultCoroutine + + override fun moveCamera(position: MapCameraPosition) = Unit + + override fun animateCamera( + position: MapCameraPosition, + duration: Long, + ) = Unit + + override fun fitBounds( + bounds: GeoRectBounds, + padding: Int, + ) = Unit + + override suspend fun clearOverlays() { + clearStrategyMarkerControllers() + } + } + + private fun markers() = + listOf( + MarkerState(position = GeoPoint(35.0, 139.0), id = "m1"), + MarkerState(position = GeoPoint(35.1, 139.1), id = "m2"), + ) + + @Test + fun `clearOverlays は登録された Strategy のマーカーを消し、他の登録物には触らない`() = + runTest { + val driver = Driver() + val groups = + (0..1).map { + val strategy = DrawAllStrategy() + val renderer = GlRenderer(strategy.markerManager) + val controller = StrategyMarkerController(strategy, renderer) + driver.registerOverlayController(controller) + controller.onCameraChanged(camera) + controller.add(markers()) + Triple(strategy, renderer, controller) + } + val other = CameraOnlyController() + driver.registerOverlayController(other) + groups.forEach { assertEquals(listOf("m1", "m2"), it.second.drawn) } + + driver.clearOverlays() + + groups.forEach { (strategy, renderer, _) -> + assertEquals(emptyList(), renderer.drawn) + assertEquals(0, strategy.markerManager.allEntities().size) + } + assertEquals(0, other.cleared) + + // 送り直せばまた描かれる。 + groups.forEach { it.third.add(markers()) } + groups.forEach { assertEquals(listOf("m1", "m2"), it.second.drawn) } + } +} diff --git a/src/test/java/com/mapconductor/core/controller/OverlayStackingTest.kt b/src/test/java/com/mapconductor/core/controller/OverlayStackingTest.kt new file mode 100644 index 0000000..4a997b4 --- /dev/null +++ b/src/test/java/com/mapconductor/core/controller/OverlayStackingTest.kt @@ -0,0 +1,236 @@ +package com.mapconductor.core.controller + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * 重なり順の決まり(ラスター < GroundImage < ポリゴン < サークル < ポリライン < マーカー)。 + * ios-sdk-core / js-sdk-core の同名テストと同じ表。 + */ +class OverlayStackingTest { + @Test + fun `帯は下からラスター・GroundImage・ポリゴン・サークル・ポリライン・マーカー`() { + assertEquals( + listOf( + OverlayKind.RasterLayer, + OverlayKind.GroundImage, + OverlayKind.Polygon, + OverlayKind.Circle, + OverlayKind.Polyline, + OverlayKind.Marker, + ), + OverlayKind.entries.sortedBy { OverlayStacking.band(it) }, + ) + } + + @Test + fun `flatZIndex はどんな zIndex でも帯をまたがない`() { + val extremes = listOf(Int.MIN_VALUE, -35_000_000, -1, 0, 1, 1000, Int.MAX_VALUE) + val bands = OverlayStacking.BOTTOM_TO_TOP + for (i in 0 until bands.size - 1) { + val lowerMax = extremes.maxOf { OverlayStacking.flatZIndex(bands[i], it) } + val upperMin = extremes.minOf { OverlayStacking.flatZIndex(bands[i + 1], it) } + assertTrue("${bands[i]} must stay below ${bands[i + 1]}", lowerMax < upperMin) + } + } + + @Test + fun `flatZIndex は帯の中で zIndex の順を保つ`() { + val zs = listOf(-1000, -10, -1, 0, 1, 2, 10, 1000) + val flat = zs.map { OverlayStacking.flatZIndex(OverlayKind.Polygon, it) } + assertEquals(flat.sorted(), flat) + assertEquals(flat.size, flat.toSet().size) + } + + private data class L( + val id: String, + val key: OverlayStacking.Key?, + ) + + private fun stack(vararg layers: L) = layers.toList() + + private fun k( + kind: OverlayKind, + z: Int = 0, + ) = OverlayStacking.Key(kind, z) + + @Test + fun `insertBefore は鍵が大きい一番下の SDK の層を選び、ベースマップの層は無視する`() { + val layers = + stack( + L("basemap-fill", null), + L("raster", k(OverlayKind.RasterLayer)), + L("basemap-labels", null), + L("polygon", k(OverlayKind.Polygon)), + L("polyline", k(OverlayKind.Polyline)), + L("markers", k(OverlayKind.Marker)), + ) + val before = OverlayStacking.insertBefore(layers, k(OverlayKind.GroundImage)) { it.key } + assertEquals("polygon", before?.id) + assertEquals( + "polyline", + OverlayStacking.insertBefore(layers, k(OverlayKind.Circle)) { it.key }?.id, + ) + assertNull(OverlayStacking.insertBefore(layers, k(OverlayKind.Marker, 5)) { it.key }) + } + + @Test + fun `同じ鍵なら後から入れたものが上、zIndex が大きいものはその上`() { + val layers = + stack( + L("pg-0a", k(OverlayKind.Polygon, 0)), + L("pg-0b", k(OverlayKind.Polygon, 0)), + L("pg-3", k(OverlayKind.Polygon, 3)), + L("circle", k(OverlayKind.Circle)), + ) + assertEquals("pg-3", OverlayStacking.insertBefore(layers, k(OverlayKind.Polygon, 0)) { it.key }?.id) + assertEquals("pg-3", OverlayStacking.insertBefore(layers, k(OverlayKind.Polygon, 1)) { it.key }?.id) + assertEquals("circle", OverlayStacking.insertBefore(layers, k(OverlayKind.Polygon, 3)) { it.key }?.id) + assertEquals("pg-0a", OverlayStacking.insertBefore(layers, k(OverlayKind.Polygon, -1)) { it.key }?.id) + } + + @Test + fun `追加の順によらず同じ並びになる`() { + val kinds = OverlayStacking.BOTTOM_TO_TOP + listOf(kinds, kinds.reversed(), listOf(kinds[3], kinds[0], kinds[5], kinds[1], kinds[4], kinds[2])).forEach { order -> + val layers = mutableListOf() + order.forEach { kind -> + val key = k(kind) + val before = OverlayStacking.insertBefore(layers, key) { it.key } + val at = if (before == null) layers.size else layers.indexOf(before) + layers.add(at, L(kind.name, key)) + } + assertEquals(kinds.map { it.name }, layers.map { it.id }) + } + } +} + +/** + * SDK が描くタイルの置き場所。プロバイダはこの鍵(GL 系)と flatZIndex(Google など)で + * タイルのレイヤーを置く。ポリラインのタイルはポリラインの帯の一番下: ポリゴンのタイルと + * サークルの上、ネイティブのポリラインとマーカー(のタイル)の下。 + */ +class ShapeTileStackingTest { + private val polygonTile = OverlayStacking.Key(OverlayKind.Polygon, Int.MIN_VALUE) + private val polylineTile = OverlayStacking.Key(OverlayKind.Polyline, Int.MIN_VALUE) + private val markerTile = OverlayStacking.Key(OverlayKind.Marker, Int.MIN_VALUE) + + @Test + fun `ポリラインのタイルはサークルの上、ネイティブのポリラインとマーカーの下`() { + val keys = + listOf( + OverlayStacking.Key(OverlayKind.Marker, Int.MIN_VALUE + 1), + markerTile, + OverlayStacking.Key(OverlayKind.Polyline, -1_000_000), + polylineTile, + OverlayStacking.Key(OverlayKind.Circle, Int.MAX_VALUE), + OverlayStacking.Key(OverlayKind.Polygon, Int.MAX_VALUE), + polygonTile, + ) + assertEquals(keys.reversed(), keys.sorted()) + } + + @Test + fun `flatZIndex でも同じ順`() { + val polylineTileZ = OverlayStacking.flatZIndex(OverlayKind.Polyline, Int.MIN_VALUE) + assertTrue(polylineTileZ > OverlayStacking.flatZIndex(OverlayKind.Circle, Int.MAX_VALUE)) + assertTrue(polylineTileZ > OverlayStacking.flatZIndex(OverlayKind.Polygon, Int.MIN_VALUE)) + assertTrue(polylineTileZ < OverlayStacking.flatZIndex(OverlayKind.Polyline, -1_000)) + assertTrue(polylineTileZ < OverlayStacking.flatZIndex(OverlayKind.Marker, Int.MIN_VALUE)) + } + + @Test + fun `GL 系の層の並びでは、ポリゴンのタイルとサークルの上、ネイティブのポリラインの下へ入る`() { + val stack = OverlayLayerStack() + stack.put("raster-layer-mc-polygon-tiles", polygonTile) + stack.put("circle-layer", OverlayStacking.Key(OverlayKind.Circle)) + stack.put("polyline-layer", OverlayStacking.Key(OverlayKind.Polyline)) + stack.put("raster-layer-marker-tile-1", markerTile) + val layers = + listOf( + "water", + "raster-layer-mc-polygon-tiles", + "circle-layer", + "polyline-layer", + "raster-layer-marker-tile-1", + ) + assertEquals("polyline-layer", stack.beforeId(layers, polylineTile)) + } +} + +/** + * 円のタイルはサークルの帯の一番下: ポリゴン(タイル・ネイティブとも)の上、ネイティブの円・ + * ポリラインのタイル・マーカー(のタイル)の下。 + */ +class CircleTileStackingTest { + private val polygonTile = OverlayStacking.Key(OverlayKind.Polygon, Int.MIN_VALUE) + private val circleTile = OverlayStacking.Key(OverlayKind.Circle, Int.MIN_VALUE) + private val polylineTile = OverlayStacking.Key(OverlayKind.Polyline, Int.MIN_VALUE) + private val markerTile = OverlayStacking.Key(OverlayKind.Marker, Int.MIN_VALUE) + + @Test + fun `円のタイルはポリゴンの上、ネイティブの円・ポリラインのタイル・マーカーの下`() { + val keys = + listOf( + markerTile, + polylineTile, + OverlayStacking.Key(OverlayKind.Circle, -1_000_000), + circleTile, + OverlayStacking.Key(OverlayKind.Polygon, Int.MAX_VALUE), + polygonTile, + ) + assertEquals(keys.reversed(), keys.sorted()) + } + + @Test + fun `flatZIndex でも同じ順`() { + val circleTileZ = OverlayStacking.flatZIndex(OverlayKind.Circle, Int.MIN_VALUE) + assertTrue(circleTileZ > OverlayStacking.flatZIndex(OverlayKind.Polygon, Int.MAX_VALUE)) + assertTrue(circleTileZ > OverlayStacking.flatZIndex(OverlayKind.Polygon, Int.MIN_VALUE)) + assertTrue(circleTileZ < OverlayStacking.flatZIndex(OverlayKind.Circle, -1_000)) + assertTrue(circleTileZ < OverlayStacking.flatZIndex(OverlayKind.Polyline, Int.MIN_VALUE)) + assertTrue(circleTileZ < OverlayStacking.flatZIndex(OverlayKind.Marker, Int.MIN_VALUE)) + } + + @Test + fun `GL 系の層の並びでは、ポリゴンのタイルの上、ネイティブの円とポリラインのタイルの下へ入る`() { + val stack = OverlayLayerStack() + stack.put("raster-layer-mc-polygon-tiles", polygonTile) + stack.put("circle-layer", OverlayStacking.Key(OverlayKind.Circle)) + stack.put("raster-layer-mc-polyline-tiles", polylineTile) + stack.put("raster-layer-marker-tile-1", markerTile) + val layers = + listOf( + "water", + "raster-layer-mc-polygon-tiles", + "circle-layer", + "raster-layer-mc-polyline-tiles", + "raster-layer-marker-tile-1", + ) + assertEquals("circle-layer", stack.beforeId(layers, circleTile)) + // ネイティブの円が無ければポリラインのタイルの下 + stack.remove("circle-layer") + assertEquals("raster-layer-mc-polyline-tiles", stack.beforeId(layers - "circle-layer", circleTile)) + } +} + +class OverlayLayerStackTest { + @Test + fun `台帳に無い層は無視し、スタイルを読み直しても同じ位置を返す`() { + val stack = OverlayLayerStack() + stack.put("raster-layer-A", OverlayStacking.Key(OverlayKind.RasterLayer)) + stack.put("polygon-fill-layer-0", OverlayStacking.Key(OverlayKind.Polygon, 0)) + stack.put("markers-layer", OverlayStacking.Key(OverlayKind.Marker)) + val layers = listOf("water", "raster-layer-A", "road-label", "polygon-fill-layer-0", "markers-layer") + assertEquals( + "polygon-fill-layer-0", + stack.beforeId(layers, OverlayStacking.Key(OverlayKind.GroundImage)), + ) + // 読み直し直後(SDK の層がまだ何も無い)なら一番上。 + assertNull(stack.beforeId(listOf("water", "road-label"), OverlayStacking.Key(OverlayKind.GroundImage))) + stack.remove("markers-layer") + assertNull(stack.beforeId(layers, OverlayStacking.Key(OverlayKind.Polyline))) + } +} diff --git a/src/test/java/com/mapconductor/core/geocell/HexCellRegistryRebuildTest.kt b/src/test/java/com/mapconductor/core/geocell/HexCellRegistryRebuildTest.kt deleted file mode 100644 index 580975e..0000000 --- a/src/test/java/com/mapconductor/core/geocell/HexCellRegistryRebuildTest.kt +++ /dev/null @@ -1,116 +0,0 @@ -package com.mapconductor.core.geocell - -import com.mapconductor.core.features.GeoPoint -import com.mapconductor.core.marker.MarkerEntity -import com.mapconductor.core.marker.MarkerState -import org.junit.Assert.assertEquals -import org.junit.Assert.assertFalse -import org.junit.Assert.assertTrue -import org.junit.Test - -/** - * [HexCellRegistry] の再構築条件。 - * - * KDTree が索引しているのはセル集合なので、同じ位置の entity を入れ直しても木は変わらない。 - * 以前はここで無条件に dirty を立てていたため、位置の変わらない更新(アイコン差し替え、 - * [com.mapconductor.core.marker.MarkerViewportSwitch] のタイル⇔ネイティブ切り替えなど。 - * `MarkerManager.updateEntity` は毎回 setPoint を呼ぶ)のあと、次の空間検索が全セルから - * 木を作り直していた。実機(24,000 件)で 200ms 超のメインスレッド停止として観測されたもの。 - */ -class HexCellRegistryRebuildTest { - private val geocell = HexGeocell.defaultGeocell() - - private fun registry() = HexCellRegistry(geocell = geocell, zoom = 20.0) - - private fun entity( - id: String, - latitude: Double, - longitude: Double, - ) = MarkerEntity( - marker = null, - state = MarkerState(id = id, position = GeoPoint.fromLatLong(latitude, longitude)), - ) - - /** 検索を一度通して木を建て、dirty を落とした状態にする。 */ - private fun HexCellRegistry.settle() { - findWithinRadiusWithDistance(GeoPoint.fromLatLong(35.68, 139.76), 1.0) - assertFalse("前提: この時点で dirty は落ちている", getStats().needsRebuild) - } - - /** 同じ位置での再登録は木を汚さない。ここが本命。 */ - @Test - fun `同じ位置の再登録では再構築を要求しない`() { - val registry = registry() - registry.setPoint(entity("a", 35.68, 139.76)) - registry.settle() - - repeat(5) { registry.setPoint(entity("a", 35.68, 139.76)) } - - assertFalse(registry.getStats().needsRebuild) - assertEquals(1, registry.getStats().totalCells) - } - - /** 位置が変わればセル集合が変わるので、再構築は要求される。 */ - @Test - fun `別セルへ移ったら再構築を要求する`() { - val registry = registry() - val before = registry.setPoint(entity("a", 35.68, 139.76)) - registry.settle() - - val after = registry.setPoint(entity("a", 34.70, 135.50)) - - assertTrue("移動後は別セルであること", before.id != after.id) - assertTrue(registry.getStats().needsRebuild) - assertEquals(1, registry.getStats().totalCells) - assertEquals(setOf("a"), registry.getEntryIDsByHexCell(after)?.toSet()) - } - - /** 同一セルに残りがあるなら、1 件消してもセル集合は変わらない。 */ - @Test - fun `同一セル内の 1 件削除では再構築を要求しない`() { - val registry = registry() - // zoom 20 のセルは 10cm 程度なので、同じセルに入れるには座標を完全に一致させる。 - val cell = registry.setPoint(entity("a", 35.680000, 139.760000)) - registry.setPoint(entity("b", 35.680000, 139.760000)) - assertEquals(setOf("a", "b"), registry.getEntryIDsByHexCell(cell)?.toSet()) - registry.settle() - - registry.removePoint(entity("a", 35.680000, 139.760000)) - - assertFalse(registry.getStats().needsRebuild) - assertEquals(setOf("b"), registry.getEntryIDsByHexCell(cell)?.toSet()) - } - - /** 最後の 1 件を消すとセルが消えるので、再構築は要求される。 */ - @Test - fun `セルが空になったら再構築を要求する`() { - val registry = registry() - registry.setPoint(entity("a", 35.68, 139.76)) - registry.settle() - - registry.removePoint(entity("a", 35.68, 139.76)) - - assertTrue(registry.getStats().needsRebuild) - assertEquals(0, registry.getStats().totalCells) - } - - /** 再登録を挟んでも半径検索の結果は変わらない(最適化で結果を落としていないこと)。 */ - @Test - fun `再登録を挟んでも半径検索の結果が変わらない`() { - val registry = registry() - val center = GeoPoint.fromLatLong(35.68, 139.76) - registry.setPoint(entity("a", 35.6800, 139.7600)) - registry.setPoint(entity("b", 35.6805, 139.7605)) - registry.setPoint(entity("c", 34.7000, 135.5000)) - - val before = registry.findWithinRadiusWithDistance(center, 2000.0).map { it.cell.id }.toSet() - repeat(3) { - registry.setPoint(entity("a", 35.6800, 139.7600)) - registry.setPoint(entity("b", 35.6805, 139.7605)) - } - val after = registry.findWithinRadiusWithDistance(center, 2000.0).map { it.cell.id }.toSet() - - assertTrue("近傍のセルが取れていること", after.isNotEmpty()) - assertEquals(before, after) - } -} diff --git a/src/test/java/com/mapconductor/core/geometry/GeodesicPolygonRingTest.kt b/src/test/java/com/mapconductor/core/geometry/GeodesicPolygonRingTest.kt new file mode 100644 index 0000000..2edb524 --- /dev/null +++ b/src/test/java/com/mapconductor/core/geometry/GeodesicPolygonRingTest.kt @@ -0,0 +1,204 @@ +package com.mapconductor.core.geometry + +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.features.GeoPointInterface +import com.mapconductor.core.polygon.PolygonEntity +import com.mapconductor.core.polygon.PolygonManager +import com.mapconductor.core.polygon.PolygonState +import com.mapconductor.core.spherical.Planar +import com.mapconductor.core.spherical.WGS84Geodesic +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotSame +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import kotlin.math.PI +import kotlin.math.abs +import kotlin.math.atan +import kotlin.math.exp +import kotlin.math.hypot +import kotlin.math.ln +import kotlin.math.tan + +/** + * ポリゴンの閉じる辺(末尾 → 先頭)も他の辺と同じ方式で補間すること。geodesic は大圏、 + * geodesic=false は緯度経度の線形補間。どちらも塗り・穴・輪郭が同じ点列になる。 + * + * js-sdk-core の `GeodesicPolygonRing.test.mjs`、ios-sdk の `GeodesicPolygonRingTests` と 1 対 1 で対応する。 + * + * [WGS84Geodesic.createInterpolatePoints] は隣り合う点の間しか補間しない。ポリゴンの点は開いたリング + * (末尾 ≠ 先頭)で渡されるので、塗りのリングは閉じる辺だけが補間されず直線の弦になっていた。 + * 輪郭はリングを閉じてからポリラインとして密度化するので大圏になり、「輪郭は曲線、塗りの一辺だけ直線」になる。 + * Google のように塗りと輪郭を 1 つのネイティブポリゴンで描くプロバイダは、輪郭まで直線になる。 + */ +class GeodesicPolygonRingTest { + private val boston = GeoPoint.fromLatLong(42.36, -71.06) + private val london = GeoPoint.fromLatLong(51.5, -0.12) + private val iceland = GeoPoint.fromLatLong(64.1, -21.9) + + // 実機検証と同じ順序。閉じる辺は アイスランド → ボストン。 + private val triangle = listOf(boston, london, iceland) + + private fun same( + a: GeoPointInterface, + b: GeoPointInterface, + ): Boolean = abs(a.latitude - b.latitude) < 1e-9 && abs(a.longitude - b.longitude) < 1e-9 + + private fun assertSamePoints( + expected: List, + actual: List, + ) { + assertEquals(expected.size, actual.size) + expected.indices.forEach { i -> assertTrue("point $i: ${actual[i]} != ${expected[i]}", same(expected[i], actual[i])) } + } + + /** 輪郭(閉じたリングをポリラインとして密度化)から、末尾の重複点を除いたもの。 */ + private fun outlineOf( + points: List, + geodesic: Boolean, + ): List = buildUnwrappedPolylinePath(points + points.first(), geodesic).dropLast(1) + + @Test + fun greatCircleMidpoint_bostonToIceland_bulgesNorthwestByAboutFourDegrees() { + val mid = WGS84Geodesic.interpolate(boston, iceland, 0.5) + + // Web メルカトルでの直線(弦)が同じ経度で通る緯度。 + fun merc(lat: Double) = ln(tan(PI / 4 + lat * PI / 360)) + val t = (mid.longitude - boston.longitude) / (iceland.longitude - boston.longitude) + val y = merc(boston.latitude) + t * (merc(iceland.latitude) - merc(boston.latitude)) + val chordLat = (2 * atan(exp(y)) - PI / 2) * 180 / PI + assertTrue("mid ${mid.latitude}", abs(mid.latitude - 55.63) < 0.05) + assertTrue("chord $chordLat", abs(chordLat - 51.6) < 0.05) + } + + @Test + fun densifyPolygonRing_interpolatesClosingEdge_andKeepsRingOpen() { + val ring = densifyPolygonRing(triangle, geodesic = true) + assertTrue(same(boston, ring.first())) + // 先頭の重複点を末尾に付けない(閉じて補間した結果から末尾の 1 点だけを除いた長さ)。 + // createInterpolatePoints は分割比を足し込むため、末尾の手前に終点とほぼ同じ点が残ることがある。 + assertEquals(WGS84Geodesic.createInterpolatePoints(triangle + boston).size - 1, ring.size) + assertNotSame(boston, ring.last()) + val expected = WGS84Geodesic.createInterpolatePoints(listOf(iceland, boston)) + assertSamePoints(expected.subList(1, expected.size - 1), ring.takeLast(expected.size - 2)) + } + + @Test + fun densifyPolygonRing_keepsClosedRingClosed() { + val closed = triangle + boston + assertSamePoints(WGS84Geodesic.createInterpolatePoints(closed), densifyPolygonRing(closed, geodesic = true)) + assertSamePoints(Planar.createInterpolatePoints(closed), densifyPolygonRing(closed, geodesic = false)) + } + + @Test + fun densifyPolygonRing_nonGeodesic_interpolatesClosingEdgeLinearly() { + val ring = densifyPolygonRing(triangle, geodesic = false) + assertTrue(same(boston, ring.first())) + assertEquals(Planar.createInterpolatePoints(triangle + boston).size - 1, ring.size) + val expected = Planar.createInterpolatePoints(listOf(iceland, boston)) + assertSamePoints(expected.subList(1, expected.size - 1), ring.takeLast(expected.size - 2)) + } + + @Test + fun unwrappedGeodesicFill_matchesOutline() { + val fill = buildUnwrappedPolygonRings(triangle, emptyList(), geodesic = true).outerRings.single() + assertSamePoints(outlineOf(triangle, true), fill) + val mid = WGS84Geodesic.interpolate(iceland, boston, 0.5) + val nearest = fill.minOf { hypot(it.latitude - mid.latitude, it.longitude - mid.longitude) } + assertTrue("nearest $nearest", nearest < 0.1) + } + + @Test + fun splitGeodesicFill_interpolatesClosingEdge() { + val rings = buildPolygonRings(triangle, emptyList(), geodesic = true).outerRings + assertEquals(1, rings.size) + assertSamePoints(outlineOf(triangle, true), rings.single()) + } + + /** + * geodesic=false の輪郭は閉じる辺も緯度経度で線形補間する(メルカトルではわずかに曲がる)。 + * 塗りも同じ点列であること。以前は閉じる辺だけ補間されず、メルカトル上の直線(弦)だった。 + */ + @Test + fun nonGeodesicFill_matchesOutline_includingClosingEdge() { + val unwrapped = buildUnwrappedPolygonRings(triangle, emptyList(), geodesic = false).outerRings.single() + assertSamePoints(outlineOf(triangle, false), unwrapped) + assertSamePoints(outlineOf(triangle, false), buildPolygonRings(triangle, emptyList(), geodesic = false).outerRings.single()) + + // 閉じる辺(アイスランド → ボストン)の緯度経度の中点が点列に含まれる(弦の上ではない)。 + val mid = GeoPoint.fromLatLong((iceland.latitude + boston.latitude) / 2, (iceland.longitude + boston.longitude) / 2) + val nearest = unwrapped.minOf { hypot(it.latitude - mid.latitude, it.longitude - mid.longitude) } + assertTrue("nearest $nearest", nearest < 0.1) + } + + @Test + fun geodesicHoles_interpolateClosingEdge() { + val outer = + listOf( + GeoPoint.fromLatLong(30.0, -80.0), + GeoPoint.fromLatLong(30.0, 10.0), + GeoPoint.fromLatLong(70.0, 10.0), + GeoPoint.fromLatLong(70.0, -80.0), + ) + val hole = triangle + val unwrapped = buildUnwrappedPolygonRings(outer, listOf(hole), geodesic = true) + assertSamePoints(outlineOf(hole, true), unwrapped.holeRings.single()) + assertSamePoints(outlineOf(outer, true), unwrapped.outerRings.single()) + assertSamePoints(outlineOf(hole, true), buildPolygonRings(outer, listOf(hole), geodesic = true).holeRings.single()) + } + + @Test + fun nonGeodesicHoles_interpolateClosingEdge() { + val outer = + listOf( + GeoPoint.fromLatLong(30.0, -80.0), + GeoPoint.fromLatLong(30.0, 10.0), + GeoPoint.fromLatLong(70.0, 10.0), + GeoPoint.fromLatLong(70.0, -80.0), + ) + val hole = triangle + val unwrapped = buildUnwrappedPolygonRings(outer, listOf(hole), geodesic = false) + assertSamePoints(outlineOf(hole, false), unwrapped.holeRings.single()) + assertSamePoints(outlineOf(outer, false), unwrapped.outerRings.single()) + assertSamePoints(outlineOf(hole, false), buildPolygonRings(outer, listOf(hole), geodesic = false).holeRings.single()) + } + + @Test + fun hitTest_followsGreatCircleOnClosingEdge() { + // 弦と大圏の間(北西へ膨らんだ部分)の点。 + val mid = WGS84Geodesic.interpolate(iceland, boston, 0.5) + val t = (mid.longitude - iceland.longitude) / (boston.longitude - iceland.longitude) + val chordLat = iceland.latitude + t * (boston.latitude - iceland.latitude) + val bulge = GeoPoint.fromLatLong((mid.latitude + chordLat) / 2, mid.longitude) + + val manager = PolygonManager() + val state = PolygonState(points = triangle, id = "g", geodesic = true) + manager.registerEntity(PolygonEntity(polygon = Unit, state = state)) + assertEquals("g", manager.find(bulge)?.state?.id) + + state.geodesic = false + assertNull(manager.find(bulge)) + } + + /** + * geodesic=false のタップ判定は生の頂点を緯度経度平面で判定する。閉じる辺は緯度経度の直線 + * (= 線形補間した塗り・輪郭と同じ線)になり、メルカトルの弦ではない。 + */ + @Test + fun nonGeodesicHitTest_followsLinearClosingEdge() { + val midLng = (iceland.longitude + boston.longitude) / 2 + val linearLat = (iceland.latitude + boston.latitude) / 2 + + fun merc(lat: Double) = ln(tan(PI / 4 + lat * PI / 360)) + val chordLat = (2 * atan(exp((merc(iceland.latitude) + merc(boston.latitude)) / 2)) - PI / 2) * 180 / PI + // メルカトルの弦は緯度経度の直線より北を通る。その間は塗りの外。 + assertTrue("chord $chordLat linear $linearLat", chordLat > linearLat + 0.5) + val between = GeoPoint.fromLatLong((chordLat + linearLat) / 2, midLng) + val inside = GeoPoint.fromLatLong(linearLat - 0.5, midLng) + + val manager = PolygonManager() + manager.registerEntity(PolygonEntity(polygon = Unit, state = PolygonState(points = triangle, id = "p", geodesic = false))) + assertNull(manager.find(between)) + assertEquals("p", manager.find(inside)?.state?.id) + } +} diff --git a/src/test/java/com/mapconductor/core/geometry/OverlayGeometryTest.kt b/src/test/java/com/mapconductor/core/geometry/OverlayGeometryTest.kt index 5008e33..74a54a1 100644 --- a/src/test/java/com/mapconductor/core/geometry/OverlayGeometryTest.kt +++ b/src/test/java/com/mapconductor/core/geometry/OverlayGeometryTest.kt @@ -74,7 +74,8 @@ class OverlayGeometryTest { val rings = buildPolygonRings(outer, listOf(hole), geodesic = true) assertEquals(1, rings.outerRings.size) assertEquals(1, rings.holeRings.size) - assertEquals(legacyInterpolate(hole, true), rings.holeRings.first()) + // geodesic の穴は閉じる辺(末尾 → 先頭)も補間する(GeodesicPolygonRingTest)。 + assertEquals(densifyPolygonRing(hole, geodesic = true).map { it.normalize() }, rings.holeRings.first()) } @Test diff --git a/src/test/java/com/mapconductor/core/map/ApplyStyleMutationsTest.kt b/src/test/java/com/mapconductor/core/map/ApplyStyleMutationsTest.kt new file mode 100644 index 0000000..281144d --- /dev/null +++ b/src/test/java/com/mapconductor/core/map/ApplyStyleMutationsTest.kt @@ -0,0 +1,269 @@ +package com.mapconductor.core.map + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * The body of every provider's mutation support, against a renderer that + * only records. + * + * Kept in step with `applyStyleMutations.test.mjs` on the web and + * `ApplyStyleMutationsTests` on iOS. + */ +class ApplyStyleMutationsTest { + private val calls = mutableListOf() + private val layers = mutableSetOf("roads", "labels") + private var refuse: String? = null + private var ready = true + + private val target = + object : StyleMutationTarget { + override val isReady: Boolean get() = ready + + override fun hasLayer(layerId: String) = layerId in layers + + override fun setPaint( + layerId: String, + key: String, + valueJson: String, + ) { + if (key == refuse) throw IllegalStateException("nope") + calls += "paint $layerId $key=$valueJson" + } + + override fun setLayout( + layerId: String, + key: String, + valueJson: String, + ) { + calls += "layout $layerId $key=$valueJson" + } + + override fun setFilter( + layerId: String, + filterJson: String, + ) { + calls += "filter $layerId=$filterJson" + } + + override fun setZoomRange( + layerId: String, + minZoom: Float, + maxZoom: Float, + ) { + calls += "zoom $layerId=$minZoom..$maxZoom" + } + + override fun addLayer( + layerId: String, + layerJson: String, + beforeId: String?, + ) { + calls += "add $layerId $layerJson before=$beforeId" + } + + override fun removeLayer(layerId: String) { + layers -= layerId + calls += "remove $layerId" + } + } + + @Test + fun setsPaintAndLayoutProperties() { + val unapplied = + applyStyleMutations( + target, + listOf( + StyleMutation.SetPaint("roads", "line-color", "\"#fff\"", "\"#888\""), + StyleMutation.SetLayout("labels", "visibility", "\"none\"", "null"), + ), + ) + + assertTrue(unapplied.isEmpty()) + assertEquals( + listOf("paint roads line-color=\"#fff\"", "layout labels visibility=\"none\""), + calls, + ) + } + + /** + * Every renderer takes both ends of a zoom range at once, so a mutation + * that changes one has to restate the other — and a layer that named + * neither gets the spec's own defaults. + */ + @Test + fun aZoomRangeRestatesBothEnds() { + applyStyleMutations( + target, + listOf(StyleMutation.SetZoomRange("roads", minZoom = 5.0, maxZoom = null, null, null)), + ) + assertEquals(listOf("zoom roads=5.0..24.0"), calls) + } + + /** + * A layer the style does not have is not a crash and not a silent pass: + * it comes back, and the caller says so. + */ + @Test + fun whatTheStyleHasNoLayerForComesBack() { + val unapplied = + applyStyleMutations( + target, + listOf( + StyleMutation.SetPaint("roads", "line-color", "\"#fff\"", "null"), + StyleMutation.SetPaint("nope", "line-color", "\"#fff\"", "null"), + ), + ) + assertEquals(1, unapplied.size) + assertEquals("nope", unapplied.single().layerId) + assertEquals("the good one still went through", 1, calls.size) + } + + /** One property the renderer rejects must not cost the other three hundred. */ + @Test + fun aThrowingPropertyIsReportedNotPropagated() { + refuse = "line-gradient" + val unapplied = + applyStyleMutations( + target, + listOf( + StyleMutation.SetPaint("roads", "line-gradient", "[]", "null"), + StyleMutation.SetPaint("roads", "line-color", "\"#fff\"", "null"), + ), + ) + assertEquals(1, unapplied.size) + assertEquals(listOf("paint roads line-color=\"#fff\""), calls) + } + + @Test + fun addsAndRemovesALayer() { + applyStyleMutations( + target, + listOf(StyleMutation.AddLayer("bg", """{"id":"bg","type":"background"}""", "roads")), + ) + assertEquals(listOf("""add bg {"id":"bg","type":"background"} before=roads"""), calls) + + calls.clear() + applyStyleMutations(target, listOf(StyleMutation.RemoveLayer("roads"))) + assertEquals(listOf("remove roads"), calls) + } + + /** + * Adding and removing go through whatever the layer is, every time. + * + * The renderer decides what to do about a layer that is already there, + * or already gone — only it can say, and on the MapTiler bridge it is + * the only one that keeps a record at all. Putting the whole set back + * after a style reload depends on this: a layer missing from the + * reloaded style must still be added, and `hasLayer` cannot be trusted + * to notice. + */ + @Test + fun addAndRemoveAreNotGuardedHere() { + val unapplied = + applyStyleMutations( + target, + listOf( + StyleMutation.AddLayer("roads", """{"id":"roads","type":"background"}""", null), + StyleMutation.RemoveLayer("gone"), + ), + ) + assertTrue(unapplied.isEmpty()) + assertEquals( + listOf("""add roads {"id":"roads","type":"background"} before=null""", "remove gone"), + calls, + ) + } + + /** + * スタイルがまだ無いときは「できなかった」ではなく「まだしていない」。 + * + * これを混同していたのが、読み込み中の地図に対して + * 「N adjustments were not applied: this map cannot set those properties」 + * と言っていた原因。しかも `UnsupportedPolicy.RELOAD` だと、そのまま + * 調整済みドキュメントを渡し直してしまう(=避けたかった再読み込み)。 + * ロードが終われば store が一式を入れ直すので、失われるものは無い。 + */ + @Test + fun `スタイルが無いあいだは何も報告しない`() { + ready = false + + val unapplied = + applyStyleMutations( + target, + listOf( + StyleMutation.SetPaint("roads", "line-color", "\"#fff\"", "null"), + StyleMutation.SetPaint("nope", "line-color", "\"#fff\"", "null"), + ), + ) + + assertEquals(emptyList(), unapplied) + assertEquals("触ってもいない", emptyList(), calls) + } + + /** 準備できたら、いつもどおり本当にできないものだけが返る。 */ + @Test + fun `準備できたあとは判定が戻る`() { + ready = false + applyStyleMutations(target, listOf(StyleMutation.SetPaint("nope", "line-color", "\"#fff\"", "null"))) + ready = true + + val unapplied = + applyStyleMutations(target, listOf(StyleMutation.SetPaint("nope", "line-color", "\"#fff\"", "null"))) + + assertEquals(1, unapplied.size) + } + + /** + * 既定は「常に準備できている」。外部のドライバが実装していなくても + * 以前と同じ挙動になる(=互換のための既定であって、推奨ではない)。 + */ + @Test + fun `isReady の既定は true`() { + val plain = + object : StyleMutationTarget { + override fun hasLayer(layerId: String) = false + + override fun setPaint( + layerId: String, + key: String, + valueJson: String, + ) = Unit + + override fun setLayout( + layerId: String, + key: String, + valueJson: String, + ) = Unit + + override fun setFilter( + layerId: String, + filterJson: String, + ) = Unit + + override fun setZoomRange( + layerId: String, + minZoom: Float, + maxZoom: Float, + ) = Unit + + override fun addLayer( + layerId: String, + layerJson: String, + beforeId: String?, + ) = Unit + + override fun removeLayer(layerId: String) = Unit + } + + assertTrue(plain.isReady) + assertEquals( + 1, + applyStyleMutations( + plain, + listOf(StyleMutation.SetPaint("roads", "line-color", "\"#fff\"", "null")), + ).size, + ) + } +} diff --git a/src/test/java/com/mapconductor/core/map/CameraPaddingEmulationTest.kt b/src/test/java/com/mapconductor/core/map/CameraPaddingEmulationTest.kt new file mode 100644 index 0000000..9e84bc2 --- /dev/null +++ b/src/test/java/com/mapconductor/core/map/CameraPaddingEmulationTest.kt @@ -0,0 +1,123 @@ +package com.mapconductor.core.map + +import com.mapconductor.core.InternalMapConductorApi +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.features.GeoPointInterface +import com.mapconductor.core.spherical.Spherical +import com.mapconductor.core.zoom.AbstractZoomAltitudeConverter +import org.junit.Assert.assertEquals +import org.junit.Test +import kotlin.math.cos +import kotlin.math.pow +import kotlin.math.sin +import kotlin.math.tan + +/** + * パディングのエミュレーションが、独立に書いたピンホールカメラの投影と一致することを確認する。 + * + * ios-sdk の `CameraPaddingEmulationTests`、js-sdk の `CameraPaddingEmulation.test.mjs` と同じ観点。 + */ +@OptIn(InternalMapConductorApi::class) +class CameraPaddingEmulationTest { + private val target = GeoPoint(latitude = 35.6812, longitude = 139.7671) + private val zoom = 15.0 + private val height = 800.0 + + private fun metersPerDp(latitude: Double) = + AbstractZoomAltitudeConverter.WEB_MERCATOR_INITIAL_MPP_256 * cos(Math.toRadians(latitude)) / 2.0.pow(zoom) + + /** + * カメラ中心 [center] から見た [point] の画面位置(中央からの dp、右・下が正)。 + * 地上の (前方, 右) をピンホールカメラで投影する。fov 0 は遠近なし。 + */ + private fun project( + center: GeoPointInterface, + point: GeoPointInterface, + tilt: Double, + heading: Double, + fov: Double, + ): Pair { + val d = Spherical.computeDistanceBetween(center, point) + val dir = Math.toRadians(Spherical.computeHeading(center, point) - heading) + val forward = d * cos(dir) + val right = d * sin(dir) + val mpp = metersPerDp(center.latitude) + val t = Math.toRadians(tilt) + if (fov == 0.0) return Pair(right / mpp, -forward * cos(t) / mpp) + val f = (height / 2) / tan(Math.toRadians(fov) / 2) + val distance = f * mpp + // カメラ座標: 光軸方向の奥行き z、画面下向き y。 + val z = distance + forward * sin(t) + val y = -forward * cos(t) + return Pair(f * right / z, f * y / z) + } + + private fun assertLandsAtPaddedCenter( + paddings: MapPaddings, + tilt: Double, + heading: Double, + fov: Double, + ) { + val center = + CameraPaddingEmulation.centerForTarget(target, zoom, tilt, heading, paddings, fov, height) + val (x, y) = project(center, target, tilt, heading, fov) + assertEquals("x tilt=$tilt heading=$heading fov=$fov", (paddings.left - paddings.right) / 2, x, 0.5) + assertEquals("y tilt=$tilt heading=$heading fov=$fov", (paddings.top - paddings.bottom) / 2, y, 0.5) + val back = CameraPaddingEmulation.targetForCenter(center, zoom, tilt, heading, paddings, fov, height) + assertEquals(target.latitude, back.latitude, 5e-6) + assertEquals(target.longitude, back.longitude, 5e-6) + } + + @Test + fun noPaddingKeepsTarget() { + val center = + CameraPaddingEmulation.centerForTarget(target, zoom, 60.0, 0.0, MapPaddings.Zeros, 36.87, height) + assertEquals(target.latitude, center.latitude, 0.0) + assertEquals(target.longitude, center.longitude, 0.0) + } + + @Test + fun topPaddingAtTiltZeroMovesCenterNorth() { + val center = + CameraPaddingEmulation.centerForTarget(target, zoom, 0.0, 0.0, MapPaddings(top = 300.0), 36.87, height) + val meters = Spherical.computeDistanceBetween(target, center) + assertEquals(150 * metersPerDp(target.latitude), meters, 0.05) + assertEquals(0.0, Spherical.computeHeading(target, center), 0.01) + } + + @Test + fun perspectiveLandsAtPaddedCenter() { + for (tilt in listOf(0.0, 30.0, 45.0, 60.0)) { + for (heading in listOf(0.0, 90.0, 225.0)) { + for (fov in listOf(36.87, 25.0, 32.2)) { + assertLandsAtPaddedCenter(MapPaddings(top = 300.0), tilt, heading, fov) + assertLandsAtPaddedCenter(MapPaddings(top = 120.0, left = 200.0, bottom = 40.0), tilt, heading, fov) + } + } + } + } + + @Test + fun orthographicLandsAtPaddedCenter() { + for (tilt in listOf(30.0, 60.0)) { + assertLandsAtPaddedCenter(MapPaddings(top = 300.0, right = 100.0), tilt, 45.0, 0.0) + } + } + + @Test + fun unknownFovFallsBackToFlat() { + val flat = + CameraPaddingEmulation.centerForTarget(target, zoom, 0.0, 0.0, MapPaddings(top = 300.0), null, height) + val tilted = + CameraPaddingEmulation.centerForTarget(target, zoom, 60.0, 0.0, MapPaddings(top = 300.0), null, height) + assertEquals(flat.latitude, tilted.latitude, 0.0) + } + + @Test + fun fovIsKeptByCopyAndIgnoredByEquals() { + val camera = MapCameraPosition(position = target, zoom = 10.0, fov = 36.87) + assertEquals(36.87, camera.copy(zoom = 11.0).fov!!, 0.0) + val withoutFov: MapCameraPositionInterface = MapCameraPosition(position = target, zoom = 10.0) + assertEquals(true, camera.equals(withoutFov)) + } +} diff --git a/src/test/java/com/mapconductor/core/map/CameraPositionResolveTest.kt b/src/test/java/com/mapconductor/core/map/CameraPositionResolveTest.kt new file mode 100644 index 0000000..a3060e2 --- /dev/null +++ b/src/test/java/com/mapconductor/core/map/CameraPositionResolveTest.kt @@ -0,0 +1,89 @@ +package com.mapconductor.core.map + +import com.mapconductor.core.features.GeoPoint +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * 未指定の zoom / bearing / tilt だけが現在のカメラから引き継がれ、 + * 明示された 0 はそのまま使われることを確認する。 + * + * ios-sdk の `CameraPositionResolveTests`、js-sdk の `CameraPositionResolve.test.mjs` と同じ観点。 + */ +class CameraPositionResolveTest { + private val tokyo = GeoPoint(latitude = 35.6812, longitude = 139.7671) + private val osaka = GeoPoint(latitude = 34.7025, longitude = 135.4959) + private val current = MapCameraPosition(position = tokyo, zoom = 12.0, bearing = 30.0, tilt = 45.0) + + private fun MapCameraPosition.zbt() = listOf(zoom, bearing, tilt) + + @Test + fun positionOnlyKeepsEverythingElse() { + val resolved = MapCameraPosition(position = osaka).resolvedOnto(current) + assertEquals(osaka.latitude, resolved.position.latitude, 0.0) + assertEquals(listOf(12.0, 30.0, 45.0), resolved.zbt()) + } + + @Test + fun explicitZeroIsHonoured() { + val resolved = + MapCameraPosition(position = osaka, zoom = 0.0, bearing = 0.0, tilt = 0.0) + .resolvedOnto(current) + assertEquals(listOf(0.0, 0.0, 0.0), resolved.zbt()) + } + + @Test + fun eachPropertyIsInheritedOnItsOwn() { + assertEquals( + listOf(0.0, 30.0, 45.0), + MapCameraPosition(position = osaka, zoom = 0.0).resolvedOnto(current).zbt(), + ) + assertEquals( + listOf(12.0, 0.0, 45.0), + MapCameraPosition(position = osaka, bearing = 0.0).resolvedOnto(current).zbt(), + ) + assertEquals( + listOf(12.0, 30.0, 0.0), + MapCameraPosition(position = osaka, tilt = 0.0).resolvedOnto(current).zbt(), + ) + } + + @Test + fun unsetReadsAsZeroBeforeResolving() { + val camera = MapCameraPosition(position = osaka) + assertEquals(0.0, camera.zoom, 0.0) + assertFalse(camera.isZoomSpecified) + assertFalse(camera.isBearingSpecified) + assertFalse(camera.isTiltSpecified) + assertTrue(MapCameraPosition.Default.isZoomSpecified) + } + + @Test + fun copyKeepsUnspecifiedUnlessGiven() { + assertFalse(MapCameraPosition(position = osaka).copy(position = tokyo).isZoomSpecified) + + val withZoom = MapCameraPosition(position = osaka).copy(zoom = 0.0) + assertTrue(withZoom.isZoomSpecified) + assertFalse(withZoom.isBearingSpecified) + } + + private class TestState( + initial: MapCameraPosition, + ) : MapViewState(initial) { + override val id: String = "test" + override var mapDesignType: String = "design" + } + + @Test + fun mapViewStateMergesUnsetPropertiesFromCurrentCamera() { + val state = TestState(current) + + state.moveCameraTo(MapCameraPosition(position = osaka, bearing = 0.0), null) + assertEquals(listOf(12.0, 0.0, 45.0), state.cameraPosition.zbt()) + + state.moveCameraTo(MapCameraPosition(position = osaka, zoom = 0.0), null) + assertEquals(0.0, state.cameraPosition.zoom, 0.0) + } +} diff --git a/src/test/java/com/mapconductor/core/map/MapViewHolderProjectedPointTest.kt b/src/test/java/com/mapconductor/core/map/MapViewHolderProjectedPointTest.kt new file mode 100644 index 0000000..221a22c --- /dev/null +++ b/src/test/java/com/mapconductor/core/map/MapViewHolderProjectedPointTest.kt @@ -0,0 +1,57 @@ +package com.mapconductor.core.map + +import androidx.compose.ui.geometry.Offset +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.features.GeoPointInterface +import com.mapconductor.core.projection.MapCoordinateSystem +import com.mapconductor.core.projection.ProjectedPoint +import com.mapconductor.core.projection.ProjectedUnit +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Test + +/** + * 投影座標の既定実装。上書きしないホルダは EPSG:3857 メートルを返す。 + */ +class MapViewHolderProjectedPointTest { + private class PlainHolder : MapViewHolderInterface { + override val mapView = Unit + override val map = Unit + + override fun toScreenOffset(position: GeoPointInterface): Offset? = null + } + + @Test + fun defaultCoordinateSystemIsWebMercator() { + val system = PlainHolder().coordinateSystem + assertEquals("EPSG:3857", system.code) + assertEquals(ProjectedUnit.Meters, system.unit) + assertEquals(MapCoordinateSystem.WebMercator, system) + } + + @Test + fun defaultProjectionIsEpsg3857Meters() { + // 東京駅。期待値は x = λ·a、y = a·ln(tan(π/4 + φ/2))(a = 6378137)。 + val point = PlainHolder().toProjectedPoint(GeoPoint(35.681236, 139.767125, 0.0)) + assertNotNull(point) + assertEquals(15558805.18, point!!.x, 0.01) + assertEquals(4256848.12, point.y, 0.01) + } + + @Test + fun defaultRoundTripReturnsTheSamePoint() { + val holder = PlainHolder() + val original = GeoPoint(-33.8688, 151.2093, 0.0) + val back = holder.fromProjectedPoint(holder.toProjectedPoint(original)!!) + assertNotNull(back) + assertEquals(original.latitude, back!!.latitude, 1e-9) + assertEquals(original.longitude, back.longitude, 1e-9) + } + + @Test + fun originMapsToNullIsland() { + val back = PlainHolder().fromProjectedPoint(ProjectedPoint(0.0, 0.0)) + assertEquals(0.0, back!!.latitude, 1e-12) + assertEquals(0.0, back.longitude, 1e-12) + } +} diff --git a/src/test/java/com/mapconductor/core/map/MapViewStateBaseTest.kt b/src/test/java/com/mapconductor/core/map/MapViewStateBaseTest.kt index 19a5e8e..73d519c 100644 --- a/src/test/java/com/mapconductor/core/map/MapViewStateBaseTest.kt +++ b/src/test/java/com/mapconductor/core/map/MapViewStateBaseTest.kt @@ -258,4 +258,31 @@ class MapViewStateBaseTest { assertTrue(controller.moved.isEmpty()) assertNull(state.getMapViewHolder()) } + + @Test + fun `破棄したコントローラを渡すと手放す`() { + // アプリが state を持ち続けても、壊した地図のコントローラ(と全オーバーレイ)を + // 抱えたままにしない。 + val controller = FakeController() + val state = TestState().apply { attach(controller) } + + state.detachController(controller) + + assertNull(state.getMapViewHolder()) + } + + @Test + fun `別のコントローラが接続済みなら古いものを渡しても外さない`() { + val old = FakeController() + val current = FakeController() + val state = TestState().apply { attach(old) } + state.attach(current) + + state.detachController(old) + + assertSame(current.holder, state.getMapViewHolder()) + current.moved.clear() + state.moveCameraTo(cameraAt(1.0, 2.0), durationMillis = 0) + assertEquals(1, current.moved.size) + } } diff --git a/src/test/java/com/mapconductor/core/map/MapViewStyleHostTest.kt b/src/test/java/com/mapconductor/core/map/MapViewStyleHostTest.kt new file mode 100644 index 0000000..ba35823 --- /dev/null +++ b/src/test/java/com/mapconductor/core/map/MapViewStyleHostTest.kt @@ -0,0 +1,251 @@ +package com.mapconductor.core.map + +import com.mapconductor.core.controller.BaseMapViewController +import com.mapconductor.core.features.GeoRectBounds +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Before +import org.junit.Test + +/** + * [MapViewStyleHost.apply] の決定表。 + * + * このクラスで実際に意味があるのは「いつ入れ直し、いつ入れ直さないか」だけで、 + * 残りはプロバイダへの受け渡しでしかない。そして一度その条件が逆になったまま + * 気付かれなかった:**同じキーで `update` を呼び**(再コンパイル → 診断 → + * state → 再コンポジション → 無限ループ。ユーザーには左下パネルのチラつきと + * して見えた)、**キーが変わったときは `update` を呼ばなかった**(毎回 + * 破棄して入れ直す。差分をコンパイルする設計の意味がなくなる)。 + * 両方とも「コンパイルは通り地図も描ける」種類の壊れ方なので、ここで表に + * して押さえる。 + * + * ios-sdk の `MapViewStyleHostTests`、js-sdk-core の `MapViewStyleHost.test.mjs` + * と 1 対 1 で対応する。 + */ +class MapViewStyleHostTest { + private val log = mutableListOf() + private lateinit var originalSink: MapDiagnostics.Sink + + @Before + fun setUp() { + originalSink = MapDiagnostics.sink + MapDiagnostics.sink = MapDiagnostics.Sink { log.add(it) } + } + + @After + fun tearDown() { + MapDiagnostics.sink = originalSink + } + + /** 何が呼ばれたかだけを記録するスタイル。 */ + private class RecordingStyle( + override val key: String, + private val calls: MutableList, + /** + * `update` が受けるかどうか。false なら呼び出し側は破棄して入れ直す。 + * 関数なのは、入れたあとに答えを変えられるようにするため(下の + * 「連続カウントは戻る」)。 + */ + private val takesUpdates: () -> Boolean = { true }, + ) : MapViewStyle { + override fun install(host: MapStyleHost): MapStyleInstallation { + calls.add("install($key)") + return object : MapStyleInstallation { + override fun dispose() { + calls.add("dispose($key)") + } + + override fun update(next: MapViewStyle): Boolean { + calls.add("update($key -> ${next.key})") + return takesUpdates() + } + } + } + } + + private val calls = mutableListOf() + + private fun host(): MapViewStyleHost = + MapViewStyleHost(MutableMapServiceRegistry(), NoController()) + + private fun style( + key: String, + takesUpdates: Boolean = true, + ) = RecordingStyle(key, calls) { takesUpdates } + + private fun style( + key: String, + takesUpdates: () -> Boolean, + ) = RecordingStyle(key, calls, takesUpdates) + + @Test + fun `最初の apply で入る`() { + host().apply(style("a")) + assertEquals(listOf("install(a)"), calls) + } + + /** + * キーが同じなら何もしない。これが逆になっていたのがチラつきの原因で、 + * 再コンパイルは無駄なだけでなく診断を再送し、それを描くアプリが state を + * 更新して再コンポジションを呼ぶ。 + */ + @Test + fun `キーが同じ apply は何も呼ばない`() { + val host = host() + host.apply(style("a")) + calls.clear() + + // 中身の同じ別インスタンス。インライン生成されたスタイルはこうなる。 + host.apply(style("a")) + host.apply(style("a")) + + assertEquals(emptyList(), calls) + } + + /** + * キーが変わったら、まず今入っているものに渡す。受けられたなら地図は + * ドキュメントを読み直さない — スライダーを動かして再読み込みが起きない + * のはこの 1 行のおかげ。 + */ + @Test + fun `キーが変わったら入れ直す前に update を試す`() { + val host = host() + host.apply(style("a")) + calls.clear() + + host.apply(style("b")) + + assertEquals(listOf("update(a -> b)"), calls) + } + + /** update が受けたなら、次は新しいキーが「同じ」の基準になる。 */ + @Test + fun `update が受けたキーは据え置かれる`() { + val host = host() + host.apply(style("a")) + host.apply(style("b")) + calls.clear() + + host.apply(style("b")) + + assertEquals(emptyList(), calls) + } + + @Test + fun `update を断られたら破棄して入れ直す`() { + val host = host() + host.apply(style("a", takesUpdates = false)) + calls.clear() + + host.apply(style("b", takesUpdates = false)) + + assertEquals(listOf("update(a -> b)", "dispose(a)", "install(b)"), calls) + } + + /** + * `update` を持たないスタイル(`MapStyleInstallation.of` が返すもの)は + * 既定で false。これが true 扱いになると、入れ替わっていないものに + * 新しいキーが付く。 + */ + @Test + fun `update を持たないスタイルは入れ直される`() { + val plain = + { key: String -> + object : MapViewStyle { + override val key = key + + override fun install(host: MapStyleHost): MapStyleInstallation { + calls.add("install($key)") + return MapStyleInstallation.of { calls.add("dispose($key)") } + } + } + } + val host = host() + host.apply(plain("a")) + calls.clear() + + host.apply(plain("b")) + + assertEquals(listOf("dispose(a)", "install(b)"), calls) + } + + /** 渡さなくなったら外す。スタイルが残した地図ではなく元の地図に戻る。 */ + @Test + fun `null は外す`() { + val host = host() + host.apply(style("a")) + calls.clear() + + host.apply(null) + + assertEquals(listOf("dispose(a)"), calls) + // 外したあとに同じキーが来たら、据え置きではなく入れ直し。 + calls.clear() + host.apply(style("a")) + assertEquals(listOf("install(a)"), calls) + } + + /** + * 毎回断られるのは正しいが遅い。原因はたいてい `remember` に入れていない + * ラスタライザなので、黙って遅くするのではなく言う。 + */ + @Test + fun `断られ続けたら診断を出す`() { + val host = host() + host.apply(style("k0", takesUpdates = false)) + repeat(5) { host.apply(style("k${it + 1}", takesUpdates = false)) } + + assertEquals(1, log.count { it.contains("refused") }) + assertEquals( + "直し方まで言う: identity 比較される値を作り直しているのが原因", + 1, + log.count { it.contains("remember") }, + ) + } + + /** + * 連続して断られたことだけが問題なので、1 回受かったら数え直す。 + * 入っているスタイル自身の答えを途中で変える必要があるため、ここだけ + * フラグ越しに答えさせる。 + */ + @Test + fun `update が受けたら連続カウントは戻る`() { + val host = host() + var takes = false + host.apply(style("k0") { takes }) + repeat(4) { host.apply(style("r$it") { takes }) } + takes = true + host.apply(style("ok") { takes }) + takes = false + repeat(4) { host.apply(style("s$it") { takes }) } + + assertEquals(emptyList(), log.filter { it.contains("refused") }) + } +} + +/** + * コントローラは [MapViewStyleHost] の判断に一切関与しない(使うのは + * `onStyleLoaded` / `upsertRaster` / `removeRaster` の受け渡しだけ)ので、 + * ここでは置けるだけの最小実装。 + */ +private class NoController : BaseMapViewController() { + override val holder get() = throw UnsupportedOperationException() + override val defaultCoroutine = CoroutineScope(Dispatchers.Unconfined) + override val mainCoroutine = defaultCoroutine + + override fun moveCamera(position: MapCameraPosition) = Unit + + override fun animateCamera( + position: MapCameraPosition, + duration: Long, + ) = Unit + + override fun fitBounds( + bounds: GeoRectBounds, + padding: Int, + ) = Unit + + override suspend fun clearOverlays() = Unit +} diff --git a/src/test/java/com/mapconductor/core/map/PartialPaddingsTest.kt b/src/test/java/com/mapconductor/core/map/PartialPaddingsTest.kt new file mode 100644 index 0000000..c3d7cad --- /dev/null +++ b/src/test/java/com/mapconductor/core/map/PartialPaddingsTest.kt @@ -0,0 +1,92 @@ +package com.mapconductor.core.map + +import com.mapconductor.core.features.GeoPoint +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotSame +import org.junit.Assert.assertSame +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * 省略した余白の辺だけが現在のカメラから引き継がれ、明示された 0 はそのまま使われることを確認する。 + * + * ios-sdk / js-sdk の同名テストと同じ観点。 + */ +class PartialPaddingsTest { + private val tokyo = GeoPoint(latitude = 35.6812, longitude = 139.7671) + private val current = + MapCameraPosition( + position = tokyo, + zoom = 12.0, + bearing = 30.0, + tilt = 45.0, + paddings = MapPaddings(10.0, 20.0, 30.0, 40.0), + ) + + private fun MapPaddingsInterface?.sides() = listOf(this!!.top, left, bottom, right) + + @Test + fun unsetSidesCopyFromCurrent() { + val resolved = + MapCameraPosition(position = tokyo, zoom = 12.0, bearing = 0.0, tilt = 0.0, paddings = MapPaddings(top = 300.0)) + .resolvedOnto(current) + assertEquals(listOf(300.0, 20.0, 30.0, 40.0), resolved.paddings.sides()) + assertTrue((resolved.paddings as MapPaddings).isFullySpecified) + } + + @Test + fun allUnsetCopiesAll() { + val resolved = MapCameraPosition(position = tokyo, paddings = MapPaddings()).resolvedOnto(current) + assertEquals(listOf(10.0, 20.0, 30.0, 40.0), resolved.paddings.sides()) + } + + @Test + fun explicitZeroIsHonoured() { + val resolved = + MapCameraPosition(position = tokyo, paddings = MapPaddings(top = 0.0, right = 0.0)).resolvedOnto(current) + assertEquals(listOf(0.0, 20.0, 30.0, 0.0), resolved.paddings.sides()) + } + + @Test + fun omittedPaddingsStillMeanZeros() { + val resolved = MapCameraPosition(position = tokyo).resolvedOnto(current) + assertEquals(listOf(0.0, 0.0, 0.0, 0.0), resolved.paddings.sides()) + } + + @Test + fun unresolvedReadsZeroAndKeepsFlags() { + val partial = MapPaddings(top = 300.0) + assertEquals(listOf(300.0, 0.0, 0.0, 0.0), partial.sides()) + assertTrue(partial.isTopSpecified) + assertFalse(partial.isLeftSpecified) + assertFalse(partial.isBottomSpecified) + assertFalse(partial.isRightSpecified) + assertSame(partial, MapPaddings.from(partial)) + val copied = MapCameraPosition(position = tokyo, paddings = partial).copy(zoom = 5.0) + assertFalse((copied.paddings as MapPaddings).isLeftSpecified) + } + + @Test + fun nullCurrentPaddingsFillWithZero() { + val noPaddings = MapCameraPosition(position = tokyo, paddings = null) + val resolved = MapCameraPosition(position = tokyo, paddings = MapPaddings(bottom = 50.0)).resolvedOnto(noPaddings) + assertEquals(listOf(0.0, 0.0, 50.0, 0.0), resolved.paddings.sides()) + } + + @Test + fun fastPathNeedsAllSides() { + val full = + MapCameraPosition(position = tokyo, zoom = 1.0, bearing = 0.0, tilt = 0.0, paddings = MapPaddings(1.0, 2.0, 3.0, 4.0)) + assertSame(full, full.resolvedOnto(current)) + val partial = MapCameraPosition(position = tokyo, zoom = 1.0, bearing = 0.0, tilt = 0.0, paddings = MapPaddings(top = 1.0)) + assertNotSame(partial, partial.resolvedOnto(current)) + } + + @Test + fun fourArgumentConstructorIsFullySpecified() { + assertTrue(MapPaddings(0.0, 0.0, 0.0, 0.0).isFullySpecified) + assertTrue(MapPaddings.Zeros.isFullySpecified) + assertTrue(MapPaddings(top = 1.0, left = 2.0, bottom = 3.0, right = 4.0).isFullySpecified) + } +} diff --git a/src/test/java/com/mapconductor/core/map/StyleMutationStoreTest.kt b/src/test/java/com/mapconductor/core/map/StyleMutationStoreTest.kt new file mode 100644 index 0000000..bcafea8 --- /dev/null +++ b/src/test/java/com/mapconductor/core/map/StyleMutationStoreTest.kt @@ -0,0 +1,123 @@ +package com.mapconductor.core.map + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * The two things a provider would otherwise have to remember on its own, + * and both of which look fine until they do not: a replaced set has to undo + * what it dropped, and a style load wipes everything that was applied. + */ +class StyleMutationStoreTest { + private val applied = mutableListOf() + + private fun store(unsupported: (StyleMutation) -> Boolean = { false }) = + StyleMutationStore { mutations -> + applied += mutations + mutations.filter(unsupported) + } + + private fun paint( + layer: String, + key: String, + value: String, + previous: String, + ) = StyleMutation.SetPaint(layer, key, value, previous) + + @Test + fun replacingASetPutsBackWhatTheNewOneNoLongerMentions() { + val store = store() + store.apply( + listOf( + paint("roads", "line-color", "\"#fff\"", "\"#888\""), + paint("water", "fill-color", "\"#000\"", "\"#a0c8f0\""), + ), + ) + applied.clear() + + // The second set drops the water rule entirely. + store.apply(listOf(paint("roads", "line-color", "\"#f00\"", "\"#888\""))) + + assertEquals( + "water goes back to the style's own colour, then roads take the new one", + listOf( + paint("water", "fill-color", "\"#a0c8f0\"", "\"#000\""), + paint("roads", "line-color", "\"#f00\"", "\"#888\""), + ), + applied, + ) + } + + /** + * The restore has to be sent before the new value, or a property that + * both sets touch would be put back to the style's value after being + * given its new one. + */ + @Test + fun restoresGoOutBeforeTheNewValues() { + val store = store() + store.apply(listOf(paint("a", "line-color", "\"#1\"", "\"#0\""))) + applied.clear() + store.apply(listOf(paint("b", "line-color", "\"#2\"", "\"#0\""))) + + assertEquals("a", applied.first().layerId) + assertEquals("b", applied.last().layerId) + } + + @Test + fun clearPutsEverythingBack() { + val store = store() + store.apply(listOf(paint("roads", "line-color", "\"#fff\"", "\"#888\""))) + applied.clear() + + store.clear() + + assertEquals(listOf(paint("roads", "line-color", "\"#888\"", "\"#fff\"")), applied) + assertTrue(store.applied.isEmpty()) + } + + /** + * A design change, a provider reloading, anything: the renderer comes + * back with the document's values and nothing that was applied over + * them. Without this the adjustment survives until the first basemap + * switch and then quietly stops. + */ + @Test + fun aStyleLoadPutsTheWholeSetOnAgain() { + val store = store() + val mutations = listOf(paint("roads", "line-color", "\"#fff\"", "\"#888\"")) + store.apply(mutations) + applied.clear() + + store.onStyleLoaded() + + assertEquals(mutations, applied) + } + + @Test + fun nothingAppliedMeansNothingToDoOnAStyleLoad() { + val store = store() + store.onStyleLoaded() + assertTrue(applied.isEmpty()) + } + + /** + * iOS MapLibre cannot set every spec key by name. The caller has to be + * told which ones, rather than being left to assume the map looks the + * way the rules asked. + */ + @Test + fun whatTheMapCouldNotDoComesBack() { + val store = store(unsupported = { (it as? StyleMutation.SetPaint)?.key == "line-gradient" }) + val failed = + store.apply( + listOf( + paint("roads", "line-color", "\"#fff\"", "\"#888\""), + paint("roads", "line-gradient", "[\"interpolate\"]", "null"), + ), + ) + assertEquals(1, failed.size) + assertEquals("line-gradient", (failed.single() as StyleMutation.SetPaint).key) + } +} diff --git a/src/test/java/com/mapconductor/core/marker/DefaultIconLabelPositionTest.kt b/src/test/java/com/mapconductor/core/marker/DefaultIconLabelPositionTest.kt new file mode 100644 index 0000000..628c979 --- /dev/null +++ b/src/test/java/com/mapconductor/core/marker/DefaultIconLabelPositionTest.kt @@ -0,0 +1,41 @@ +package com.mapconductor.core.marker + +import org.junit.Assert.assertEquals +import org.junit.Test + +/** + * `labelPosition` の読み取り。react-sdk の `DefaultIconLabelPosition.test.mjs`、 + * ios-sdk の `DefaultIconLabelPositionTests` と同じ規則を見る。 + */ +class DefaultIconLabelPositionTest { + private fun parse(value: String) = AbstractDefaultIcon.parseLabelPosition(value) + + @Test + fun defaultIsCenterCenter() { + assertEquals(0 to 0, parse(AbstractDefaultIcon.DEFAULT_LABEL_POSITION)) + } + + @Test + fun readsBothAxes() { + assertEquals(1 to 0, parse("right center")) + assertEquals(-1 to -1, parse("left top")) + assertEquals(0 to 1, parse("center bottom")) + } + + @Test + fun keywordOrderDoesNotMatter() { + assertEquals(parse("right top"), parse("top right")) + } + + @Test + fun singleKeywordLeavesOtherAxisCentered() { + assertEquals(1 to 0, parse("right")) + assertEquals(0 to -1, parse("top")) + } + + @Test + fun unknownWordsFallBackToCenter() { + assertEquals(0 to 0, parse(" middle ")) + assertEquals(1 to 1, parse(" RIGHT Bottom ")) + } +} diff --git a/src/test/java/com/mapconductor/core/marker/GeocellConformanceTest.kt b/src/test/java/com/mapconductor/core/marker/GeocellConformanceTest.kt new file mode 100644 index 0000000..2269b90 --- /dev/null +++ b/src/test/java/com/mapconductor/core/marker/GeocellConformanceTest.kt @@ -0,0 +1,107 @@ +package com.mapconductor.core.marker + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Assume.assumeTrue +import org.junit.Test +import java.io.File + +/** + * The geocell conformance test. + * + * ios-sdk and react-sdk read the same `geocell-vectors.txt`. The point is that + * all three name the same cell; what runs here is only this platform's half. + * + * Built like `ProjectionConformanceTest`. What differs is not the shape but + * **why the comparison is on strings.** The projection returns a Double + * everywhere, so rounding the digits is enough. A cell key does not: it is a + * `Long` here, an `Int64` on iOS and a `number` on the web, and that last one + * holds integers exactly only to 2^53 — its bitwise operators truncate to 32 + * bits entirely. Comparing the numbers could not tell a real disagreement from + * a difference in representation. Over `0123456789abcdef` the question does not + * arise. + */ +class GeocellConformanceTest { + private fun runVectors(): String { + val vectors = + requireNotNull(javaClass.classLoader?.getResourceAsStream("geocell-vectors.txt")) { + "geocell-vectors.txt not on the test classpath" + } + val out = StringBuilder() + vectors.bufferedReader().forEachLine { line -> + val row = line.trim() + if (row.isEmpty() || row.startsWith("#")) return@forEachLine + val parts = row.split("|") + when (parts[0]) { + "geocell" -> { + val text = MarkerGrid.geocell(parts[1].toDouble(), parts[2].toDouble(), parts[3].toInt()) + out.append("geocell|${parts[1]}|${parts[2]}|${parts[3]}|$text\n") + } + "level" -> { + val level = MarkerGrid.levelForSeparation(parts[1].toDouble()) + out.append("level|${parts[1]}|${level?.toString() ?: "none"}\n") + } + "cell" -> { + val level = parts[3].toInt() + val lat = MarkerGrid.latCell(parts[1].toDouble(), level) + val lon = MarkerGrid.lonCell(parts[2].toDouble(), level) + out.append("cell|${parts[1]}|${parts[2]}|${parts[3]}|$lat,$lon\n") + } + "qlevel" -> { + val level = MarkerGrid.queryLevel(parts[1].toDouble(), parts[2].toDouble()) + out.append("qlevel|${parts[1]}|${parts[2]}|$level\n") + } + "colwalk" -> { + val level = parts[3].toInt() + val span = MarkerGrid.eastwardSpan(parts[1].toDouble(), parts[2].toDouble()) + val (start, count) = MarkerGrid.columnWalk(parts[1].toDouble(), span, level) + out.append("colwalk|${parts[1]}|${parts[2]}|${parts[3]}|$start,$count\n") + } + "morton" -> { + val key = MarkerGrid.morton(parts[1].toLong(), parts[2].toLong(), parts[3].toInt()) + out.append("morton|${parts[1]}|${parts[2]}|${parts[3]}|$key\n") + } + else -> throw IllegalArgumentException("unknown op: ${parts[0]}") + } + } + return out.toString() + } + + @Test + fun vectorsAllRun() { + val actual = runVectors() + + // Written out for the cross-platform comparison. Not a by-product of + // the test — this is the product. + File(System.getProperty("java.io.tmpdir"), "geocell-actual.android.txt").writeText(actual) + assertTrue("no vector was processed", actual.lines().count { it.isNotBlank() } > 0) + } + + /** Absent until the three platforms agree and the answer is frozen. */ + @Test + fun matchesCanonicalIfPresent() { + val expected = javaClass.classLoader?.getResourceAsStream("geocell-expected.txt") + assumeTrue("no canonical file yet", expected != null) + assertEquals(expected!!.bufferedReader().readText(), runVectors()) + } + + /** + * A deeper cell's name extends a shallower one's. + * + * This is the condition that makes the index a hierarchy at all. Break it + * and "a coarse cell's markers are contiguous" stops holding, and range + * queries quietly drop markers. + */ + @Test + fun deeperCellsExtendShallowerOnes() { + for ((latitude, longitude) in listOf(35.681236 to 139.767125, -33.86882 to 151.20929, 0.0 to 0.0)) { + var previous = "" + for (characters in 1..10) { + val text = MarkerGrid.geocell(latitude, longitude, characters) + assertEquals(characters, text.length) + assertTrue("$text does not extend $previous", text.startsWith(previous)) + previous = text + } + } + } +} diff --git a/src/test/java/com/mapconductor/core/marker/MarkerDrawOrderTest.kt b/src/test/java/com/mapconductor/core/marker/MarkerDrawOrderTest.kt new file mode 100644 index 0000000..836f20b --- /dev/null +++ b/src/test/java/com/mapconductor/core/marker/MarkerDrawOrderTest.kt @@ -0,0 +1,131 @@ +package com.mapconductor.core.marker + +import com.mapconductor.core.InternalMapConductorApi +import com.mapconductor.core.features.GeoPoint +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +@OptIn(InternalMapConductorApi::class) +class MarkerDrawOrderTest { + private val tokyo = GeoPoint(35.7, 139.8, 0.0) + private val sydney = GeoPoint(-33.9, 151.2, 0.0) + + @Test + fun explicitZIndexBeatsUnspecifiedInBothHemispheres() { + for (point in listOf(tokyo, sydney, GeoPoint(-89.9, -179.9, 0.0), GeoPoint(89.9, 179.9, 0.0))) { + assertTrue(MarkerDrawOrder.of(1, point) > MarkerDrawOrder.of(null, point)) + assertTrue(MarkerDrawOrder.ofInt(1, point) > MarkerDrawOrder.ofInt(null, point)) + } + // 南半球の未指定でも、北の明示 1 を越えない。 + assertTrue(MarkerDrawOrder.of(1, tokyo) > MarkerDrawOrder.of(null, GeoPoint(-89.9, -179.9, 0.0))) + assertTrue(MarkerDrawOrder.ofInt(1, tokyo) > MarkerDrawOrder.ofInt(null, GeoPoint(-89.9, -179.9, 0.0))) + } + + @Test + fun zIndexIsPrimaryIncludingNegatives() { + assertTrue(MarkerDrawOrder.of(-1, sydney) < MarkerDrawOrder.of(0, tokyo)) + assertTrue(MarkerDrawOrder.of(2, tokyo) > MarkerDrawOrder.of(1, sydney)) + assertTrue(MarkerDrawOrder.ofInt(-1, sydney) < MarkerDrawOrder.ofInt(0, tokyo)) + } + + @Test + fun southThenWestBreakTies() { + val north = GeoPoint(35.7001, 139.8, 0.0) + val west = GeoPoint(35.7, 139.7999, 0.0) + assertTrue(MarkerDrawOrder.of(null, tokyo) > MarkerDrawOrder.of(null, north)) + assertTrue(MarkerDrawOrder.of(null, west) > MarkerDrawOrder.of(null, tokyo)) + assertTrue(MarkerDrawOrder.of(3, sydney) > MarkerDrawOrder.of(3, tokyo)) + // Float にしても数メートルの緯度差は残る(Google Maps は Float で受ける)。 + val tenMetersSouth = GeoPoint(35.7 - 0.0001, 139.8, 0.0) + assertTrue(MarkerDrawOrder.of(null, tenMetersSouth).toFloat() > MarkerDrawOrder.of(null, tokyo).toFloat()) + assertTrue(MarkerDrawOrder.ofInt(null, sydney) > MarkerDrawOrder.ofInt(null, tokyo)) + } + + @Test + fun tiebreakStaysBelowHalf() { + val extreme = GeoPoint(-90.0, -180.0, 0.0) + assertTrue(MarkerDrawOrder.of(0, extreme) < 0.5) + assertTrue(MarkerDrawOrder.of(0, GeoPoint(90.0, 180.0, 0.0)) >= 0.0) + } + + // ---- 地図の向き(heading)に合わせた並び ---- + + private val north = GeoPoint(35.71, 139.8, 0.0) + private val south = GeoPoint(35.69, 139.8, 0.0) + private val east = GeoPoint(35.7, 139.81, 0.0) + private val west = GeoPoint(35.7, 139.79, 0.0) + + private fun inFront( + a: GeoPoint, + b: GeoPoint, + heading: Double, + origin: Double = 139.8, + ): Boolean = MarkerDrawOrder.of(null, a, heading, origin) > MarkerDrawOrder.of(null, b, heading, origin) + + @Test + fun headingZeroKeepsNorthUpOrder() { + val points = listOf(tokyo, sydney, north, south, east, west, GeoPoint(60.0, -170.0, 0.0), GeoPoint(-10.0, 20.0, 0.0)) + for (a in points) { + for (b in points) { + if (a == b) continue + assertEquals( + "$a vs $b", + MarkerDrawOrder.of(null, a) > MarkerDrawOrder.of(null, b), + MarkerDrawOrder.of(null, a, 0.0, 0.0) > MarkerDrawOrder.of(null, b, 0.0, 0.0), + ) + } + } + } + + @Test + fun lowerOnScreenIsInFrontAtEveryHeading() { + // 0°: 南が画面の下。 + assertTrue(inFront(south, north, 0.0)) + assertTrue(inFront(west, east, 0.0)) + // 90°(画面の上が東): 西が画面の下。 + assertTrue(inFront(west, east, 90.0)) + // 同じ経度の南北は画面の同じ高さに並ぶ。左(北)が手前。 + assertTrue(inFront(north, south, 90.0)) + // 180°: 北が画面の下。 + assertTrue(inFront(north, south, 180.0)) + // 270°(画面の上が西): 東が画面の下。 + assertTrue(inFront(east, west, 270.0)) + assertTrue(inFront(south, north, 270.0)) + } + + @Test + fun zIndexDominatesAtEveryHeading() { + for (heading in listOf(0.0, 45.0, 90.0, 135.0, 180.0, 270.0, 359.0)) { + for (a in listOf(north, south, east, west, sydney)) { + for (b in listOf(north, south, east, west, sydney)) { + assertTrue(MarkerDrawOrder.of(1, a, heading, 139.8) > MarkerDrawOrder.of(null, b, heading, 139.8)) + assertTrue(MarkerDrawOrder.ofInt(1, a, heading, 139.8) > MarkerDrawOrder.ofInt(null, b, heading, 139.8)) + val v = MarkerDrawOrder.of(0, a, heading, 139.8) + assertTrue(v >= 0.0 && v < 0.5) + } + } + } + } + + @Test + fun antimeridianPairOrdersAcrossTheSeam() { + // 日付変更線の両側。179.99E は 179.99W の西隣。 + val westOfSeam = GeoPoint(0.0, 179.99, 0.0) + val eastOfSeam = GeoPoint(0.0, -179.99, 0.0) + // 90°(画面の上が東)では西が手前。 + assertTrue(inFront(westOfSeam, eastOfSeam, 90.0, origin = 180.0)) + assertTrue(inFront(eastOfSeam, westOfSeam, 270.0, origin = 180.0)) + } + + @Test + fun frameChangesOnlyOnBearingOrFarOrigin() { + val f = MarkerDrawOrder.Frame(10.0, 139.0) + assertFalse(MarkerDrawOrder.Frame(10.2, 150.0).differsEnoughFrom(f)) + assertTrue(MarkerDrawOrder.Frame(10.6, 139.0).differsEnoughFrom(f)) + assertTrue(MarkerDrawOrder.Frame(359.9, 139.0).differsEnoughFrom(MarkerDrawOrder.Frame(0.5, 139.0))) + assertFalse(MarkerDrawOrder.Frame(359.9, 139.0).differsEnoughFrom(MarkerDrawOrder.Frame(0.1, 139.0))) + assertTrue(MarkerDrawOrder.Frame(10.0, -100.0).differsEnoughFrom(f)) + } +} diff --git a/src/test/java/com/mapconductor/core/marker/MarkerGridIndexTest.kt b/src/test/java/com/mapconductor/core/marker/MarkerGridIndexTest.kt new file mode 100644 index 0000000..14499b5 --- /dev/null +++ b/src/test/java/com/mapconductor/core/marker/MarkerGridIndexTest.kt @@ -0,0 +1,493 @@ +package com.mapconductor.core.marker + +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.features.GeoRectBounds +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 + +/** + * [MarkerGridIndex] must answer exactly what a scan would. + * + * The index packs a cell key and an array position into one Long and reads them + * back with shifts and masks, so an off-by-one in the bit layout or in a range + * bound does not throw — it quietly drops markers. Every test here is the same + * shape: ask the index, ask brute force, demand the same set. + */ +class MarkerGridIndexTest { + private fun entity( + id: Int, + latitude: Double, + longitude: Double, + ): MarkerEntityInterface = + MarkerEntity( + marker = id, + state = MarkerState(position = GeoPoint.fromLatLong(latitude, longitude), id = "$id"), + ) + + /** A deterministic spread, so a failure is reproducible. */ + private fun scatter( + count: Int, + latitude: Double, + longitude: Double, + spread: Double, + ): List> { + var seed = 0x2545F4914F6CDD1DuL + + fun next(): Double { + seed = seed * 6364136223846793005uL + 1442695040888963407uL + return (seed shr 11).toDouble() / (1L shl 53).toDouble() + } + return (0 until count).map { index -> + entity( + index, + latitude + (next() - 0.5) * spread, + longitude + (next() - 0.5) * spread, + ) + } + } + + private fun ids(entities: Collection>): Set = + entities.map { it.state.id }.toSet() + + private fun bounds( + south: Double, + west: Double, + north: Double, + east: Double, + ): GeoRectBounds = + GeoRectBounds( + southWest = GeoPoint.fromLatLong(south, west), + northEast = GeoPoint.fromLatLong(north, east), + ) + + @Test + fun boundsQueryMatchesBruteForce() { + val markers = scatter(5000, 35.68, 139.76, 0.6) + val index = MarkerGridIndex { markers } + + // A box inside one cell, one spanning several, one wider than the data, + // and one over empty ground — the last because an index that returns + // nothing is right here and wrong everywhere else. + for (box in listOf( + bounds(35.6812, 139.7612, 35.6814, 139.7614), + bounds(35.68, 139.76, 35.69, 139.77), + bounds(35.0, 139.0, 36.5, 140.5), + bounds(10.0, 100.0, 11.0, 101.0), + )) { + val expected = ids(markers.filter { box.contains(it.state.position) }) + assertEquals("grid disagreed with a scan", expected, ids(index.inBounds(box))) + } + + // The middle two have to be carrying markers, or the comparison above is + // only proving that two empty sets match. + assertFalse(index.inBounds(bounds(35.68, 139.76, 35.69, 139.77)).isEmpty()) + assertEquals(markers.size, index.inBounds(bounds(35.0, 139.0, 36.5, 140.5)).size) + } + + /** + * A box crossing 180° has its east corner west of its west one. + * + * The first version walked `lonFrom..lonTo` straight, which is an empty + * range in Kotlin and a trap in Swift. Fiji and the Chathams are real + * places, and a map centred there is a reversed box every frame. + */ + @Test + fun boundsQueryCrossesTheAntimeridian() { + val markers = + listOf( + entity(0, -18.0, 179.9), + entity(1, -18.0, -179.9), + entity(2, -18.0, 178.0), + entity(3, -18.0, 0.0), + ) + scatter(3000, -18.0, 179.95, 0.4) + + val index = MarkerGridIndex { markers } + val box = bounds(-18.5, 179.5, -17.5, -179.5) + val expected = ids(markers.filter { box.contains(it.state.position) }) + + assertTrue("the box should hold the marker just west of 180", expected.contains("0")) + assertTrue("and the one just east of it", expected.contains("1")) + assertEquals(expected, ids(index.inBounds(box))) + } + + /** + * The thinned query may drop markers, but only ones it was told are + * interchangeable — and never a whole cell. + * + * A caller asks for this when it is about to keep one marker per cell of + * its own anyway. What it must not get back is a hole: a cell holding + * markers inside the bounds that returns nothing, which on a map is a patch + * of the city with no trees in it and no error anywhere. + */ + @Test + fun thinnedQueryKeepsOneMarkerFromEveryCellItCovers() { + val markers = scatter(60000, 35.68, 139.76, 0.4) + val index = MarkerGridIndex { markers } + val box = bounds(35.60, 139.68, 35.76, 139.84) + + val thinned = index.inBoundsThinned(box, minSeparationDegrees = 0.005) + assertNotNull("0.005 degrees is coarser than a cell, so this must be answered", thinned) + val kept = thinned!! + + val inside = markers.filter { box.contains(it.state.position) } + assertTrue("the box should hold something to compare", inside.size > 1000) + + // The level the index picks, worked out here the same way. 0.005 degrees + // gives level 16, an even level, so the cell has a whole-character name + // of 9 characters and can be compared as a string. + assertEquals(16L, MarkerGrid.levelForSeparation(0.005)!!.toLong()) + + fun cellOf(entity: MarkerEntityInterface): String = + MarkerGrid.geocell( + entity.state.position.latitude, + entity.state.position.longitude, + characters = 9, + ) + + // Every cell holding something inside the box has to be represented. + // Markers from outside the box are fine and expected: a cell's winner + // is chosen without reference to the box, so a cell on the edge can be + // represented by a marker just outside it. Not trimming those is what + // makes neighbouring tiles agree — see `MarkerTileSeamTest`. + assertTrue( + "some populated cell returned no representative", + kept.map(::cellOf).toSet().containsAll(inside.map(::cellOf).toSet()), + ) + val outside = kept.count { !box.contains(it.state.position) } + assertTrue( + "more markers outside the box than one edge cell can explain", + outside < kept.size * 0.15, + ) + assertEquals("more than one from some cell", kept.map(::cellOf).toSet().size, kept.size) + // The box is 0.16 degrees a side, so at level 16 it spans about 3,400 + // square cells of 0.00275 degrees and holds around 9,600 of these + // markers — nearly three to a cell. Without this the assertions above + // would still pass on data too sparse to thin, proving nothing. + assertTrue("the data is too sparse to be exercising thinning", kept.size * 2 < inside.size) + } + + /** + * Cells coarser than the caller's separation would thin more than asked. + * + * While the grid was flat that floor was 0.005 degrees. Now that it is a + * hierarchy the floor is the bottom level — 0.000687 degrees on a side — + * and anything coarser is answered by picking a level. That difference is + * what makes thinning work at the deeper zooms. + */ + @Test + fun thinnedQueryDeclinesWhenItsCellsAreTooCoarse() { + val index = MarkerGridIndex { scatter(2000, 35.68, 139.76, 0.4) } + val box = bounds(35.6, 139.7, 35.7, 139.8) + assertNull(index.inBoundsThinned(box, 0.0005)) + assertNotNull( + "0.001 degrees is coarser than the bottom level, so a level can be chosen", + index.inBoundsThinned(box, 0.001), + ) + } + + /** The wrap the plain query learned has to hold here too. */ + @Test + fun thinnedQueryCrossesTheAntimeridian() { + val markers = + listOf( + entity(0, -18.0, 179.99), + entity(1, -18.0, -179.99), + entity(2, -18.0, 178.0), + ) + val index = MarkerGridIndex { markers } + val kept = index.inBoundsThinned(bounds(-18.5, 179.5, -17.5, -179.5), 0.01) + assertNotNull(kept) + assertEquals(setOf("0", "1"), ids(kept!!)) + } + + @Test + fun nearestMatchesBruteForce() { + val markers = scatter(5000, 35.68, 139.76, 0.6) + val index = MarkerGridIndex { markers } + + for (point in listOf( + GeoPoint.fromLatLong(35.68, 139.76), + GeoPoint.fromLatLong(35.4, 139.5), + GeoPoint.fromLatLong(36.0, 140.1), + )) { + val expected = markers.minByOrNull { squared(it, point) } + assertEquals(expected?.state?.id, index.nearest(point)?.state?.id) + } + } + + /** + * Beyond the rings the index searches it falls back to a scan rather than + * returning nothing — the answer still has to be right, just slower. + */ + @Test + fun nearestFallsBackWhenNothingIsClose() { + val index = MarkerGridIndex { listOf(entity(0, 35.0, 139.0)) } + assertEquals("0", index.nearest(GeoPoint.fromLatLong(-35.0, -70.0))?.state?.id) + } + + @Test + fun emptyIndexHasNoNearest() { + val index = MarkerGridIndex { emptyList() } + assertNull(index.nearest(GeoPoint.fromLatLong(35.0, 139.0))) + } + + /** The index borrows the manager's markers, so a change has to be seen. */ + @Test + fun invalidateShowsLaterMarkers() { + val markers = mutableListOf(entity(0, 35.0, 139.0)) + val index = MarkerGridIndex { markers } + val box = bounds(34.9, 138.9, 35.1, 139.1) + assertEquals(1, index.inBounds(box).size) + + markers.add(entity(1, 35.001, 139.001)) + assertEquals("a stale index should stay stale until told", 1, index.inBounds(box).size) + + index.invalidate() + assertEquals(2, index.inBounds(box).size) + } + + /** + * Changes are applied to the built index, not rebuilt from the collection. + * + * The index is queried first so every change lands on a built index, and + * the collection counts how often it is read: a rebuild reads it, applying + * a change does not. After every kind of change the answers still have to + * be a scan's — a slot left pointing at a marker that went, or an entry + * left in the cell a marker moved out of, does not fail loudly; it returns + * a marker that is not there. + */ + @Test + fun changesAreAppliedWithoutARebuild() { + val markers = scatter(5000, 35.68, 139.76, 0.6).toMutableList() + var reads = 0 + val index = + MarkerGridIndex { + reads++ + markers + } + val boxes = + listOf( + bounds(35.6812, 139.7612, 35.6814, 139.7614), + bounds(35.68, 139.76, 35.69, 139.77), + bounds(35.6, 139.6, 35.8, 139.9), + bounds(35.0, 139.0, 36.5, 140.5), + ) + val probes = + listOf( + GeoPoint.fromLatLong(35.68, 139.76), + GeoPoint.fromLatLong(35.5, 139.6), + GeoPoint.fromLatLong(35.9, 140.0), + ) + + fun assertMatchesScan(label: String) { + // By identity: a replaced marker has the same id as the one it replaced. + val live = markers.toSet() + for ((at, box) in boxes.withIndex()) { + val expected = ids(markers.filter { box.contains(it.state.position) }) + val found = index.inBounds(box) + assertEquals("$label, box $at", expected, ids(found)) + assertEquals("$label, box $at: a marker twice", expected.size, found.size) + assertTrue("$label, box $at: a replaced object", found.all { it in live }) + } + for (point in probes + markers.take(20).map { it.state.position as GeoPoint }) { + val best = markers.minOf { squared(it, point) } + assertEquals("$label, nearest", best, squared(index.nearest(point)!!, point), 0.0) + } + val box = bounds(35.60, 139.68, 35.76, 139.84) + val kept = index.inBoundsThinned(box, 0.005)!! + assertTrue("$label: thinning returned a marker that left", kept.all { it in live }) + + fun cellOf(entity: MarkerEntityInterface): String = + MarkerGrid.geocell(entity.state.position.latitude, entity.state.position.longitude, characters = 9) + val inside = markers.filter { box.contains(it.state.position) }.map(::cellOf).toSet() + assertTrue("$label: a populated cell went unrepresented", kept.map(::cellOf).toSet().containsAll(inside)) + } + + assertMatchesScan("built") + assertEquals(1, reads) + + var seed = 99L + + fun next(): Double { + seed = seed * 6364136223846793005L + 1442695040888963407L + return (seed ushr 11).toDouble() / (1L shl 53).toDouble() + } + + fun anywhere() = GeoPoint.fromLatLong(35.38 + next() * 0.6, 139.46 + next() * 0.6) + var nextId = 10_000 + repeat(5) { round -> + repeat(200) { + when ((next() * 5).toInt()) { + // A new marker. + 0 -> { + val position = anywhere() + val added = entity(nextId++, position.latitude, position.longitude) + markers.add(added) + index.add(added) + } + // A marker leaves. + 1 -> { + val gone = markers.removeAt((next() * markers.size).toInt()) + index.remove(gone) + } + // Replaced by a new object in the same place: an icon change. + 2 -> { + val at = (next() * markers.size).toInt() + val old = markers[at] + val replacement = + entity(old.state.id.toInt(), old.state.position.latitude, old.state.position.longitude) + markers[at] = replacement + index.replace(old, replacement) + } + // Replaced by a new object somewhere else. + 3 -> { + val at = (next() * markers.size).toInt() + val old = markers[at] + val position = anywhere() + val moved = entity(old.state.id.toInt(), position.latitude, position.longitude) + markers[at] = moved + index.replace(old, moved) + } + // Moved in place, as a drag does, then reported. + else -> { + val dragged = markers[(next() * markers.size).toInt()] + dragged.state.position = anywhere() + index.replace(dragged, dragged) + } + } + } + assertMatchesScan("round $round") + } + assertEquals("a change was applied by rebuilding", 1, reads) + } + + /** + * A cell whose representative left is still represented. + * + * The thinned query takes the last entry of a cell's run. A marker that + * leaves empties its slot but keeps its entry until the next merge, and + * with nothing added since, there is no merge: the query has to step back + * past it to the one before, or the cell drops out of the map. + */ + @Test + fun thinnedQuerySkipsAMarkerThatLeft() { + val first = entity(0, 35.68, 139.76) + val second = entity(1, 35.68, 139.76) + val markers = mutableListOf(first, second) + val index = MarkerGridIndex { markers } + val box = bounds(35.67, 139.75, 35.69, 139.77) + assertEquals(listOf(second), index.inBoundsThinned(box, 0.01)) + + markers.remove(second) + index.remove(second) + assertEquals(listOf(first), index.inBoundsThinned(box, 0.01)) + } + + /** A marker the index cannot find makes it rebuild rather than trust itself. */ + @Test + fun removingAnUnknownMarkerRebuilds() { + val markers = scatter(1000, 35.68, 139.76, 0.6).toMutableList() + var reads = 0 + val index = + MarkerGridIndex { + reads++ + markers + } + val box = bounds(35.0, 139.0, 36.5, 140.5) + assertEquals(markers.size, index.inBounds(box).size) + + index.remove(entity(99_999, 35.68, 139.76)) + assertFalse(index.isBuilt) + assertEquals(markers.size, index.inBounds(box).size) + assertEquals(2, reads) + } + + /** Once half the slots are empty, a rebuild compacts them. */ + @Test + fun manyRemovalsCompactByRebuilding() { + val markers = scatter(20_000, 35.68, 139.76, 0.6).toMutableList() + var reads = 0 + val index = + MarkerGridIndex { + reads++ + markers + } + val box = bounds(35.0, 139.0, 36.5, 140.5) + index.inBounds(box) + + repeat(12_000) { index.remove(markers.removeAt(markers.size - 1)) } + assertEquals(ids(markers), ids(index.inBounds(box))) + assertEquals(2, reads) + } + + private fun squared( + entity: MarkerEntityInterface, + point: GeoPoint, + ): Double { + val deltaLat = entity.state.position.latitude - point.latitude + val deltaLon = entity.state.position.longitude - point.longitude + return deltaLat * deltaLat + deltaLon * deltaLon + } + + /** + * Whatever shape the box is, the index has to answer what a scan answers. + * + * Square boxes alone never reach the new level choice's **per-axis cap** — + * the path a very flat band or a very narrow column takes. Get that wrong + * and nothing on the map changes except that queries of that shape quietly + * drop markers. + * + * The near-global box is here because column indices fold: the column + * holding 180 and the one holding -180 are the same, so taking the end of + * the walk from the east corner covers a single column. See + * `MarkerGrid.columnWalk`. + * + * Pairs with ios-sdk's `testBoundsQueryMatchesBruteForceForEveryShapeOfBox` + * and react-sdk's test of the same name. + */ + @Test + fun boundsQueryMatchesBruteForceForEveryShapeOfBox() { + // The second group's ids are shifted. `scatter` numbers from zero every + // time, so adding them straight makes ids collide, and `ids()` folds two + // different markers into one — the index could return duplicates and the + // sets would still agree. + val near = scatter(30000, 35.68, 139.76, 0.8) + val far = + scatter(10000, -18.0, 179.95, 0.6).map { + entity(it.state.id.toInt() + 30000, it.state.position.latitude, it.state.position.longitude) + } + val markers = near + far + val index = MarkerGridIndex { markers } + + var nonEmpty = 0 + val boxes = + listOf( + // Tile-sized, from z=14 down to z=9. + bounds(35.6800, 139.7600, 35.6946, 139.7820), + bounds(35.6000, 139.6000, 35.7000, 139.8000), + bounds(35.2000, 139.2000, 36.2000, 140.2000), + // A very flat band and a very narrow column. Area alone cannot + // choose a level for either. + bounds(35.6790, 139.0000, 35.6810, 140.5000), + bounds(35.0000, 139.7590, 36.4000, 139.7610), + // Nearly the whole globe. + bounds(-85.0, -179.9, 85.0, 179.9), + // Across the antimeridian. + bounds(-18.5, 179.5, -17.5, -179.5), + // Empty ground: the one box where returning nothing is right. + bounds(10.0, 100.0, 11.0, 101.0), + ) + for ((at, box) in boxes.withIndex()) { + val expected = ids(markers.filter { box.contains(it.state.position) }) + val found = index.inBounds(box) + assertEquals("box $at: the grid disagreed with a scan", expected, ids(found)) + assertEquals("box $at: returned the same marker twice", expected.size, found.size) + if (expected.isNotEmpty()) nonEmpty++ + } + assertEquals("only comparing empty sets to empty sets", 7, nonEmpty) + } +} diff --git a/src/test/java/com/mapconductor/core/marker/MarkerHitTestTest.kt b/src/test/java/com/mapconductor/core/marker/MarkerHitTestTest.kt index fb89978..e104f6d 100644 --- a/src/test/java/com/mapconductor/core/marker/MarkerHitTestTest.kt +++ b/src/test/java/com/mapconductor/core/marker/MarkerHitTestTest.kt @@ -1,5 +1,6 @@ package com.mapconductor.core.marker +import androidx.compose.ui.geometry.Offset import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Test @@ -95,3 +96,69 @@ class MarkerHitTestTest { assertFalse(centered(0.0, 24.0 + tolerance + 0.5)) } } + +/** + * [MarkerHitPick.pickIndex] の選び方。ios-sdk の `MarkerHitTestTests`、react-sdk の + * `MarkerHitPick.test.mjs` と同じ観点を見る。 + */ +@OptIn(com.mapconductor.core.InternalMapConductorApi::class) +class MarkerHitTestPickTest { + private val tolerance = 14.0 + + private fun rect( + x: Float, + y: Float, + width: Double = 48.0, + height: Double = 48.0, + anchorX: Double = 0.5, + ) = MarkerHitPick.ScreenRect(Offset(x, y), width, height, anchorX, 1.0) + + @Test + fun iconUnderTheFingerBeatsANearerTip() { + // labelled: 先端 (0, 100)、ラベルを右へ伸ばして幅 200(矩形 x -24..176, y 52..100)。 + // nearTip: 先端 (150, 70) でタップ点にずっと近いが、矩形 (126..174, 22..70) はタップ点に届かない。 + // タップ (150, 80) は labelled のラベルの上なので、先端の近さに関係なく labelled が選ばれる。 + val labelled = rect(0f, 100f, width = 200.0, anchorX = 0.12) + val nearTip = rect(150f, 70f) + assertTrue(MarkerHitPick.pickIndex(Offset(150f, 80f), listOf(nearTip, labelled), tolerance) == 1) + } + + @Test + fun frontmostWinsWhenTwoIconsOverlap() { + val back = rect(100f, 100f) + val front = rect(100f, 120f) + assertTrue(MarkerHitPick.pickIndex(Offset(100f, 90f), listOf(back, front), tolerance) == 1) + } + + @Test + fun toleranceOnlyWhenNothingIsUnderTheFinger() { + val far = rect(100f, 100f) + val near = rect(140f, 100f) + // どちらの矩形にも入らないが、許容範囲には両方入る点。アンカーの近い方。 + val touch = Offset(170f, 105f) + assertTrue(MarkerHitPick.pickIndex(touch, listOf(far, near), 40.0) == 1) + assertTrue(MarkerHitPick.pickIndex(Offset(400f, 400f), listOf(far, near), tolerance) == null) + } + + /** + * A projection that rounds to whole pixels (ArcGIS's 3D SceneView does): zoomed out, + * 1e-4° is under a pixel, and the scale must still be measured. Without that the + * search area could not be made and no marker tap was recognised. + */ + @Test + fun searchBoundsWorksWithAProjectionRoundedToWholePixels() { + val worldPx = 512.0 * Math.pow(2.0, 9.0) // zoom 9 + fun project(p: com.mapconductor.core.features.GeoPointInterface): Offset { + val x = (p.longitude + 180.0) / 360.0 * worldPx + val s = Math.sin(Math.toRadians(p.latitude)) + val y = (0.5 - Math.log((1 + s) / (1 - s)) / (4 * Math.PI)) * worldPx + return Offset(Math.round(x).toFloat(), Math.round(y).toFloat()) + } + val tap = com.mapconductor.core.features.GeoPoint(21.31, -157.86) + val bounds = MarkerHitPick.searchBounds(tap, project(tap), ::project, density = 2.0) + assertTrue("bounds were not made", bounds != null) + // 256 dp at density 2 is 512 px; at zoom 9 (728 px a degree) that is about 0.70° each way. + val halfLon = (bounds!!.northEast!!.longitude - bounds.southWest!!.longitude) / 2 + assertTrue("half width $halfLon", halfLon in 0.63..0.77) + } +} diff --git a/src/test/java/com/mapconductor/core/marker/MarkerTileSeamTest.kt b/src/test/java/com/mapconductor/core/marker/MarkerTileSeamTest.kt new file mode 100644 index 0000000..141b0ac --- /dev/null +++ b/src/test/java/com/mapconductor/core/marker/MarkerTileSeamTest.kt @@ -0,0 +1,155 @@ +package com.mapconductor.core.marker + +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.features.GeoRectBounds +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * Neighbouring tiles must agree about the markers they share. + * + * Tiles are drawn one at a time. A marker drawn on tile A but not on tile B + * gets **cut** at the boundary: the left half appears on the left tile and the + * rest is nowhere. + * + * The renderer queries its own box grown by the icon overhang + * (`queryByHalfExtentPx`), so the property that keeps the seam intact is: + * a marker returned for A that also falls inside B's grown box must be + * returned for B. That is all this test looks at — it never draws anything. + * + * ios-sdk's `MarkerTileSeamTests` and react-sdk's `MarkerTileSeam.test.mjs` + * check the same thing. + */ +class MarkerTileSeamTest { + private val tileSize = 512.0 + + /** The sample's declutter. The disagreement shows up as a side effect of thinning. */ + private val declutterPx = 14.0 + + /** Half an icon. The renderer measures it; a fixed value is enough here. */ + private val halfExtentPx = 10.0 + + private fun markers(count: Int): List> { + var seed = 12345uL + + fun next(): Double { + seed = seed * 6364136223846793005uL + 1442695040888963407uL + return (seed shr 11).toDouble() / (1uL shl 53).toDouble() + } + return (0 until count).map { at -> + MarkerEntity( + marker = at, + state = + MarkerState( + position = GeoPoint.fromLatLong(35.5 + next() * 0.4, 139.5 + next() * 0.5), + id = "$at", + ), + ) + } + } + + /** Tile coordinates to a lat/lng box. Same formulas as the renderer. */ + private fun tileBounds( + x: Int, + y: Int, + z: Int, + ): GeoRectBounds { + val n = Math.pow(2.0, z.toDouble()) + + fun lon(tx: Double) = tx / n * 360.0 - 180.0 + + fun lat(ty: Double) = Math.atan(Math.sinh(Math.PI * (1.0 - 2.0 * (ty / n)))) * 180.0 / Math.PI + return GeoRectBounds( + southWest = GeoPoint.fromLatLong(lat((y + 1).toDouble()), lon(x.toDouble())), + northEast = GeoPoint.fromLatLong(lat(y.toDouble()), lon((x + 1).toDouble())), + ) + } + + private data class Asked( + val expanded: GeoRectBounds, + val kept: List>, + val thinned: Boolean, + ) + + /** + * The box and separation the renderer actually asks with. + * + * At zooms where the separation is finer than the bottom level the index + * declines and the renderer falls back to the full query. That path has to + * hold the seam too, so when it declines this checks `inBounds` instead. + */ + private fun ask( + index: MarkerGridIndex, + x: Int, + y: Int, + z: Int, + ): Asked { + val bounds = tileBounds(x, y, z) + val southWest = bounds.southWest!! + val northEast = bounds.northEast!! + val latSpan = northEast.latitude - southWest.latitude + val lonSpan = northEast.longitude - southWest.longitude + val padNorm = halfExtentPx / tileSize + val expanded = + GeoRectBounds( + southWest = + GeoPoint.fromLatLong( + southWest.latitude - latSpan * padNorm, + southWest.longitude - lonSpan * padNorm, + ), + northEast = + GeoPoint.fromLatLong( + northEast.latitude + latSpan * padNorm, + northEast.longitude + lonSpan * padNorm, + ), + ) + val separation = maxOf(latSpan, lonSpan) * declutterPx / tileSize + val thinned = index.inBoundsThinned(expanded, separation) + return if (thinned != null) { + Asked(expanded, thinned, true) + } else { + Asked(expanded, index.inBounds(expanded), false) + } + } + + @Test + fun adjacentTilesAgreeOnTheMarkersTheyShare() { + val all = markers(144_183) + val index = MarkerGridIndex { all } + + var checked = 0 + var thinnedPairs = 0 + for (z in listOf(9, 10, 11, 12, 13, 14)) { + val n = Math.pow(2.0, z.toDouble()) + val x = ((139.75 + 180.0) / 360.0 * n).toInt() + val latRad = 35.68 * Math.PI / 180 + val y = ((1.0 - Math.log(Math.tan(latRad) + 1.0 / Math.cos(latRad)) / Math.PI) / 2.0 * n).toInt() + + // Sideways and downwards. A seam runs in both directions. + for ((dx, dy) in listOf(1 to 0, 0 to 1)) { + val a = ask(index, x, y, z) + val b = ask(index, x + dx, y + dy, z) + // At low zoom the whole cloud fits on one tile and the + // neighbour is empty. Comparing against nothing proves nothing. + if (a.kept.isEmpty() || b.kept.isEmpty()) continue + checked++ + if (a.thinned) thinnedPairs++ + + val inB = b.kept.map { it.state.id }.toSet() + val missing = + a.kept.count { + b.expanded.contains(it.state.position) && it.state.id !in inB + } + assertEquals( + "z=$z d=($dx,$dy) thinned=${a.thinned}: tile A draws $missing markers " + + "that the overlapping tile B does not — the icon is cut at the seam", + 0, + missing, + ) + } + } + assertTrue("too few pairs were comparable", checked >= 8) + assertTrue("no pair exercised thinning", thinnedPairs >= 4) + } +} diff --git a/src/test/java/com/mapconductor/core/marker/StrategyMarkerClearOrderTest.kt b/src/test/java/com/mapconductor/core/marker/StrategyMarkerClearOrderTest.kt new file mode 100644 index 0000000..027c594 --- /dev/null +++ b/src/test/java/com/mapconductor/core/marker/StrategyMarkerClearOrderTest.kt @@ -0,0 +1,138 @@ +package com.mapconductor.core.marker + +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.features.GeoRectBounds +import com.mapconductor.core.map.MapCameraPosition +import com.mapconductor.core.map.MapViewHolderInterface +import com.mapconductor.core.map.VisibleRegion +import kotlinx.coroutines.test.runTest +import org.junit.Assert.assertEquals +import org.junit.Test + +/** + * [StrategyMarkerController.clear] は他のコントローラの clear() と同じく + * 「onRemove(全部) → 空にする → onPostProcess」で、何も描かれていない状態で終わること。 + * + * 以前は strategy.clear() で manager を空にするだけで、onRemove も onPostProcess も + * 呼ばなかった。GL 系の描画担当は onPostProcess で manager から描き直すので、 + * clear() の後もマーカーが地図に残る。js-sdk-core / ios-sdk-core の同名テストと同じ。 + */ +class StrategyMarkerClearOrderTest { + private val bounds = GeoRectBounds(GeoPoint(34.0, 138.0), GeoPoint(36.0, 140.0)) + private val camera = + MapCameraPosition( + position = GeoPoint(35.0, 139.0), + zoom = 10.0, + visibleRegion = VisibleRegion(bounds, null, null, null, null), + ) + + /** GL 系の描画担当: onRemove では何もせず、onPostProcess で manager の全部を描き直す。 */ + private class GlRenderer( + private val manager: MarkerManager, + ) : MarkerOverlayRendererInterface { + var drawn: List = emptyList() + val removed = mutableListOf() + override var animateStartListener: OnMarkerEventHandler? = null + override var animateEndListener: OnMarkerEventHandler? = null + override val holder: MapViewHolderInterface<*, *> + get() = throw UnsupportedOperationException("not used") + + override suspend fun onAdd(data: List) = data.map { it.state.id } + + override suspend fun onChange(data: List>) = + data.map { it.current.state.id } + + override suspend fun onRemove(data: List>) { + removed += data.map { it.state.id } + } + + override suspend fun onAnimate(entity: MarkerEntityInterface) = Unit + + override suspend fun onPostProcess() { + drawn = manager.allEntities().map { it.state.id }.sorted() + } + } + + /** + * 渡されたマーカーを全部描くストラテジ。既定アイコン(AbstractMarkerRenderingStrategy が持つ)は + * Android の Bitmap を焼くので素の JVM では使えない。描いた状態は manager へ直接登録する。 + */ + private class DrawAllStrategy : MarkerRenderingStrategyInterface { + override val markerManager: MarkerManager = MarkerManager.defaultManager() + var cleared = 0 + + override fun clear() { + cleared++ + markerManager.clear() + } + + override suspend fun onUpdate( + state: MarkerState, + viewport: GeoRectBounds, + renderer: MarkerOverlayRendererInterface, + ): Boolean = true + + override suspend fun onAdd( + data: List, + viewport: GeoRectBounds, + renderer: MarkerOverlayRendererInterface, + ): Boolean { + data.forEach { markerManager.registerEntity(MarkerEntity(marker = it.id, state = it, isRendered = true)) } + renderer.onPostProcess() + return true + } + + override suspend fun onCameraChanged( + cameraPosition: MapCameraPosition, + renderer: MarkerOverlayRendererInterface, + ) = Unit + } + + private fun markers() = + listOf( + MarkerState(position = GeoPoint(35.0, 139.0), id = "m1"), + MarkerState(position = GeoPoint(35.1, 139.1), id = "m2"), + ) + + @Test + fun `clear 後は何も描かれず、ストラテジ自身の後片付けも走る`() = + runTest { + val strategy = DrawAllStrategy() + val renderer = GlRenderer(strategy.markerManager) + val controller = StrategyMarkerController(strategy, renderer) + controller.onCameraChanged(camera) + controller.add(markers()) + assertEquals(listOf("m1", "m2"), renderer.drawn) + + controller.clear() + + assertEquals(listOf("m1", "m2"), renderer.removed.sorted()) + assertEquals(1, strategy.cleared) + assertEquals(emptyList(), renderer.drawn) + } + + @Test + fun `最初のカメラ待ちのマーカーも clear で捨てる`() = + runTest { + val strategy = DrawAllStrategy() + val renderer = GlRenderer(strategy.markerManager) + val controller = StrategyMarkerController(strategy, renderer) + controller.add(markers()) // カメラ前なので保留 + controller.clear() + controller.onCameraChanged(camera) + assertEquals(emptyList(), renderer.drawn) + } + + @Test + fun `clear 後に送り直せばまた描かれる`() = + runTest { + val strategy = DrawAllStrategy() + val renderer = GlRenderer(strategy.markerManager) + val controller = StrategyMarkerController(strategy, renderer) + controller.onCameraChanged(camera) + controller.add(markers()) + controller.clear() + controller.add(markers()) + assertEquals(listOf("m1", "m2"), renderer.drawn) + } +} diff --git a/src/test/java/com/mapconductor/core/polygon/PolygonHitToleranceTest.kt b/src/test/java/com/mapconductor/core/polygon/PolygonHitToleranceTest.kt new file mode 100644 index 0000000..1339257 --- /dev/null +++ b/src/test/java/com/mapconductor/core/polygon/PolygonHitToleranceTest.kt @@ -0,0 +1,65 @@ +package com.mapconductor.core.polygon + +import com.mapconductor.core.features.GeoPoint +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +/** + * A tap counts as on a polygon's edge only when it is within `eps` (1e-6°, + * about 0.1 m) of that edge. Taps outside the polygon's bounding box never get + * that far, so the tolerance only matters on and just inside the outline. + * + * js-sdk-core の `PolygonHitTolerance.test.mjs`、ios-sdk の `PolygonHitToleranceTests` と + * 1 対 1 で対応する。 + * + * 辺上の判定が度の 2 乗の量(内積)を 1e-6 と比べていて、短い辺から約 100 m 以内の + * タップをすべて「辺上」として拾っていた。建物の輪郭のように辺が数 m のポリゴンを + * 並べると、タップした建物ではなく、リストで先にある近所の建物が返る。大きな図形では + * 起きないので、サンプルの六角形では見えなかった。 + */ +class PolygonHitToleranceTest { + // ボストン中心部の、一辺が約 10 m の建物 + private val building = + listOf( + GeoPoint(42.3550, -71.0600), + GeoPoint(42.3550, -71.0599), + GeoPoint(42.3551, -71.0599), + GeoPoint(42.3551, -71.0600), + GeoPoint(42.3550, -71.0600), + ) + + private fun managerWith(vararg states: PolygonState): PolygonManager = + PolygonManager().apply { + states.forEach { registerEntity(PolygonEntity(polygon = Unit, state = it)) } + } + + @Test + fun `50 m 離れたタップは、辺の短い建物に当たらない`() { + val manager = managerWith(PolygonState(points = building, id = "small")) + // 建物の東の辺から東へ約 50 m(経度 0.0006°) + assertNull(manager.find(GeoPoint(42.35505, -71.0593))) + // 北へ約 50 m + assertNull(manager.find(GeoPoint(42.3556, -71.05995))) + } + + @Test + fun `内側のタップと辺の上のタップは当たり、0点6 m 外れたタップは当たらない`() { + val manager = managerWith(PolygonState(points = building, id = "small")) + assertEquals("small", manager.find(GeoPoint(42.35505, -71.05995))?.state?.id) + assertEquals("南の辺の上", "small", manager.find(GeoPoint(42.3550, -71.05995))?.state?.id) + assertNull("南の辺から外へ約 0.6 m", manager.find(GeoPoint(42.354995, -71.05995))) + } + + @Test + fun `近所の建物ではなく、タップした建物が返る`() { + // 西隣(約 20 m 西)にもう 1 棟。リストでは先に入れる + val west = building.map { GeoPoint(it.latitude, it.longitude - 0.00025) } + val manager = + managerWith( + PolygonState(points = west, id = "west"), + PolygonState(points = building, id = "tapped"), + ) + assertEquals("tapped", manager.find(GeoPoint(42.35505, -71.05995))?.state?.id) + } +} diff --git a/src/test/java/com/mapconductor/core/polygon/PolygonHoleUnionFixtureTest.kt b/src/test/java/com/mapconductor/core/polygon/PolygonHoleUnionFixtureTest.kt new file mode 100644 index 0000000..79055bd --- /dev/null +++ b/src/test/java/com/mapconductor/core/polygon/PolygonHoleUnionFixtureTest.kt @@ -0,0 +1,101 @@ +package com.mapconductor.core.polygon + +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.features.GeoPointInterface +import org.junit.Assert.assertSame +import org.junit.Assert.assertTrue +import org.junit.Test +import kotlin.math.abs + +/** + * unionHoleRings keeps the area of the union of the holes: holes that touch at a + * point or share (part of) an edge add up, overlaps count once. + * + * js-sdk-core (`PolygonHoleUnion.test.mjs`) and ios-sdk-core + * (`PolygonHoleUnionFixtureTests`) read the same `polygon-hole-union-fixture.txt`; + * the expected areas are shapely's unary_union. + */ +class PolygonHoleUnionFixtureTest { + private class Case( + val name: String, + val unit: Double, + val originLon: Double, + val originLat: Double, + val unionArea: Double, + ) { + var outer: List? = null + val holes = mutableListOf>() + + fun toGeo(flat: List): List = + flat.chunked(2).map { (x, y) -> + GeoPoint.fromLatLong(latitude = originLat + y * unit, longitude = originLon + x * unit) + } + + /** Planar area in grid units². */ + fun areaInUnits(ring: List): Double { + var a = 0.0 + for (i in ring.indices) { + val p = ring[i] + val q = ring[(i + 1) % ring.size] + val px = (p.longitude - originLon) / unit + val py = (p.latitude - originLat) / unit + val qx = (q.longitude - originLon) / unit + val qy = (q.latitude - originLat) / unit + a += px * qy - qx * py + } + return a / 2.0 + } + } + + private fun readCases(): List { + val stream = + requireNotNull(javaClass.classLoader?.getResourceAsStream("polygon-hole-union-fixture.txt")) { + "polygon-hole-union-fixture.txt not on the test classpath" + } + val cases = mutableListOf() + stream.bufferedReader().forEachLine { line -> + if (line.isBlank() || line.startsWith("#")) return@forEachLine + val parts = line.split("|") + when (parts[0]) { + "case" -> + cases.add( + Case( + name = parts[1], + unit = parts[2].toDouble(), + originLon = parts[3].toDouble(), + originLat = parts[4].toDouble(), + unionArea = parts[5].toDouble(), + ), + ) + "outer" -> cases.last().outer = parts[1].split(",").map { it.toDouble() } + "hole" -> cases.last().holes.add(parts[1].split(",").map { it.toDouble() }) + } + } + return cases + } + + @Test + fun unionKeepsTheAreaOfTheUnion() { + val cases = readCases() + assertTrue("fixture has cases", cases.size >= 20) + val failures = mutableListOf() + for (c in cases) { + val holes = c.holes.map { c.toGeo(it) } + val result = + c.outer?.let { outer -> + val state = PolygonState(points = c.toGeo(outer), holes = holes) + val unioned = state.unionHoles() + assertSame("${c.name}: the outline is left alone", state.points, unioned.points) + unioned.holes + } ?: unionHoleRings(holes) + val area = result.sumOf { abs(c.areaInUnits(it)) } + if (abs(area - c.unionArea) > 1e-6 * c.unionArea) { + failures.add("${c.name}: area $area != union ${c.unionArea} (${result.size} rings from ${holes.size})") + } + if (result.any { c.areaInUnits(it) >= 0.0 }) { + failures.add("${c.name}: a hole came back counter-clockwise") + } + } + assertTrue(failures.joinToString("\n"), failures.isEmpty()) + } +} diff --git a/src/test/java/com/mapconductor/core/polygon/PolygonTileGeometryTest.kt b/src/test/java/com/mapconductor/core/polygon/PolygonTileGeometryTest.kt new file mode 100644 index 0000000..f30811f --- /dev/null +++ b/src/test/java/com/mapconductor/core/polygon/PolygonTileGeometryTest.kt @@ -0,0 +1,146 @@ +package com.mapconductor.core.polygon + +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.features.GeoPointInterface +import org.junit.Assert.assertArrayEquals +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 + +/** + * タイルに描く前の幾何: 巻きの正規化、ズームごとの簡略化、グリッド索引。 + * + * js-sdk-core の tile-sw.js「Polygon tiles」節と同じ手順であることを固定する。 + * 画素そのものは端末で見る(androidTest の `PolygonTileRendererDeviceTest`)。 + */ +class PolygonTileGeometryTest { + private fun p( + latitude: Double, + longitude: Double, + ): GeoPointInterface = GeoPoint.fromLatLong(latitude, longitude) + + private fun square( + lat: Double, + lng: Double, + size: Double, + ): List = listOf(p(lat, lng), p(lat, lng + size), p(lat + size, lng + size), p(lat + size, lng)) + + @Test + fun `外周は正、穴は負の巻きにそろう(与えた向きによらない)`() { + val outer = square(0.0, 0.0, 4.0) + val hole = square(1.0, 1.0, 1.0) + for (o in listOf(outer, outer.reversed())) { + for (h in listOf(hole, hole.reversed())) { + val polygon = TilePolygon.from(PolygonState(points = o, holes = listOf(h)))!! + assertTrue(signedArea(polygon.rings[0]) > 0) + assertTrue(signedArea(polygon.rings[1]) < 0) + } + } + } + + @Test + fun `外接矩形は Web Mercator の 0 から 1 で、北が小さい y`() { + val polygon = TilePolygon.from(PolygonState(points = square(0.0, 0.0, 10.0)))!! + assertEquals(0.5, polygon.bbox[0], 1e-12) + assertEquals((10.0 + 180) / 360, polygon.bbox[2], 1e-12) + assertEquals(0.5, polygon.bbox[3], 1e-12) + assertTrue(polygon.bbox[1] < 0.5) + } + + @Test + fun `外周が 3 点未満なら描かない、穴が 3 点未満なら穴だけ捨てる`() { + assertNull(TilePolygon.from(PolygonState(points = listOf(p(0.0, 0.0), p(1.0, 1.0))))) + val polygon = TilePolygon.from(PolygonState(points = square(0.0, 0.0, 4.0), holes = listOf(listOf(p(1.0, 1.0)))))!! + assertEquals(1, polygon.rings.size) + } + + @Test + fun `頂点は画素格子に丸め、続く重複を捨て、半画素の Douglas-Peucker で間引く`() { + val scale = 1000.0 + // 1 画素幅の正方形の辺上に、同じ画素に丸まる点と、直線上の点を足す + val ring = + doubleArrayOf( + 0.0, + 0.0, + 0.0004, + 0.0001, // (0, 0) に丸まる + 0.005, + 0.0, // 直線上 + 0.010, + 0.0, + 0.010, + 0.010, + 0.0, + 0.010, + ) + val simplified = simplifyRing(ring, scale)!! + assertArrayEquals(doubleArrayOf(0.0, 0.0, 10.0, 0.0, 10.0, 10.0, 0.0, 10.0), simplified, 0.0) + } + + @Test + fun `半画素未満のずれは捨て、それを超えるずれは残す`() { + val straight = douglasPeucker(doubleArrayOf(0.0, 0.0, 5.0, 0.4, 10.0, 0.0), 3, DP_TOLERANCE_PX) + assertArrayEquals(doubleArrayOf(0.0, 0.0, 10.0, 0.0), straight, 0.0) + val bent = douglasPeucker(doubleArrayOf(0.0, 0.0, 5.0, 1.0, 10.0, 0.0), 3, DP_TOLERANCE_PX) + assertEquals(6, bent.size) + } + + @Test + fun `1 画素に満たないポリゴンは 1 画素の点になる`() { + val polygon = TilePolygon.from(PolygonState(points = square(0.0, 0.0, 0.001)))!! + // z0: 世界が 256 画素。0.001 度は 0.0007 画素 + val shape = simplifyPolygon(polygon, 256.0) + assertTrue(shape is TileShape.Dot) + shape as TileShape.Dot + assertEquals(128.0, shape.x, 0.0) + assertEquals(127.0, shape.y, 0.0) + } + + @Test + fun `画面上 4 画素未満のポリゴンは枠線を描かない`() { + val polygon = TilePolygon.from(PolygonState(points = square(0.0, 0.0, 1.0)))!! + // 1 度は 256 * 2^z / 360 画素。z2: 2.8 px、z3: 5.7 px + val small = simplifyPolygon(polygon, 256.0 * 4) as TileShape.Rings + val large = simplifyPolygon(polygon, 256.0 * 8) as TileShape.Rings + assertFalse(small.outlined) + assertTrue(large.outlined) + } + + @Test + fun `索引は外接矩形が重なるものだけを、重複なく描く順に返す`() { + val states = + listOf( + square(0.0, 0.0, 0.01), // 0 + square(0.0, 1.0, 0.01), // 1: 離れている + square(0.0, 0.005, 0.2), // 2: 複数のセルにまたがる + square(-60.0, -100.0, 120.0), // 3: 大きい(every query) + ) + val polygons = states.map { TilePolygon.from(PolygonState(points = it)) }.toTypedArray() + val index = PolygonGridIndex.build(polygons) + val b0 = polygons[0]!!.bbox + assertArrayEquals(intArrayOf(0, 2, 3), index.query(polygons, b0[0], b0[1], b0[2], b0[3])) + val b1 = polygons[1]!!.bbox + assertArrayEquals(intArrayOf(1, 3), index.query(polygons, b1[0], b1[1], b1[2], b1[3])) + // 消したポリゴン(null)は返さない + polygons[0] = null + assertArrayEquals(intArrayOf(2, 3), index.query(polygons, b0[0], b0[1], b0[2], b0[3])) + } + + @Test + fun `測地線と、経度の幅が 180 度以上のポリゴンはタイルにしない`() { + assertTrue(PolygonTileSet.canTile(PolygonState(points = square(0.0, 0.0, 1.0)))) + assertFalse(PolygonTileSet.canTile(PolygonState(points = square(0.0, 0.0, 1.0), geodesic = true))) + assertFalse(PolygonTileSet.canTile(PolygonState(points = square(0.0, -90.0, 180.0)))) + assertFalse(PolygonTileSet.canTile(PolygonState(points = listOf(p(0.0, 0.0), p(1.0, 1.0))))) + } + + @Test + fun `頂点数は外周と穴の合計`() { + val state = PolygonState(points = square(0.0, 0.0, 4.0), holes = listOf(square(1.0, 1.0, 1.0))) + assertEquals(16, PolygonTileSet.vertexCount(listOf(state, state))) + assertNotNull(TilePolygon.from(state)) + } +} diff --git a/src/test/java/com/mapconductor/core/polygon/PolygonTilingTest.kt b/src/test/java/com/mapconductor/core/polygon/PolygonTilingTest.kt new file mode 100644 index 0000000..fe5eadd --- /dev/null +++ b/src/test/java/com/mapconductor/core/polygon/PolygonTilingTest.kt @@ -0,0 +1,102 @@ +package com.mapconductor.core.polygon + +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.features.GeoPointInterface +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertSame +import org.junit.Assert.assertTrue +import org.junit.Test +import kotlin.math.PI +import kotlin.math.cos +import kotlin.math.sin + +/** + * ポリゴンのタイル描画を支える部品。 + * + * js-sdk-core の `PolygonTiling.test.mjs`、ios-sdk の `PolygonTilingTests` と 1 対 1 で対応する。 + * web の Encoded Polyline の 2 件は、サービスワーカーへ渡すための変換なので + * Android には無い(タイルサーバーが同じプロセスにあり、状態をそのまま読む)。 + * + * - しきい値: ポリゴン数か頂点数のどちらかが届けばタイル。判定はここ 1 か所。 + * - 穴のユニオンの近道: 交わらない穴はそのまま返す。道路網の区画(穴 80 個・穴の頂点 + * 8,000)で 1 個数秒かかっていた二乗の計算を、交わる穴があるときだけに絞る。 + */ +class PolygonTilingTest { + private fun p( + latitude: Double, + longitude: Double, + ): GeoPointInterface = GeoPoint.fromLatLong(latitude, longitude) + + private fun square( + lat: Double, + lng: Double, + size: Double, + ): List = listOf(p(lat, lng), p(lat, lng + size), p(lat + size, lng + size), p(lat + size, lng)) + + /** The same square wound clockwise, the way holes come out of the union. */ + private fun clockwise(ring: List): List = ring.reversed() + + @Test + fun `ポリゴン数か頂点数のどちらかが届けばタイルにする`() { + val o = PolygonTilingOptions.Default + assertFalse(o.shouldUseTiles(1999, 49_999)) + assertTrue(o.shouldUseTiles(2000, 0)) + assertTrue(o.shouldUseTiles(10, 50_000)) + assertFalse(PolygonTilingOptions.Disabled.shouldUseTiles(100_000, 10_000_000)) + } + + @Test + fun `geodesic・経度の幅 180 度以上・頂点 3 未満はタイルにしない`() { + assertTrue(PolygonTileSet.canTile(PolygonState(points = square(0.0, 0.0, 1.0)))) + assertFalse(PolygonTileSet.canTile(PolygonState(points = square(0.0, 0.0, 1.0), geodesic = true))) + assertFalse(PolygonTileSet.canTile(PolygonState(points = listOf(p(0.0, -100.0), p(0.0, 80.0), p(10.0, 0.0))))) + assertTrue(PolygonTileSet.canTile(PolygonState(points = listOf(p(0.0, -90.0), p(0.0, 89.0), p(10.0, 0.0))))) + assertFalse(PolygonTileSet.canTile(PolygonState(points = listOf(p(0.0, 0.0), p(1.0, 1.0))))) + } + + @Test + fun `交わらない穴は計算せずにそのまま返す`() { + val holes = listOf(square(0.0, 0.0, 1.0), square(0.0, 2.0, 1.0), square(2.0, 0.0, 1.0)).map(::clockwise) + assertSame(holes, unionHoleRings(holes)) + } + + /** + * Android の union は穴を時計回りにそろえて返す(レンダラーが外周と逆巻きを期待する。 + * `PolygonHoleUnionTest.disjointSquares_remainSeparateWithSameAreas`)。近道でもそれは守る。 + * web の近道は向きをそろえずに返す。 + */ + @Test + fun `近道でも、反時計回りの穴は時計回りにして返す`() { + val holes = listOf(square(0.0, 0.0, 1.0), clockwise(square(0.0, 2.0, 1.0))) + val result = unionHoleRings(holes) + assertEquals(2, result.size) + assertEquals(holes[0].reversed(), result[0]) + assertSame(holes[1], result[1]) + } + + @Test + fun `重なる穴・中に入った穴・接する穴は従来どおり 1 つにまとめる`() { + assertEquals("重なる", 1, unionHoleRings(listOf(square(0.0, 0.0, 2.0), square(1.0, 1.0, 2.0))).size) + assertEquals("中に入った", 1, unionHoleRings(listOf(square(0.0, 0.0, 4.0), square(1.0, 1.0, 1.0))).size) + assertEquals("辺で接する", 1, unionHoleRings(listOf(square(0.0, 0.0, 1.0), square(0.0, 1.0, 1.0))).size) + } + + @Test + fun `交わらない穴が多くても速い(穴 80 個 x 100 頂点)`() { + val holes = + List(80) { i -> + val cx = (i % 10) * 3.0 + val cy = (i / 10) * 3.0 + List(100) { k -> + val a = -2 * PI * k / 100 + p(cy + sin(a), cx + cos(a)) + } + } + val start = System.nanoTime() + val result = unionHoleRings(holes) + val ms = (System.nanoTime() - start) / 1e6 + assertSame(holes, result) + assertTrue("$ms ms", ms < 200) + } +} diff --git a/src/test/java/com/mapconductor/core/polyline/PolylineHitToleranceTest.kt b/src/test/java/com/mapconductor/core/polyline/PolylineHitToleranceTest.kt new file mode 100644 index 0000000..c0289dc --- /dev/null +++ b/src/test/java/com/mapconductor/core/polyline/PolylineHitToleranceTest.kt @@ -0,0 +1,169 @@ +package com.mapconductor.core.polyline + +import androidx.compose.ui.unit.dp +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.map.MapCameraPosition +import com.mapconductor.core.spherical.Planar +import com.mapconductor.core.spherical.calculateMetersPerPixel +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test +import kotlin.random.Random + +/** + * ポリラインのタップ判定。タイルで描いていてもネイティブで描いていても同じ。 + * + * 当たるのは「線の縁から指の大きさ(tapTolerance)以内」: 中心線から tapTolerance + 線幅 / 2 + * (どちらも画面上の大きさ)。複数当たれば一番近い線。clickable = false の線は素通り。 + * 5 万本を毎回測らないよう、外接矩形(許容ぶん広げる)に入らない線は先に飛ばす。飛ばしても結果は変わらない。 + * + * js-sdk-core の `PolylineHitTolerance.test.mjs`、ios-sdk の `PolylineHitToleranceTests` と 1 対 1 で対応する。 + * ユニットテストでは density = 1(ResourceProvider のフォールバック)、tapTolerance は 14 dp = 14 px。 + */ +class PolylineHitToleranceTest { + private val lat = 42.3550 + private val camera = MapCameraPosition(position = GeoPoint.fromLatLong(lat, -71.06), zoom = 16.0) + private val metersPerPixel = calculateMetersPerPixel(lat, 16.0) + + /** 北へ [meters] m。 */ + private fun north(meters: Double) = meters / 111_320.0 + + private fun line( + id: String, + offsetMeters: Double = 0.0, + width: Float = 1f, + clickable: Boolean = true, + ) = PolylineState( + points = listOf(GeoPoint(lat + north(offsetMeters), -71.0610), GeoPoint(lat + north(offsetMeters), -71.0590)), + id = id, + strokeWidth = width.dp, + clickable = clickable, + ) + + private fun managerWith(vararg states: PolylineState): PolylineManager = + PolylineManager().apply { + states.forEach { registerEntity(PolylineEntity(polyline = Unit, state = it)) } + } + + private fun tapNorth(meters: Double) = GeoPoint(lat + north(meters), -71.0600) + + @Test + fun `太い線は縁から指の大きさ以内なら当たり、細い線は同じ距離で外れる`() { + // z16 で約 1.77 m/px。細い線(1 px): 14.5 px ≒ 25.6 m、太い線(10 px): 19 px ≒ 33.5 m + val thirty = 30.0 + assertEquals( + "wide", + managerWith(line("wide", width = 10f)) + .find(tapNorth(thirty), camera) + ?.entity + ?.state + ?.id, + ) + assertNull(managerWith(line("thin", width = 1f)).find(tapNorth(thirty), camera)) + // 境目の内と外 + val edge = (14.0 + 5.0) * metersPerPixel + assertEquals( + "wide", + managerWith(line("wide", width = 10f)) + .find(tapNorth(edge - 1.0), camera) + ?.entity + ?.state + ?.id, + ) + assertNull(managerWith(line("wide", width = 10f)).find(tapNorth(edge + 1.0), camera)) + } + + @Test + fun `当たった点は線上の最近点`() { + val hit = managerWith(line("a", width = 4f)).find(tapNorth(10.0), camera)!! + assertEquals(lat, hit.closestPoint.latitude, 1e-7) + assertEquals(-71.0600, hit.closestPoint.longitude, 1e-7) + } + + @Test + fun `複数当たれば一番近い線`() { + val manager = managerWith(line("south", 0.0, width = 6f), line("north", 20.0, width = 2f)) + assertEquals( + "north", + manager + .find(tapNorth(15.0), camera) + ?.entity + ?.state + ?.id, + ) + assertEquals( + "south", + manager + .find(tapNorth(5.0), camera) + ?.entity + ?.state + ?.id, + ) + } + + @Test + fun `clickable = false の線は素通りして下の線に当たる`() { + val manager = managerWith(line("under", 0.0), line("over", 2.0, clickable = false)) + assertEquals( + "under", + manager + .find(tapNorth(2.0), camera) + ?.entity + ?.state + ?.id, + ) + assertNull(managerWith(line("over", 2.0, clickable = false)).find(tapNorth(2.0), camera)) + } + + @Test + fun `外接矩形で飛ばしても、全部測ったときと同じ線が当たる`() { + val random = Random(7) + val states = + List(300) { i -> + val lat0 = lat + random.nextDouble(-0.01, 0.01) + val lng0 = -71.06 + random.nextDouble(-0.01, 0.01) + val points = + List(2 + random.nextInt(4)) { + GeoPoint(lat0 + random.nextDouble(-0.001, 0.001), lng0 + random.nextDouble(-0.001, 0.001)) + } + PolylineState(points = points, id = "l$i", strokeWidth = random.nextInt(1, 8).dp) + } + val manager = managerWith(*states.toTypedArray()) + var hits = 0 + repeat(400) { + val tap = GeoPoint(lat + random.nextDouble(-0.011, 0.011), -71.06 + random.nextDouble(-0.011, 0.011)) + val expected = bruteForce(states, tap) + val actual = + manager + .find(tap, camera) + ?.entity + ?.state + ?.id + assertEquals(expected, actual) + if (actual != null) hits++ + } + // 当たりも外れも十分に含む + assert(hits in 40..360) { "hits=$hits" } + } + + /** 外接矩形を使わず、全部の線の全部の辺を測る。 */ + private fun bruteForce( + states: List, + tap: GeoPoint, + ): String? { + var best: String? = null + var bestDistance = Double.POSITIVE_INFINITY + val mpp = calculateMetersPerPixel(tap.latitude, 16.0) + for (s in states) { + val threshold = mpp * (14.0 + s.strokeWidth.value / 2.0) + for (i in 0 until s.points.size - 1) { + val hit = Planar.pointOnLineOrNull(s.points[i], s.points[i + 1], tap, threshold) ?: continue + if (hit.second < bestDistance) { + bestDistance = hit.second + best = s.id + } + } + } + return best + } +} diff --git a/src/test/java/com/mapconductor/core/polyline/PolylineTilingTest.kt b/src/test/java/com/mapconductor/core/polyline/PolylineTilingTest.kt new file mode 100644 index 0000000..35d5937 --- /dev/null +++ b/src/test/java/com/mapconductor/core/polyline/PolylineTilingTest.kt @@ -0,0 +1,144 @@ +package com.mapconductor.core.polyline + +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.dp +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.features.GeoPointInterface +import org.junit.Assert.assertArrayEquals +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 + +/** + * ポリラインのタイル描画を支える部品(画素を見ない部分)。 + * + * js-sdk-core の `PolylineTiling.test.mjs`、ios-sdk の `PolylineTilingTests` と 1 対 1 で対応する。 + * 画素そのものは端末で見る(androidTest の `PolylineTileRendererDeviceTest`)。 + * + * - しきい値: 本数か点の数のどちらかが届けばタイル。判定はここ 1 か所。 + * - タイルにできないもの: geodesic、経度の幅 180 度以上、2 点未満。 + * - ズームごとの簡略化: 画素格子に丸め、続く重複を捨て、半画素の Douglas-Peucker(両端は残す)。 + * 1 点に潰れたら点。 + */ +class PolylineTilingTest { + private fun p( + latitude: Double, + longitude: Double, + ): GeoPointInterface = GeoPoint.fromLatLong(latitude, longitude) + + @Test + fun `本数か点の数のどちらかが届けばタイルにする`() { + val o = PolylineTilingOptions.Default + assertFalse(o.shouldUseTiles(1999, 49_999)) + assertTrue(o.shouldUseTiles(2000, 0)) + assertTrue(o.shouldUseTiles(10, 50_000)) + assertFalse(PolylineTilingOptions.Disabled.shouldUseTiles(100_000, 10_000_000)) + } + + @Test + fun `geodesic・経度の幅 180 度以上・2 点未満はタイルにしない`() { + assertTrue(PolylineTileSet.canTile(PolylineState(points = listOf(p(0.0, 0.0), p(1.0, 1.0))))) + assertFalse(PolylineTileSet.canTile(PolylineState(points = listOf(p(0.0, 0.0), p(1.0, 1.0)), geodesic = true))) + assertFalse(PolylineTileSet.canTile(PolylineState(points = listOf(p(0.0, -100.0), p(0.0, 80.0))))) + assertTrue(PolylineTileSet.canTile(PolylineState(points = listOf(p(0.0, -90.0), p(0.0, 89.0))))) + assertFalse(PolylineTileSet.canTile(PolylineState(points = listOf(p(0.0, 0.0))))) + assertFalse(PolylineTileSet.canTile(PolylineState(points = emptyList()))) + } + + @Test + fun `点の数は全ポリラインの合計`() { + val a = PolylineState(points = listOf(p(0.0, 0.0), p(1.0, 1.0), p(2.0, 2.0))) + val b = PolylineState(points = listOf(p(0.0, 0.0), p(1.0, 1.0))) + assertEquals(5, PolylineTileSet.vertexCount(listOf(a, b))) + } + + @Test + fun `タイル用の線は開いた経路のまま、外接矩形を持つ`() { + assertNull(TilePolyline.from(PolylineState(points = listOf(p(0.0, 0.0))))) + val line = TilePolyline.from(PolylineState(points = listOf(p(0.0, 0.0), p(0.0, 90.0), p(0.0, 0.0))))!! + // 閉じない: 3 点のまま + assertEquals(6, line.path.size) + assertArrayEquals(doubleArrayOf(0.5, 0.5, 0.75, 0.5), line.bbox, 1e-12) + } + + @Test + fun `点は画素格子に丸め、続く重複と直線上の点を捨て、両端は残す`() { + // 世界 1000 画素。経度 0 度 = x 500 + val scale = 1000.0 + val line = + TilePolyline( + path = + doubleArrayOf( + 0.500, + 0.500, + 0.5004, + 0.5001, // (500, 500) に丸まる + 0.505, + 0.500, // 直線上 + 0.510, + 0.500, + 0.510, + 0.510, // 曲がる + ), + bbox = doubleArrayOf(0.5, 0.5, 0.51, 0.51), + color = 0xFF000000.toInt(), + strokeWidth = 2f, + ) + val shape = simplifyPolyline(line, scale) + assertTrue(shape is PolylineTileShape.Path) + assertArrayEquals( + doubleArrayOf(500.0, 500.0, 510.0, 500.0, 510.0, 510.0), + (shape as PolylineTileShape.Path) + .points, + 0.0, + ) + } + + @Test + fun `直線は両端の 2 点になる`() { + val line = TilePolyline.from(PolylineState(points = List(20) { i -> p(0.0, i * 0.5) }))!! + val shape = simplifyPolyline(line, 256.0 * 64) as PolylineTileShape.Path + assertEquals(4, shape.points.size) + } + + @Test + fun `1 画素に満たない線は点になる`() { + val line = TilePolyline.from(PolylineState(points = listOf(p(0.0, 0.0), p(0.0, 0.001))))!! + // z0: 世界が 256 画素。0.001 度は 0.0007 画素 + val shape = simplifyPolyline(line, 256.0) + assertTrue(shape is PolylineTileShape.Dot) + shape as PolylineTileShape.Dot + assertEquals(128.0, shape.x, 0.01) + assertEquals(128.0, shape.y, 0.01) + } + + @Test + fun `往復する短い線は、外接矩形が 1 画素以上なら経路、未満なら点`() { + val line = + TilePolyline( + path = doubleArrayOf(0.5, 0.5, 0.5012, 0.5, 0.5001, 0.5), + bbox = doubleArrayOf(0.5, 0.5, 0.5012, 0.5), + color = 0xFF000000.toInt(), + strokeWidth = 2f, + ) + // 世界 1000 画素: 500.0 → 500, 501.2 → 501, 500.1 → 500。2 画素なので経路 + assertTrue(simplifyPolyline(line, 1000.0) is PolylineTileShape.Path) + // 世界 800 画素: 外接矩形 0.96 px < 1 なので点 + assertTrue(simplifyPolyline(line, 800.0) is PolylineTileShape.Dot) + } + + @Test + fun `見えない線(透明・幅 0)は余白にも数えない`() { + val transparent = + TilePolyline + .from(PolylineState(points = listOf(p(0.0, 0.0), p(1.0, 1.0)), strokeColor = Color.Transparent))!! + assertFalse(transparent.visible) + assertEquals(0f, PolylineTilePainter.strokeWidth(transparent)) + val visible = TilePolyline.from(PolylineState(points = listOf(p(0.0, 0.0), p(1.0, 1.0)), strokeWidth = 6.dp))!! + assertNotNull(visible) + assertEquals(6f, PolylineTilePainter.strokeWidth(visible)) + } +} diff --git a/src/test/java/com/mapconductor/core/projection/ProjectionConformanceTest.kt b/src/test/java/com/mapconductor/core/projection/ProjectionConformanceTest.kt new file mode 100644 index 0000000..366643f --- /dev/null +++ b/src/test/java/com/mapconductor/core/projection/ProjectionConformanceTest.kt @@ -0,0 +1,89 @@ +package com.mapconductor.core.projection + +import com.mapconductor.core.features.GeoPoint +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test +import java.io.File + +/** + * Web Mercator の適合テスト。 + * + * 同じ `projection-vectors.txt` を ios-sdk / react-sdk も読む。3 つが同じ答えを + * 出すことを担保するのが目的で、ここが見ているのはこのプラットフォームの分だけ。 + * 突き合わせは 3 つの出力に対して別途行う。 + * + * `zoom-golden.txt` とは役割が違う。あちらは移行前の値の記録(既知の不具合込み)。 + * こちらは現在の実装どうしが一致しているかを見る。 + */ +class ProjectionConformanceTest { + /** + * 桁を固定する。 + * + * 言語ごとの既定の数値表記は揃わない。Kotlin の `Double.toString()` は + * 2000 万台を `2.0037508342789E7` と書くが、JS と Swift は書かない。 + * f64 のノイズより粗く、実装差より細かい桁で切る。 + */ + private fun fixed(value: Double): String = + when { + value.isNaN() -> "nan" + value == Double.POSITIVE_INFINITY -> "inf" + value == Double.NEGATIVE_INFINITY -> "-inf" + else -> String.format(java.util.Locale.ROOT, "%.6f", value) + } + + private fun runVectors(): String { + val vectors = + requireNotNull(javaClass.classLoader?.getResourceAsStream("projection-vectors.txt")) { + "projection-vectors.txt が見つからない" + }.bufferedReader().readText() + + val out = StringBuilder() + for (line in vectors.lines()) { + val row = line.trim() + if (row.isEmpty() || row.startsWith("#")) continue + val (op, a, b) = row.split("|").let { Triple(it[0], it[1], it[2]) } + when (op) { + "project" -> { + // 実物の GeoPoint を使う。無名実装だと wrap() を握り潰して + // しまい、投影側の wrap が効いていないように見える。 + val p = WebMercator.project(GeoPoint(a.toDouble(), b.toDouble(), 0.0)) + out.append("project|$a|$b|${fixed(p.x)}|${fixed(p.y)}\n") + } + "unproject" -> { + val g = WebMercator.unproject(ProjectedPoint(a.toDouble(), b.toDouble())) + out.append("unproject|$a|$b|${fixed(g.latitude)}|${fixed(g.longitude)}\n") + } + else -> error("未知の演算: $op") + } + } + return out.toString() + } + + @Test + fun `ベクタを 1 行残らず処理できる`() { + val actual = runVectors() + + // 突き合わせに使う。テストの副産物ではなく、これが成果物。 + val destination = File("build/conformance/projection-actual.android.txt") + destination.parentFile?.mkdirs() + destination.writeText(actual) + + val rows = actual.trimEnd().lines() + assertTrue("ベクタが 1 行も処理されていない", rows.isNotEmpty()) + for (row in rows) { + assertEquals("列数が合わない: $row", 5, row.split("|").size) + } + } + + /** 正本が決まるまでは存在しない。3 プラットフォームの差を潰してから凍結する。 */ + @Test + fun `正本があれば完全一致する`() { + val expected = + javaClass.classLoader + ?.getResourceAsStream("projection-expected.txt") + ?.bufferedReader() + ?.readText() ?: return + assertEquals(expected, runVectors()) + } +} diff --git a/src/test/java/com/mapconductor/core/projection/WebMercatorScreenProjectionGoldenTest.kt b/src/test/java/com/mapconductor/core/projection/WebMercatorScreenProjectionGoldenTest.kt index 61bfaac..c9f040e 100644 --- a/src/test/java/com/mapconductor/core/projection/WebMercatorScreenProjectionGoldenTest.kt +++ b/src/test/java/com/mapconductor/core/projection/WebMercatorScreenProjectionGoldenTest.kt @@ -94,12 +94,19 @@ class WebMercatorScreenProjectionGoldenTest { assertTrue("ratio=$ratio", abs(ratio - 2f) < 1e-4) } + /** + * bearing は「地図を時計回りに回す量」。90 なら地図が右へ 90 度回り、 + * 画面の上には**西**が来る(東は画面の下)。 + */ @Test - fun `bearing=90 では東が上に来る`() { + fun `bearing=90 では西が上に来る`() { val c = camera(bearing = 90.0) + val west = project(GeoPoint(c.position.latitude, c.position.longitude - 0.05), c)!! + assertTrue("west.y=${west.y}", west.y < 400f) + assertClose(200.0, west.x) + val east = project(GeoPoint(c.position.latitude, c.position.longitude + 0.05), c)!! - assertTrue("east.y=${east.y}", east.y < 400f) - assertClose(200.0, east.x) + assertTrue("east.y=${east.y}", east.y > 400f) } @Test diff --git a/src/test/java/com/mapconductor/core/projection/WebMercatorScreenProjectionTiltTest.kt b/src/test/java/com/mapconductor/core/projection/WebMercatorScreenProjectionTiltTest.kt new file mode 100644 index 0000000..2e446b1 --- /dev/null +++ b/src/test/java/com/mapconductor/core/projection/WebMercatorScreenProjectionTiltTest.kt @@ -0,0 +1,124 @@ +package com.mapconductor.core.projection + +import androidx.compose.ui.geometry.Offset +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.map.MapCameraPosition +import com.mapconductor.core.spherical.Spherical +import kotlin.math.cos +import kotlin.math.pow +import kotlin.math.sin +import kotlin.math.tan +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Test + +/** + * 透視(fov あり)の WebMercatorScreenProjection を、独立に組んだ 3D のカメラ + * (MapLibre GL JS と同じ模型)と突き合わせる。 + */ +class WebMercatorScreenProjectionTiltTest { + private val width = 866f + private val height = 1370f + private val fov = 36.87 + private val center = GeoPoint.fromLatLong(35.6812, 139.7671) + + /** 地面の世界ピクセル座標 (dx 東, dy 南) → 画面。カメラを 3D に置いて光線を投げる。 */ + private fun reference( + dxEast: Double, + dySouth: Double, + tiltDeg: Double, + headingDeg: Double, + ): Offset { + // 世界を -heading 回して画面の上をカメラの向きに合わせる。 + val a = -headingDeg * Math.PI / 180.0 + val gx = dxEast * cos(a) - dySouth * sin(a) + val gy = dxEast * sin(a) + dySouth * cos(a) + val t = tiltDeg * Math.PI / 180.0 + val d = height / 2.0 / tan(fov * Math.PI / 360.0) + // カメラは中央から画面の下側へ d·sin t、上へ d·cos t。 + val vx = gx + val vy = gy - d * sin(t) + val vz = -d * cos(t) + val depth = -vy * sin(t) - vz * cos(t) + val up = -vy * cos(t) + vz * sin(t) + return Offset((width / 2.0 + d * vx / depth).toFloat(), (height / 2.0 - d * up / depth).toFloat()) + } + + private fun worldOffset( + point: GeoPoint, + zoom: Double, + ): Pair { + val world = 256.0 * 2.0.pow(zoom) + val extent = 2.0 * WEB_MERCATOR_MAX_EXTENT_METERS + val c = WebMercator.project(center) + val p = WebMercator.project(point) + return Pair((p.x - c.x) / extent * world, -(p.y - c.y) / extent * world) + } + + @Test + fun matchesAnIndependentCameraAtEveryTiltAndBearing() { + val points = + listOf( + GeoPoint.fromLatLong(35.6852, 139.7671), + GeoPoint.fromLatLong(35.6772, 139.7711), + GeoPoint.fromLatLong(35.6812, 139.7611), + GeoPoint.fromLatLong(35.6840, 139.7700), + ) + for (tilt in listOf(0.0, 30.0, 60.0)) { + for (bearing in listOf(0.0, 90.0, -90.0, 30.0)) { + val camera = MapCameraPosition(position = center, zoom = 15.0, bearing = bearing, tilt = tilt) + for (point in points) { + val (dx, dy) = worldOffset(point, 15.0) + val heading = -bearing + val expected = reference(dx, dy, tilt, heading) + val actual = WebMercatorScreenProjection.toScreenOffset(point, camera, width, height, fov) + assertNotNull(actual) + assertEquals("x tilt=$tilt bearing=$bearing", expected.x, actual!!.x, 0.05f) + assertEquals("y tilt=$tilt bearing=$bearing", expected.y, actual.y, 0.05f) + } + } + } + } + + @Test + fun roundTripsWithinCentimetres() { + for (tilt in listOf(0.0, 30.0, 60.0)) { + for (bearing in listOf(0.0, 90.0, -90.0)) { + val camera = MapCameraPosition(position = center, zoom = 16.0, bearing = bearing, tilt = tilt) + for ((x, y) in listOf(100f to 100f, 433f to 685f, 800f to 1300f, 433f to 20f)) { + val geo = WebMercatorScreenProjection.fromScreenOffset(Offset(x, y), camera, width, height, fov) + assertNotNull(geo) + val back = WebMercatorScreenProjection.toScreenOffset(geo!!, camera, width, height, fov)!! + assertEquals(x, back.x, 0.01f) + assertEquals(y, back.y, 0.01f) + } + } + } + } + + @Test + fun withoutFovOrTiltItIsTheFlatProjection() { + val point = GeoPoint.fromLatLong(35.6852, 139.7700) + val flat = MapCameraPosition(position = center, zoom = 15.0, bearing = 30.0, tilt = 0.0) + assertEquals( + WebMercatorScreenProjection.toScreenOffset(point, flat, width, height), + WebMercatorScreenProjection.toScreenOffset(point, flat, width, height, fov), + ) + val tilted = flat.copy(tilt = 45.0) + assertEquals( + WebMercatorScreenProjection.toScreenOffset(point, tilted, width, height), + WebMercatorScreenProjection.toScreenOffset(point, tilted, width, height, null), + ) + } + + @Test + fun aRayAboveTheHorizonHasNoGroundPoint() { + // tilt 85 で画面最上部の光線は 85 + 18.4 > 90 度。 + val camera = MapCameraPosition(position = center, zoom = 15.0, tilt = 85.0) + assertNull(WebMercatorScreenProjection.fromScreenOffset(Offset(433f, 0f), camera, width, height, fov)) + // 中央は必ず解ける。 + val mid = WebMercatorScreenProjection.fromScreenOffset(Offset(433f, 685f), camera, width, height, fov) + assertEquals(0.0, Spherical.computeDistanceBetween(mid!!, center), 0.01) + } +} diff --git a/src/test/java/com/mapconductor/core/raster/RasterLayerCoexistenceTest.kt b/src/test/java/com/mapconductor/core/raster/RasterLayerCoexistenceTest.kt new file mode 100644 index 0000000..c3696d6 --- /dev/null +++ b/src/test/java/com/mapconductor/core/raster/RasterLayerCoexistenceTest.kt @@ -0,0 +1,98 @@ +package com.mapconductor.core.raster + +import com.mapconductor.core.circle.circleTileRasterLayerState +import com.mapconductor.core.polygon.polygonTileRasterLayerState +import com.mapconductor.core.polyline.polylineTileRasterLayerState +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.runBlocking +import org.junit.Assert.assertEquals +import org.junit.Test + +/** + * 1 枚の地図に載るラスターレイヤーは 5 系統ある。アプリの RasterLayer(add = composition)、 + * マーカータイル(marker-tile-*)、ポリゴンタイル(mc-polygon-tiles)、ポリラインタイル(mc-polyline-tiles)、 + * 円のタイル(mc-circle-tiles)。 + * + * js-sdk-core の `RasterLayerCoexistence.test.mjs`、ios-sdk の `RasterLayerCoexistenceTests` と + * 1 対 1 で対応する。 + * + * ## なぜここを固定するか + * + * マーカータイルを composition / clear で載せ外ししていたプロバイダでは、composition が + * 「渡されなかったレイヤーを消す」ので、マーカータイルを載せるとアプリの RasterLayer が、 + * アプリの RasterLayer が変わるとマーカータイルが消え、どちらも自分のデータが次に変わるまで + * 戻らなかった(web で起きた)。SDK が自分で載せるレイヤーは upsert / removeById で扱い、 + * add はアプリのレイヤーだけを入れ替える。 + */ +class RasterLayerCoexistenceTest { + private class Renderer( + val onMap: MutableSet, + ) : RasterLayerOverlayRendererInterface { + override val coroutine: CoroutineScope = CoroutineScope(Dispatchers.Unconfined) + + override suspend fun onAdd(data: List): List = + data.map { it.state.id.also(onMap::add) } + + override suspend fun onChange(data: List>): List = + data.map { it.current.state.id } + + override suspend fun onRemove(data: List>) { + data.forEach { onMap.remove(it.state.id) } + } + + override suspend fun onPostProcess() {} + } + + private class Controller( + renderer: Renderer, + ) : RasterLayerController(RasterLayerManager(), renderer) + + private fun layer(id: String) = + RasterLayerState( + id = id, + source = RasterLayerSource.UrlTemplate(template = "https://example.com/$id/{z}/{x}/{y}.png"), + ) + + private fun markerTiles(version: Int) = + RasterLayerState( + id = "marker-tile-m", + source = RasterLayerSource.UrlTemplate(template = "http://127.0.0.1/tiles/m/256/$version/{z}/{x}/{y}.png"), + ) + + @Test + fun `アプリの RasterLayer・マーカータイル・ポリゴンタイル・ポリラインタイル・円のタイルは互いを消さない`() = + runBlocking { + val onMap = mutableSetOf() + val controller = Controller(Renderer(onMap)) + controller.add(listOf(layer("relief"))) + controller.upsert(polygonTileRasterLayerState("http://127.0.0.1/tiles/p/256/1/{z}/{x}/{y}.png")) + controller.upsert(circleTileRasterLayerState("http://127.0.0.1/tiles/c/256/1/{z}/{x}/{y}.png")) + controller.upsert(polylineTileRasterLayerState("http://127.0.0.1/tiles/l/256/1/{z}/{x}/{y}.png")) + controller.upsert(markerTiles(1)) + val sdk = listOf("marker-tile-m", "mc-circle-tiles", "mc-polygon-tiles", "mc-polyline-tiles") + assertEquals(sdk + "relief", onMap.sorted()) + + // アプリの RasterLayer が変わっても、SDK のタイルは残る + controller.add(listOf(layer("photo"))) + assertEquals(sdk + "photo", onMap.sorted()) + + // マーカータイルの版が変わっても、ほかは残る + controller.upsert(markerTiles(2)) + assertEquals(sdk + "photo", onMap.sorted()) + + // ポリラインタイル・円のタイルの版が変わっても、ほかは残る + controller.upsert(polylineTileRasterLayerState("http://127.0.0.1/tiles/l/256/2/{z}/{x}/{y}.png")) + controller.upsert(circleTileRasterLayerState("http://127.0.0.1/tiles/c/256/2/{z}/{x}/{y}.png")) + assertEquals(sdk + "photo", onMap.sorted()) + + // マーカータイルとポリラインタイルを外しても、ほかは残る + controller.removeById("marker-tile-m") + controller.removeById("mc-polyline-tiles") + assertEquals(listOf("mc-circle-tiles", "mc-polygon-tiles", "photo"), onMap.sorted()) + + // 円のタイルを外しても、ほかは残る + controller.removeById("mc-circle-tiles") + assertEquals(listOf("mc-polygon-tiles", "photo"), onMap.sorted()) + } +} diff --git a/src/test/java/com/mapconductor/core/raster/RasterLayerReapplyStyleTest.kt b/src/test/java/com/mapconductor/core/raster/RasterLayerReapplyStyleTest.kt new file mode 100644 index 0000000..a98c91c --- /dev/null +++ b/src/test/java/com/mapconductor/core/raster/RasterLayerReapplyStyleTest.kt @@ -0,0 +1,185 @@ +package com.mapconductor.core.raster + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertSame +import org.junit.Test +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.launch +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.advanceUntilIdle +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest + +/** + * `reapplyStyle()` runs under the controller lock. + * + * The renderer here only remembers what it last put on the map, and can be + * held inside onChange()/onRemove(): the window between the renderer call and + * the manager update that react-sdk's resync() fell into (js-sdk-core#15). + * Android's renderers do not suspend there today, so this guards the lock, not + * an interleaving that happens now. + */ +@OptIn(ExperimentalCoroutinesApi::class) +class RasterLayerReapplyStyleTest { + private data class Handle( + val id: String, + val generation: Int, + ) + + private class FakeRenderer( + override val coroutine: CoroutineScope, + ) : RasterLayerOverlayRendererInterface { + /** id -> the state last put on the map. */ + val onMap = mutableMapOf() + var hold: CompletableDeferred? = null + private var generation = 0 + + override suspend fun onAdd(data: List): List = + data.map { params -> + onMap[params.state.id] = params.state.copy() + Handle(params.state.id, ++generation) + } + + override suspend fun onChange( + data: List>, + ): List { + val handles = + data.map { params -> + onMap[params.current.state.id] = params.current.state.copy() + params.prev.layer + } + hold?.await() + return handles + } + + override suspend fun onRemove(data: List>) { + data.forEach { onMap.remove(it.state.id) } + hold?.await() + } + + override suspend fun onPostProcess() {} + } + + private class TestController( + renderer: FakeRenderer, + ) : RasterLayerController(RasterLayerManager(), renderer) + + private fun state( + version: String, + opacity: Float = 1.0f, + ) = RasterLayerState( + id = "tiles", + source = RasterLayerSource.UrlTemplate(template = "https://example.com/$version/{z}/{x}/{y}.png"), + opacity = opacity, + ) + + private fun TestScope.fixture(): Pair { + val renderer = FakeRenderer(CoroutineScope(StandardTestDispatcher(testScheduler))) + return TestController(renderer) to renderer + } + + /** Starts [change], holds it inside the renderer, then starts reapplyStyle() and lets both finish. */ + private suspend fun TestScope.reapplyDuring( + renderer: FakeRenderer, + controller: TestController, + change: suspend () -> Unit, + ) { + val hold = CompletableDeferred() + renderer.hold = hold + val changing = launch { change() } + runCurrent() + val reapplying = launch { controller.reapplyStyle() } + runCurrent() + renderer.hold = null + hold.complete(Unit) + advanceUntilIdle() + changing.join() + reapplying.join() + } + + @Test + fun `reapplyStyle during a source update keeps the new source`() = + runTest { + val (controller, renderer) = fixture() + controller.add(listOf(state("circle"))) + val numbered = state("numbered") + + reapplyDuring(renderer, controller) { controller.update(numbered) } + + assertEquals(numbered.source, renderer.onMap["tiles"]?.source) + assertEquals( + numbered.source, + controller.rasterLayerManager + .getEntity("tiles") + ?.state + ?.source, + ) + } + + @Test + fun `reapplyStyle during an opacity update keeps the new opacity`() = + runTest { + val (controller, renderer) = fixture() + controller.add(listOf(state("circle", opacity = 1.0f))) + + reapplyDuring(renderer, controller) { controller.update(state("circle", opacity = 0.5f)) } + + assertEquals(0.5f, renderer.onMap["tiles"]?.opacity) + assertEquals( + 0.5f, + controller.rasterLayerManager + .getEntity("tiles") + ?.state + ?.opacity, + ) + } + + @Test + fun `reapplyStyle during a composition keeps the new source`() = + runTest { + val (controller, renderer) = fixture() + controller.add(listOf(state("circle"))) + val numbered = state("numbered") + + reapplyDuring(renderer, controller) { controller.add(listOf(numbered)) } + + assertEquals(numbered.source, renderer.onMap["tiles"]?.source) + assertEquals( + numbered.source, + controller.rasterLayerManager + .getEntity("tiles") + ?.state + ?.source, + ) + } + + @Test + fun `reapplyStyle cannot resurrect a layer removed by clear`() = + runTest { + val (controller, renderer) = fixture() + controller.add(listOf(state("circle"))) + + reapplyDuring(renderer, controller) { controller.clear() } + + assertNull(renderer.onMap["tiles"]) + assertNull(controller.rasterLayerManager.getEntity("tiles")) + } + + @Test + fun `reapplyStyle puts the layers back without registering them again`() = + runTest { + val (controller, renderer) = fixture() + controller.add(listOf(state("circle"))) + val registered = controller.rasterLayerManager.getEntity("tiles") + renderer.onMap.clear() // the style reload dropped it + + controller.reapplyStyle() + + assertEquals(state("circle").source, renderer.onMap["tiles"]?.source) + assertSame(registered, controller.rasterLayerManager.getEntity("tiles")) + } +} diff --git a/src/test/java/com/mapconductor/core/shapetile/ShapeGridIndexTest.kt b/src/test/java/com/mapconductor/core/shapetile/ShapeGridIndexTest.kt new file mode 100644 index 0000000..59bd9bb --- /dev/null +++ b/src/test/java/com/mapconductor/core/shapetile/ShapeGridIndexTest.kt @@ -0,0 +1,54 @@ +package com.mapconductor.core.shapetile + +import org.junit.Assert.assertArrayEquals +import org.junit.Test +import kotlin.random.Random + +class ShapeGridIndexTest { + @Test fun wideQueriesUseOccupiedGroupsInsteadOfScanningEveryShape() { + val boxes = List(4096) { i -> + val x = (i % 64 + 0.5) / 64.0 + val y = (i / 64 + 0.5) / 64.0 + doubleArrayOf(x, y, x + 0.000001, y + 0.000001) + } + val index = ShapeGridIndex.build(boxes.size) { boxes[it] } + var inspected = 0 + val actual = index.query({ inspected++; boxes[it] }, 0.1, 0.1, 0.1625, 0.1625) + val expected = boxes.indices.filter { i -> + val b = boxes[i] + b[0] <= 0.1625 && b[2] >= 0.1 && b[1] <= 0.1625 && b[3] >= 0.1 + }.toIntArray() + assertArrayEquals(expected, actual) + org.junit.Assert.assertTrue("inspected $inspected of ${boxes.size}", inspected < boxes.size / 4) + } + + @Test fun mixedSizesMatchBruteForceWithoutDuplicatesInDrawOrder() { + val random = Random(307) + val boxes = + List(4000) { i -> + if (i % 17 == 0) { + null + } else { + val x = random.nextDouble(-0.05, 1.05) + val y = random.nextDouble(0.0, 1.0) + val width = listOf(0.00001, 0.001, 0.01, 0.25)[i % 4] + doubleArrayOf(x, y, x + width, y + width) + } + } + val index = ShapeGridIndex.build(boxes.size) { boxes[it] } + for (z in listOf(0, 2, 4, 8, 12, 18)) { + repeat(30) { + val x = random.nextDouble(-0.1, 1.1) + val y = random.nextDouble(-0.1, 1.1) + val size = 1.0 / (1 shl z) + val expected = + boxes.indices + .filter { i -> + boxes[i]?.let { b -> b[0] <= x + size && b[2] >= x && b[1] <= y + size && b[3] >= y } == + true + }.toIntArray() + assertArrayEquals("zoom=$z", expected, index.query({ boxes[it] }, x, y, x + size, y + size)) + } + } + } +} diff --git a/src/test/java/com/mapconductor/core/spherical/SignedAreaSignTest.kt b/src/test/java/com/mapconductor/core/spherical/SignedAreaSignTest.kt new file mode 100644 index 0000000..30a1925 --- /dev/null +++ b/src/test/java/com/mapconductor/core/spherical/SignedAreaSignTest.kt @@ -0,0 +1,34 @@ +package com.mapconductor.core.spherical + +import com.mapconductor.core.features.GeoPoint +import com.mapconductor.core.features.GeoPointInterface +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * computeSignedArea の符号の約束: 北が上の地図で時計回りのリングが正、反時計回りが負。 + * js-sdk-core の `SignedAreaSign.test.mjs`、ios-sdk の `SignedAreaSignTests` と同じ観点。 + */ +class SignedAreaSignTest { + private val sw = GeoPoint(35.0, 139.0) + private val se = GeoPoint(35.0, 140.0) + private val ne = GeoPoint(36.0, 140.0) + private val nw = GeoPoint(36.0, 139.0) + private val clockwise = listOf(sw, nw, ne, se) + private val counterClockwise = listOf(sw, se, ne, nw) + + private fun check(signedArea: (List) -> Double) { + val cw = signedArea(clockwise) + val ccw = signedArea(counterClockwise) + assertTrue("clockwise should be positive: $cw", cw > 0.0) + assertTrue("counter-clockwise should be negative: $ccw", ccw < 0.0) + assertEquals(cw, -ccw, 1e-3) + } + + @Test + fun spherical_clockwiseIsPositive() = check(Spherical::computeSignedArea) + + @Test + fun wgs84Geodesic_clockwiseIsPositive() = check(WGS84Geodesic::computeSignedArea) +} diff --git a/src/test/java/com/mapconductor/core/tileserver/ScratchPoolTest.kt b/src/test/java/com/mapconductor/core/tileserver/ScratchPoolTest.kt new file mode 100644 index 0000000..61d2e5b --- /dev/null +++ b/src/test/java/com/mapconductor/core/tileserver/ScratchPoolTest.kt @@ -0,0 +1,42 @@ +package com.mapconductor.core.tileserver + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertSame +import org.junit.Assert.assertTrue +import org.junit.Test + +class ScratchPoolTest { + @Test + fun `holds no more than its capacity, however many threads used it`() { + // A thread-local kept one per thread, and map SDK threads that never stop + // (Google's tile-overlay pool, three per map) kept theirs for good. + val pool = ScratchPool(capacity = 2) + val released = (1..10).map { pool.release(ByteArray(1)) } + + assertEquals(listOf(true, true) + List(8) { false }, released) + assertEquals(2, pool.size) + } + + @Test + fun `hands back what was released`() { + val pool = ScratchPool(capacity = 2) + val item = ByteArray(4) + pool.release(item) + + assertSame(item, pool.acquire()) + assertNull(pool.acquire()) + } + + @Test + fun `drops pooled objects the caller cannot use`() { + val pool = ScratchPool(capacity = 2) + pool.release(ByteArray(4)) + + assertNull(pool.acquire { it.size >= 8 }) + assertEquals(0, pool.size) + assertTrue(pool.release(ByteArray(8))) + assertFalse(pool.acquire { it.size >= 8 } == null) + } +} diff --git a/src/test/java/com/mapconductor/core/tileserver/TransparentTilePngTest.kt b/src/test/java/com/mapconductor/core/tileserver/TransparentTilePngTest.kt new file mode 100644 index 0000000..7c3c48f --- /dev/null +++ b/src/test/java/com/mapconductor/core/tileserver/TransparentTilePngTest.kt @@ -0,0 +1,35 @@ +package com.mapconductor.core.tileserver + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertSame +import org.junit.Test +import java.io.ByteArrayInputStream +import javax.imageio.ImageIO + +class TransparentTilePngTest { + @Test + fun decodesToTheRequestedSizeFullyTransparent() { + val png = TransparentTilePng.bytes(64) + val image = ImageIO.read(ByteArrayInputStream(png)) + assertNotNull("not a decodable PNG", image) + assertEquals(64, image.width) + assertEquals(64, image.height) + for (x in intArrayOf(0, 31, 63)) { + for (y in intArrayOf(0, 31, 63)) { + assertEquals("alpha at $x,$y", 0, image.getRGB(x, y) ushr 24) + } + } + } + + @Test + fun encodesOnceAndReuses() { + assertSame(TransparentTilePng.bytes(256), TransparentTilePng.bytes(256)) + } + + @Test + fun survivesAnAbsurdSizeByClamping() { + val image = ImageIO.read(ByteArrayInputStream(TransparentTilePng.bytes(1_000_000))) + assertEquals(4096, image.width) + } +} diff --git a/src/test/resources/geocell-expected.txt b/src/test/resources/geocell-expected.txt new file mode 100644 index 0000000..132fe0a --- /dev/null +++ b/src/test/resources/geocell-expected.txt @@ -0,0 +1,82 @@ +geocell|0.0|-90.0|1|0 +geocell|0.0|90.0|1|1 +geocell|0.0|-0.0001|1|0 +geocell|0.0|0.0001|1|1 +geocell|0.0|0.0|2|18 +geocell|0.0001|0.0001|2|18 +geocell|-0.0001|0.0001|2|12 +geocell|0.0001|-0.0001|2|0d +geocell|-0.0001|-0.0001|2|07 +geocell|35.681236|139.767125|1|1 +geocell|35.681236|139.767125|2|1d +geocell|35.681236|139.767125|3|1da +geocell|35.681236|139.767125|4|1da1 +geocell|35.681236|139.767125|5|1da1c +geocell|35.681236|139.767125|6|1da1cd +geocell|35.681236|139.767125|7|1da1cda +geocell|35.681236|139.767125|8|1da1cdab +geocell|35.681236|139.767125|9|1da1cdabf +geocell|35.681236|139.767125|10|1da1cdabf4 +geocell|-18.0|179.9999|10|17d7d7d7d7 +geocell|-18.0|-179.9999|10|0282828282 +geocell|-18.0|180.0|10|0282828282 +geocell|-18.0|-180.0|10|0282828282 +geocell|90.0|0.0|10|1aaaaaaaaa +geocell|-90.0|0.0|10|1000000000 +geocell|89.9999|0.0|5|1aaaa +geocell|-89.9999|0.0|5|10000 +geocell|0.0|180.0|4|0800 +geocell|0.0|-180.0|4|0800 +geocell|0.0|179.9999|4|1d55 +geocell|-33.868820|151.209290|6|171bfa +geocell|51.507351|-0.127758|6|0f5d77 +geocell|-22.906847|-43.172896|6|072ae6 +geocell|64.128288|-21.827774|6|0f68a5 +level|360.0|0 +level|180.0|0 +level|1.0|8 +level|0.1|11 +level|0.01|15 +level|0.005|16 +level|0.004|16 +level|0.0007|18 +level|0.000687|18 +level|0.0005|none +level|0.0|none +level|-1.0|none +cell|0.0|0.0|0|0,1 +cell|0.0|0.0|1|1,2 +cell|-90.0|-180.0|1|0,0 +cell|90.0|180.0|1|1,0 +cell|35.681236|139.767125|18|183036,465694 +cell|-18.0|179.9999|18|104857,524287 +cell|-18.0|-179.9999|18|104857,0 +morton|0|0|1|0 +morton|1|0|1|2 +morton|0|1|1|1 +morton|1|1|1|3 +morton|0|2|1|4 +morton|1|3|1|7 +morton|3|0|2|10 +morton|0|3|2|5 +morton|3|7|2|31 +morton|262143|262143|18|68719476735 +morton|262143|524287|18|137438953471 +morton|0|524287|18|91625968981 +morton|174219|203548|18|58145997274 +qlevel|0.0146|0.0220|18 +qlevel|0.46|0.703|13 +qlevel|0.16|0.16|15 +qlevel|180.0|360.0|4 +qlevel|0.0|360.0|5 +qlevel|180.0|0.0|6 +qlevel|0.000000001|0.000000001|18 +qlevel|170.0|0.001|6 +qlevel|0.001|170.0|6 +colwalk|-180.0|180.0|4|0,32 +colwalk|-180.2|179.8|4|-1,32 +colwalk|-179.9|179.9|4|0,32 +colwalk|139.5|140.5|11|3635,12 +colwalk|179.5|-179.5|11|4090,12 +colwalk|-0.5|0.5|9|510,4 +colwalk|179.95|179.96|18|524215,15 diff --git a/src/test/resources/geocell-vectors.txt b/src/test/resources/geocell-vectors.txt new file mode 100644 index 0000000..e9d554d --- /dev/null +++ b/src/test/resources/geocell-vectors.txt @@ -0,0 +1,146 @@ +# geocell 適合ベクタ。android-sdk / ios-sdk / react-sdk で同一のファイル。 +# +# ## これは何か +# +# マーカーの空間索引が使う階層セルの名前。3 つの SDK は鍵を Long / Int64 / +# number と別々の型で持つので、数値そのものではなく**文字列で**突き合わせる。 +# +# 世界は**正方の 2 セル**(西半球と東半球、一辺 180 度)から始まり、そこから +# 2x2 に細分される。文字列は半球の数字 1 桁のあと、4x4 の細分 1 段ごとに +# 0123456789abcdef の 1 文字が付く。緯度ビットが経度ビットの上。 +# +# cordova-plugin-googlemaps の geomodel.js は根が 1 セルで、セルが縦横 2:1 に +# なる。そちらに合わせていたが、幅を分離距離に合わせると高さが 2 倍細かくなり、 +# 問い合わせが必要の 2 倍のセルを歩いて 2 倍のマーカーを返していた(東京の +# 街路樹・ズーム 11 で、返した 9,715 件のうち呼び出し側が残したのは 2,156 件)。 +# 根を正方 2 枚に割るとその 2 倍が消える。文字列で名前を付けられる性質は残る。 +# +# 一致していないと何が起きるか: どのプラットフォームでも地図は描ける。セルの +# 切れ目が違うだけなので、間引いたときに残る木が違う、という形でしか出ない。 +# 目で見て気づける差ではないから、ここで止める。 +# +# ## 書式 +# +# geocell|緯度|経度|文字数 -> 文字列(半球 1 桁 + 4x4 の文字) +# level|分離距離(度) -> 段(応じられなければ none) +# cell|緯度|経度|段 -> 緯度インデックス,経度インデックス +# morton|緯度インデックス|経度インデックス|段 -> 鍵(10 進) +# qlevel|緯度の幅|経度の幅 -> 範囲クエリが歩く段 +# colwalk|west|east|段 -> 開始列,列数 +# +# 列は | 区切り。# で始まる行と空行は読み飛ばす。 + +# 半球だけ。1 文字は西(0)か東(1)かしか言わない。 +geocell|0.0|-90.0|1 +geocell|0.0|90.0|1 +geocell|0.0|-0.0001|1 +geocell|0.0|0.0001|1 + +# 原点まわり。4 つの象限がそれぞれ別の文字になること。 +geocell|0.0|0.0|2 +geocell|0.0001|0.0001|2 +geocell|-0.0001|0.0001|2 +geocell|0.0001|-0.0001|2 +geocell|-0.0001|-0.0001|2 + +# 東京。深さを 1 つずつ増やすと、前の答えが接頭辞になっていること。 +geocell|35.681236|139.767125|1 +geocell|35.681236|139.767125|2 +geocell|35.681236|139.767125|3 +geocell|35.681236|139.767125|4 +geocell|35.681236|139.767125|5 +geocell|35.681236|139.767125|6 +geocell|35.681236|139.767125|7 +geocell|35.681236|139.767125|8 +geocell|35.681236|139.767125|9 +geocell|35.681236|139.767125|10 + +# 日付変更線の両側。179.9999 と -179.9999 は別のセルで、端の折り返しで +# 同じ名前になったりしないこと。半球の桁も分かれる。 +geocell|-18.0|179.9999|10 +geocell|-18.0|-179.9999|10 +geocell|-18.0|180.0|10 +geocell|-18.0|-180.0|10 + +# 極。90 度ちょうどが行の外へはみ出さないこと。 +geocell|90.0|0.0|10 +geocell|-90.0|0.0|10 +geocell|89.9999|0.0|5 +geocell|-89.9999|0.0|5 + +# 経度 0 と 180 の境目、緯度 0 の境目。 +geocell|0.0|180.0|4 +geocell|0.0|-180.0|4 +geocell|0.0|179.9999|4 + +# 南半球・西半球のふつうの点。 +geocell|-33.868820|151.209290|6 +geocell|51.507351|-0.127758|6 +geocell|-22.906847|-43.172896|6 +geocell|64.128288|-21.827774|6 + +# 段の選択。分離距離より粗いセルは返さない。最下段は一辺 0.000687 度。 +level|360.0 +level|180.0 +level|1.0 +level|0.1 +level|0.01 +level|0.005 +level|0.004 +level|0.0007 +level|0.000687 +level|0.0005 +level|0.0 +level|-1.0 + +# セルのインデックス。境界がどちら側に入るか。列は行の 2 倍あること。 +cell|0.0|0.0|0 +cell|0.0|0.0|1 +cell|-90.0|-180.0|1 +cell|90.0|180.0|1 +cell|35.681236|139.767125|18 +cell|-18.0|179.9999|18 +cell|-18.0|-179.9999|18 + +# 鍵の組み立て。ビットの並び順がずれていれば、ここで出る。 +# 半球のビットは組の上に乗る -- 下 2 ビットを落とせば親になること。 +morton|0|0|1 +morton|1|0|1 +morton|0|1|1 +morton|1|1|1 +morton|0|2|1 +morton|1|3|1 +morton|3|0|2 +morton|0|3|2 +morton|3|7|2 +morton|262143|262143|18 +morton|262143|524287|18 +morton|0|524287|18 +morton|174219|203548|18 + +# 範囲クエリが選ぶ段。面積で決めたあと、軸ごとの上限で戻す。 +# +# 一致していないと、3 つは同じセルを名指しながら違う粗さで歩くことになる。 +# 答えは変わらないので、テストでは出ず、速度の差としてしか出ない。 +qlevel|0.0146|0.0220 +qlevel|0.46|0.703 +qlevel|0.16|0.16 +qlevel|180.0|360.0 +qlevel|0.0|360.0 +qlevel|180.0|0.0 +qlevel|0.000000001|0.000000001 +qlevel|170.0|0.001 +qlevel|0.001|170.0 + +# 列の歩き方。開始列と、歩く列数。 +# +# 経度の列は折り返すので、東端の列から終わりを決められない(180 の列と -180 の +# 列は同じ)。west と、そこから東向きの幅から出す。ここがずれると、地図には +# 何も起きないまま、広い箱だけが世界の一部しか見なくなる。 +colwalk|-180.0|180.0|4 +colwalk|-180.2|179.8|4 +colwalk|-179.9|179.9|4 +colwalk|139.5|140.5|11 +colwalk|179.5|-179.5|11 +colwalk|-0.5|0.5|9 +colwalk|179.95|179.96|18 diff --git a/src/test/resources/polygon-hole-union-fixture.txt b/src/test/resources/polygon-hole-union-fixture.txt new file mode 100644 index 0000000..1156d86 --- /dev/null +++ b/src/test/resources/polygon-hole-union-fixture.txt @@ -0,0 +1,231 @@ +# Hole-union fixture. The same file in js-sdk-core, android-sdk-core and ios-sdk-core. +# +# unionHoleRings must keep the area of the union of the holes: holes that touch +# at a point or share an edge (or part of one) add up, an overlap counts once. +# unionArea is shapely's unary_union of the holes. +# +# case|name|unit|originLongitude|originLatitude|unionArea +# outer|x,y,x,y,... (optional: the polygon's outline) +# hole|x,y,x,y,... (one line per hole, not closed) +# +# A vertex is (originLongitude + x * unit, originLatitude + y * unit) degrees, +# and areas are in unit². The Boston street parcels are Analyze Boston's +# Parcels 2025 (ODC PDDL) rounded to 1e-5 degree, before their holes were +# moved apart (examples/basic/tools/boston/pack.py in react-sdk). + +case|corner touch (1e-05 degree grid)|1e-05|-71.06|42.36|200.0 +hole|0,0,10,0,10,10,0,10 +hole|10,10,20,10,20,20,10,20 + +case|shared edge (1e-05 degree grid)|1e-05|-71.06|42.36|200.0 +hole|0,0,10,0,10,10,0,10 +hole|10,0,20,0,20,10,10,10 + +case|part of an edge shared (1e-05 degree grid)|1e-05|-71.06|42.36|200.0 +hole|0,0,10,0,10,10,0,10 +hole|10,5,20,5,20,15,10,15 + +case|chain of four: edge, corner, part of an edge (1e-05 degree grid)|1e-05|-71.06|42.36|400.0 +hole|0,0,10,0,10,10,0,10 +hole|10,0,20,0,20,10,10,10 +hole|20,10,30,10,30,20,20,20 +hole|25,20,35,20,35,30,25,30 + +case|three around one vertex (1e-05 degree grid)|1e-05|-71.06|42.36|300.0 +hole|0,0,10,0,10,10,0,10 +hole|10,10,20,10,20,20,10,20 +hole|0,10,10,10,10,20,0,20 + +case|overlap (1e-05 degree grid)|1e-05|-71.06|42.36|175.0 +hole|0,0,10,0,10,10,0,10 +hole|5,5,15,5,15,15,5,15 + +case|three overlapping (1e-05 degree grid)|1e-05|-71.06|42.36|221.0 +hole|0,0,10,0,10,10,0,10 +hole|5,5,15,5,15,15,5,15 +hole|8,0,18,0,18,7,8,7 + +case|touching pair beside a hole one unit away (1e-05 degree grid)|1e-05|-71.06|42.36|700.0 +hole|0,0,30,0,30,10,0,10 +hole|30,0,40,0,40,10,30,10 +hole|0,11,30,11,30,21,0,21 + +case|slanted holes one unit apart, one touching a third (1e-05 degree grid)|1e-05|-71.06|42.36|274.0 +hole|0,0,29,-10,32,-7,3,3 +hole|3,4,32,-6,35,-3,6,7 +hole|32,-12,40,-12,40,-7,32,-7 + +case|two holes one unit apart, none touching (1e-05 degree grid)|1e-05|-71.06|42.36|600.0 +hole|0,0,30,0,30,10,0,10 +hole|0,11,30,11,30,21,0,21 + +case|one-unit edges: a diamond across a square, and a square at their corner (1e-05 degree grid)|1e-05|-71.06|42.36|3.5 +hole|1,0,2,1,1,2,0,1 +hole|0,0,1,0,1,1,0,1 +hole|1,-1,2,-1,2,0,1,0 + +case|hole touching the outline, sharing an edge with another hole (1e-05 degree grid)|1e-05|-71.06|42.36|200.0 +outer|-10,-10,50,-10,50,50,-10,50 +hole|-10,0,0,0,0,10,-10,10 +hole|0,0,10,0,10,10,0,10 + +case|corner touch (1e-06 degree grid)|1e-06|-71.06|42.36|200.0 +hole|0,0,10,0,10,10,0,10 +hole|10,10,20,10,20,20,10,20 + +case|shared edge (1e-06 degree grid)|1e-06|-71.06|42.36|200.0 +hole|0,0,10,0,10,10,0,10 +hole|10,0,20,0,20,10,10,10 + +case|part of an edge shared (1e-06 degree grid)|1e-06|-71.06|42.36|200.0 +hole|0,0,10,0,10,10,0,10 +hole|10,5,20,5,20,15,10,15 + +case|chain of four: edge, corner, part of an edge (1e-06 degree grid)|1e-06|-71.06|42.36|400.0 +hole|0,0,10,0,10,10,0,10 +hole|10,0,20,0,20,10,10,10 +hole|20,10,30,10,30,20,20,20 +hole|25,20,35,20,35,30,25,30 + +case|three around one vertex (1e-06 degree grid)|1e-06|-71.06|42.36|300.0 +hole|0,0,10,0,10,10,0,10 +hole|10,10,20,10,20,20,10,20 +hole|0,10,10,10,10,20,0,20 + +case|overlap (1e-06 degree grid)|1e-06|-71.06|42.36|175.0 +hole|0,0,10,0,10,10,0,10 +hole|5,5,15,5,15,15,5,15 + +case|three overlapping (1e-06 degree grid)|1e-06|-71.06|42.36|221.0 +hole|0,0,10,0,10,10,0,10 +hole|5,5,15,5,15,15,5,15 +hole|8,0,18,0,18,7,8,7 + +case|touching pair beside a hole one unit away (1e-06 degree grid)|1e-06|-71.06|42.36|700.0 +hole|0,0,30,0,30,10,0,10 +hole|30,0,40,0,40,10,30,10 +hole|0,11,30,11,30,21,0,21 + +case|slanted holes one unit apart, one touching a third (1e-06 degree grid)|1e-06|-71.06|42.36|274.0 +hole|0,0,29,-10,32,-7,3,3 +hole|3,4,32,-6,35,-3,6,7 +hole|32,-12,40,-12,40,-7,32,-7 + +case|two holes one unit apart, none touching (1e-06 degree grid)|1e-06|-71.06|42.36|600.0 +hole|0,0,30,0,30,10,0,10 +hole|0,11,30,11,30,21,0,21 + +case|one-unit edges: a diamond across a square, and a square at their corner (1e-06 degree grid)|1e-06|-71.06|42.36|3.5 +hole|1,0,2,1,1,2,0,1 +hole|0,0,1,0,1,1,0,1 +hole|1,-1,2,-1,2,0,1,0 + +case|hole touching the outline, sharing an edge with another hole (1e-06 degree grid)|1e-06|-71.06|42.36|200.0 +outer|-10,-10,50,-10,50,50,-10,50 +hole|-10,0,0,0,0,10,-10,10 +hole|0,0,10,0,10,10,0,10 + +case|Boston street parcel 97811, rounded to 1e-5 degree|1e-05|-71.03209|42.37859|376417.41510416666 +hole|3,-46,9,-43,24,-65,26,-70,41,-92,21,-99,-8,-110,-16,-114,-49,-126,-82,-138,-103,-147,-120,-122,-140,-129,-153,-135,-173,-142,-190,-117,-124,-93,-110,-88,-103,-85,-66,-71,-11,-51,-4,-48 +hole|53,-108,58,-104,78,-116,83,-120,89,-123,94,-127,76,-142,70,-148,57,-158,-13,-219,-39,-241,-75,-218 +hole|101,-138,106,-134,142,-157,100,-194,93,-199,76,-215,63,-225,40,-245,3,-222,34,-196,64,-170,92,-146 +hole|155,-176,161,-170,206,-199,189,-214,176,-224,146,-251,121,-271,107,-284,73,-313,51,-298,28,-284,46,-269,64,-253,83,-238,101,-222,120,-205,125,-201,147,-216,147,-215,148,-215,125,-201 +hole|38,-309,50,-316,55,-320,61,-323,31,-350,18,-360,-7,-382,-25,-397,-31,-403,-38,-408,-71,-438,-117,-408,-111,-404,-92,-387,-63,-362,-39,-342,-20,-325,-3,-310,4,-305,16,-294 +hole|-100,-437,-95,-441,-83,-448,-114,-474,-119,-479,-132,-489,-144,-500,-198,-546,-216,-562,-265,-604,-309,-575,-262,-534,-226,-503,-219,-498,-208,-487,-203,-484,-184,-467,-164,-450,-129,-420 +hole|-298,-600,-277,-614,-281,-618,-287,-622,-306,-639,-316,-648,-321,-651,-325,-656,-350,-676,-367,-692,-379,-701,-398,-718,-407,-726,-413,-730,-427,-743,-432,-747,-444,-740,-432,-747,-446,-759,-457,-751,-491,-731,-472,-714,-448,-694,-443,-689,-436,-684,-406,-658,-376,-633,-370,-627,-339,-602,-332,-595,-321,-586 +hole|-492,-767,-479,-756,-469,-763,-463,-766,-458,-770,-484,-793,-491,-798,-499,-806,-521,-792,-512,-785 +hole|-523,-792,-500,-806,-536,-837,-548,-848,-565,-862,-585,-880,-637,-857,-578,-806,-558,-788,-552,-784,-543,-775,-537,-771,-523,-758,-508,-746,-503,-741,-481,-755,-487,-759,-501,-772,-521,-789 +hole|-624,-878,-598,-889,-660,-967,-669,-979,-683,-996,-703,-987,-735,-974,-719,-955,-701,-931,-696,-926,-663,-883,-658,-878,-650,-867 +hole|-755,-967,-759,-967,-759,-966,-761,-966,-763,-964,-764,-964,-766,-957,-765,-957,-765,-955,-692,-863,-691,-863,-691,-862,-689,-862,-687,-861,-679,-861,-677,-862,-676,-862,-676,-863,-674,-864,-673,-866,-672,-866,-672,-868,-671,-869,-744,-963,-745,-963,-745,-964,-748,-965,-748,-966,-750,-966,-752,-967 +hole|-765,-932,-782,-953,-833,-931,-808,-898,-757,-921 +hole|-845,-918,-849,-924,-869,-915,-881,-910,-900,-901,-892,-891,-873,-900,-873,-899,-891,-890,-883,-879,-879,-875,-869,-862,-828,-811,-824,-805,-805,-813,-804,-812,-817,-806,-823,-804,-815,-794,-789,-806,-764,-817,-772,-828,-798,-816,-802,-822,-801,-823,-798,-818,-773,-828,-777,-834,-785,-843,-806,-871,-815,-881,-823,-892,-832,-902,-840,-913 +hole|-866,-831,-917,-894,-969,-871,-918,-808 +hole|-971,-850,-984,-865,-1037,-841,-951,-736,-898,-759,-935,-804 +hole|-999,-772,-1050,-836,-1103,-812,-1052,-749 +hole|-1031,-702,-1116,-807,-1168,-784,-1083,-678 +hole|-982,-707,-1007,-695,-997,-683,-985,-689,-984,-688,-972,-694,-971,-692,-995,-681,-985,-667,-982,-664,-930,-686,-941,-699,-944,-704,-956,-718 +hole|-967,-666,-979,-661,-905,-567,-854,-590,-918,-670,-921,-675,-928,-683,-941,-678,-941,-677 +hole|-835,-567,-845,-579,-896,-556,-853,-501,-835,-480,-785,-417,-770,-423,-769,-424,-735,-439,-785,-503,-818,-546 +hole|-687,-432,-687,-418,-658,-417,-656,-416,-659,-416,-657,-413,-661,-416,-687,-416,-687,-409,-682,-401,-673,-391,-668,-384,-592,-431,-598,-437,-604,-441,-652,-483,-668,-473,-668,-475,-665,-476,-653,-484,-677,-504,-686,-500 +hole|-734,-408,-736,-409,-743,-409,-748,-407,-752,-404,-758,-391,-759,-381,-760,-377,-760,-372,-759,-368,-759,-363,-755,-349,-751,-342,-745,-336,-739,-333,-736,-333,-734,-332,-726,-334,-721,-337,-717,-344,-716,-348,-715,-352,-714,-362,-714,-373,-715,-378,-719,-392,-727,-405 +hole|-664,-344,-691,-304,-662,-294,-644,-287,-612,-275,-595,-269,-586,-265,-520,-241,-511,-237,-504,-235,-487,-228,-470,-253,-437,-241,-454,-216,-421,-204,-388,-253,-414,-263,-445,-274,-470,-283,-486,-290,-528,-305,-578,-324,-595,-300,-578,-324,-657,-353,-661,-349 +hole|-464,-249,-470,-251,-486,-228,-468,-221,-461,-219,-454,-216,-439,-240,-451,-244,-457,-247 +hole|-395,-212,-405,-197,-382,-189,-371,-185,-360,-180,-355,-179,-339,-172,-272,-148,-256,-173,-255,-172,-270,-150,-271,-147,-259,-143,-253,-140,-246,-138,-206,-123,-173,-173,-191,-180,-201,-164,-202,-164,-205,-160,-192,-180,-239,-197,-255,-204,-338,-234,-371,-247,-379,-234 +hole|-169,-148,-173,-143,-153,-135,-143,-150,-137,-159,-156,-167 +hole|-129,-156,-136,-159,-151,-135,-126,-126,-120,-123,-104,-147 +hole|-70,-149,-46,-140,2,-122,7,-126,1,-132,-5,-136,-19,-149,-35,-162,-71,-194,-89,-209,-103,-200,-111,-196,-124,-187,-142,-176,-135,-173,-128,-171,-106,-162,-77,-152 +hole|-122,-206,-101,-220,-135,-248,-157,-268,-164,-273,-182,-289,-204,-308,-211,-313,-220,-322,-235,-334,-269,-312,-292,-297,-279,-287,-261,-271,-254,-266,-237,-251,-223,-261,-221,-259,-235,-249,-231,-245,-225,-241,-213,-230,-206,-225,-200,-219,-193,-214,-158,-183 +hole|-94,-234,-88,-228,-51,-252,-99,-293,-117,-309,-184,-366,-220,-343,-142,-275,-124,-259,-111,-249 +hole|-20,-253,-27,-248,-15,-237,-3,-228,3,-222,40,-246,28,-255,23,-260,9,-271,-5,-262,-13,-258 +hole|-23,-269,-3,-282,-28,-303,-58,-330,-81,-349,-87,-355,-94,-360,-111,-376,-118,-381,-136,-397,-151,-387,-159,-383,-172,-374,-130,-337,-123,-332,-106,-316,-99,-311,-40,-259 +hole|-163,-397,-147,-407,-184,-438,-189,-443,-190,-443,-224,-473,-233,-480,-233,-481,-239,-485,-242,-489,-260,-477,-263,-480,-246,-491,-256,-499,-256,-500,-294,-476,-281,-485,-295,-497,-313,-485,-316,-488,-298,-499,-300,-501,-275,-516,-281,-521,-281,-522,-330,-563,-415,-510,-366,-467,-365,-467,-360,-462,-359,-462,-263,-379,-252,-370,-248,-365,-233,-353,-224,-358,-219,-362,-211,-366,-205,-371,-197,-375 +hole|-283,-491,-278,-487,-256,-500,-261,-505,-267,-509,-272,-514,-294,-500 +hole|-386,-562,-353,-584,-390,-615,-412,-601,-407,-596,-401,-592,-401,-591,-388,-580,-393,-577,-417,-598,-432,-588,-435,-590,-393,-617,-404,-627,-414,-636,-446,-616,-457,-610,-464,-605,-468,-608,-438,-626,-418,-639,-433,-651,-438,-656,-445,-661,-457,-672,-481,-692,-505,-714,-511,-718,-526,-709,-542,-698,-553,-692,-595,-665,-487,-571,-481,-567,-462,-550,-438,-530,-424,-538,-395,-557 +hole|-544,-715,-522,-729,-537,-741,-558,-760,-577,-748,-578,-748,-559,-760,-574,-773,-597,-757,-609,-750,-658,-719,-633,-698,-608,-714,-605,-712,-630,-695,-620,-687,-606,-695,-611,-699,-610,-700,-605,-696,-595,-703,-594,-702,-604,-695,-619,-686,-607,-675 +hole|-601,-769,-582,-781,-589,-786,-607,-802,-644,-779,-650,-776,-677,-775,-678,-737,-667,-727,-613,-762 +hole|-632,-799,-627,-795,-611,-805,-620,-813,-637,-803 +hole|-642,-808,-637,-803,-621,-814,-640,-830,-655,-821,-653,-816,-652,-809,-653,-796,-655,-796,-655,-812,-657,-822,-641,-831,-660,-848,-667,-844,-675,-841,-676,-813,-677,-802,-677,-779,-655,-779,-652,-780,-628,-794,-648,-811,-647,-812,-643,-808 +hole|-720,-836,-696,-846,-717,-871,-768,-849,-759,-837,-745,-844,-731,-850,-730,-848,-758,-836,-749,-824 +hole|-774,-856,-722,-878,-725,-882,-726,-882,-733,-891,-732,-891,-736,-897,-737,-896,-746,-907,-745,-907,-747,-909,-798,-887 +hole|-698,-816,-698,-825,-704,-828,-739,-813,-719,-786,-709,-774,-699,-779 +hole|-745,-794,-755,-806,-768,-800,-749,-776,-751,-776,-770,-799,-806,-783,-771,-739,-767,-733,-766,-733,-721,-676,-704,-656,-703,-656,-700,-737,-741,-788 +hole|-832,-788,-859,-821,-911,-798,-884,-765 +hole|-775,-717,-822,-776,-874,-754,-771,-626,-720,-648,-739,-672,-743,-676,-746,-681,-751,-686,-761,-700 +hole|-879,-734,-890,-748,-921,-733,-941,-725,-929,-710,-904,-721,-903,-720,-928,-709,-908,-683,-898,-672,-880,-648,-828,-671,-847,-695,-861,-712,-874,-729 +hole|-965,-730,-988,-759,-1041,-735,-1018,-706 +hole|-849,-652,-854,-658,-878,-647,-847,-607,-843,-603,-839,-597,-788,-619,-807,-643,-834,-631,-841,-639,-839,-639 +hole|-797,-599,-810,-593,-823,-588,-829,-585,-738,-470,-728,-459,-718,-446,-708,-449,-708,-476,-707,-484,-708,-490,-707,-504,-706,-519,-717,-532,-727,-545,-734,-553,-742,-564,-747,-569,-754,-579,-762,-588,-766,-594,-778,-608 +hole|-653,-505,-566,-430,-509,-466,-521,-476,-452,-521,-548,-604,-555,-609,-555,-610,-560,-615,-579,-630,-608,-656,-665,-620,-635,-594,-634,-594,-621,-582,-592,-558,-568,-537,-557,-528,-538,-515,-559,-520,-568,-523,-569,-524,-571,-524,-575,-527,-577,-528,-580,-527,-679,-611,-682,-609,-684,-531,-663,-513,-643,-525,-642,-525,-662,-513 +hole|-486,-445,-499,-456,-554,-420,-529,-399,-511,-383,-476,-352,-453,-367,-451,-365,-460,-359,-454,-355,-455,-354,-460,-358,-474,-350,-452,-331,-445,-326,-418,-343,-416,-342,-428,-334,-421,-327,-422,-327,-429,-333,-444,-324,-409,-295,-397,-284,-388,-276,-382,-272,-378,-267,-373,-263,-359,-272,-378,-289,-377,-290,-382,-294,-380,-295,-371,-287,-365,-283,-355,-274,-345,-281,-357,-291,-334,-306,-333,-305,-339,-302,-355,-291,-344,-282,-333,-288,-322,-296,-316,-299,-353,-331,-389,-362,-402,-372,-420,-388,-461,-423,-489,-405,-491,-408,-463,-425 +hole|-557,-401,-568,-410,-579,-404,-589,-397,-595,-394,-583,-384,-568,-394,-562,-397 +hole|-583,-381,-596,-393,-617,-379,-643,-363,-618,-353,-589,-343,-569,-335,-554,-357,-568,-335,-544,-326,-535,-323,-518,-334,-518,-335,-496,-349,-555,-399 +hole|-510,-332,-515,-335,-534,-323,-518,-317,-506,-312,-491,-307,-482,-303,-472,-300,-464,-296,-445,-290,-437,-286,-428,-283,-424,-286,-435,-296,-454,-312,-477,-333,-492,-324,-485,-319,-487,-319 +hole|-496,-326,-492,-324,-478,-333,-496,-349,-513,-338,-509,-335,-510,-334,-505,-331,-504,-332 +hole|-345,-264,-358,-256,-338,-249,-329,-245,-321,-243,-299,-235,-287,-230,-280,-228,-270,-242,-289,-248,-302,-253,-304,-253,-280,-268,-305,-290,-321,-279,-327,-276,-333,-271 +hole|-266,-237,-271,-239,-279,-227,-254,-218,-249,-216,-241,-228 +hole|-232,-227,-237,-231,-248,-216,-213,-203,-209,-207 +hole|-255,-234,-241,-229,-237,-231,-256,-247,-268,-239 +hole|-275,-244,-268,-241,-257,-248,-270,-260,-279,-268,-301,-254 +hole|-315,-319,-303,-308,-290,-316,-327,-348,-326,-349,-289,-317,-277,-324,-314,-356,-311,-358,-295,-343,-289,-339,-275,-326,-253,-339,-246,-344,-324,-411,-325,-411,-331,-417,-332,-417,-355,-438,-368,-448,-379,-459,-392,-469,-404,-480,-429,-501,-483,-465,-437,-424,-429,-418,-411,-402,-369,-366,-363,-360,-362,-360,-343,-343 +hole|-649,-648,-621,-666,-653,-694,-660,-688,-659,-682,-660,-682,-663,-689,-654,-695,-675,-713,-679,-711,-680,-660,-662,-660,-662,-659,-681,-659,-681,-634,-677,-630 +hole|-705,-597,-704,-629,-710,-637,-762,-614,-744,-592,-740,-586,-727,-571,-718,-559,-705,-565 +hole|-827,-639,-809,-646,-820,-661,-828,-670,-852,-659,-833,-636 + +case|Boston street parcel 98014, rounded to 1e-5 degree|1e-05|-71.11716|42.30025|378410.0 +hole|-554,-698,-554,-696,-553,-694,-553,-684,-552,-684,-552,-683,-550,-683,-515,-704,-489,-719,-463,-735,-438,-749,-481,-789,-517,-767,-530,-760,-542,-752,-580,-730,-557,-705 +hole|-401,-741,-371,-712,-341,-729,-332,-721,-362,-704,-322,-666,-266,-698,-254,-706,-235,-716,-235,-717,-234,-717,-295,-810,-296,-810,-296,-811,-302,-811,-302,-810,-407,-749,-408,-749,-408,-747,-407,-747 +hole|-288,-672,-312,-658,-272,-619,-234,-642,-207,-657,-202,-659,-202,-660,-201,-660,-211,-680,-225,-703,-225,-704,-226,-704,-226,-705,-232,-705,-232,-704 +hole|-239,-625,-263,-610,-225,-576,-225,-575,-219,-575,-185,-595,-174,-600,-174,-601,-173,-601,-173,-602,-172,-602,-172,-606,-181,-625,-188,-624,-194,-646,-195,-646,-195,-647,-198,-648,-200,-648,-200,-647,-212,-641 +hole|-189,-578,-211,-566,-211,-565,-212,-565,-212,-562,-211,-562,-211,-561,-173,-526,-151,-504,-149,-531,-152,-553,-165,-586,-166,-586,-166,-587,-167,-587,-167,-588,-172,-588 +hole|-333,-810,-318,-818,-316,-819,-316,-820,-315,-820,-315,-821,-314,-821,-314,-822,-313,-822,-313,-828,-314,-828,-330,-853,-336,-866,-339,-875,-325,-879,-326,-889,-326,-900,-321,-917,-366,-903,-524,-856,-420,-759,-371,-787,-416,-829,-435,-847,-421,-851,-360,-794 +hole|-361,-915,-349,-919,-315,-928,-306,-941,-303,-943,-301,-946,-298,-948,-319,-964,-330,-974,-336,-984,-411,-962,-424,-959,-439,-954,-469,-946,-495,-938,-553,-922,-579,-907,-533,-865,-483,-880,-470,-883,-455,-888,-439,-892,-408,-902 +hole|-614,-914,-726,-1020,-756,-1048,-811,-1100,-861,-1146,-861,-1147,-863,-1147,-863,-1148,-868,-1148,-868,-1147,-870,-1147,-870,-1146,-871,-1146,-869,-1135,-864,-1121,-861,-1108,-859,-1089,-859,-1072,-856,-1054,-854,-1048,-847,-1036,-841,-1029,-841,-1028,-798,-988,-788,-980,-779,-971,-769,-963,-760,-954,-729,-927,-715,-913,-703,-899,-692,-881,-687,-873,-674,-842,-669,-835,-667,-830,-663,-824,-662,-824,-635,-791,-595,-814,-595,-815,-542,-846 +hole|-652,-976,-641,-966,-640,-966,-640,-965,-639,-965,-639,-966,-638,-966,-611,-982,-602,-985,-543,-1000,-527,-1005,-512,-1008,-495,-1013,-478,-1017,-421,-1033,-372,-1045,-372,-1046,-370,-1046,-370,-1047,-369,-1047,-369,-1048,-368,-1048,-368,-1053,-377,-1086,-378,-1086,-378,-1087,-381,-1088,-384,-1088,-426,-1078,-523,-1055,-538,-1052,-580,-1041,-610,-1035,-623,-1031,-651,-1025,-659,-1021,-683,-1006 +hole|-445,-1086,-433,-1088,-403,-1095,-392,-1098,-391,-1098,-391,-1099,-390,-1099,-390,-1102,-391,-1102,-391,-1103,-428,-1133,-429,-1133,-429,-1134,-434,-1134,-451,-1130,-478,-1125,-576,-1104,-689,-1080,-699,-1077,-711,-1071,-736,-1056,-693,-1015,-659,-1035,-628,-1042,-614,-1046,-586,-1052,-572,-1056,-514,-1069,-500,-1073,-459,-1082 +hole|-606,-793,-626,-782,-588,-740,-526,-776,-515,-783,-490,-797,-532,-837,-557,-823 +hole|-869,-1181,-860,-1173,-840,-1184,-805,-1206,-793,-1212,-747,-1239,-721,-1255,-709,-1261,-675,-1282,-663,-1288,-630,-1308,-649,-1323,-671,-1342,-672,-1342,-672,-1343,-675,-1343,-677,-1344,-678,-1344,-678,-1343,-681,-1343,-681,-1342,-763,-1294,-776,-1287,-789,-1278,-801,-1272,-813,-1264,-859,-1237,-902,-1211 +hole|-595,-1298,-570,-1278,-568,-1277,-564,-1275,-559,-1273,-554,-1272,-552,-1272,-551,-1271,-490,-1273,-488,-1274,-483,-1275,-481,-1276,-477,-1278,-475,-1280,-464,-1286,-484,-1304,-505,-1322,-516,-1330,-546,-1356,-559,-1366,-620,-1419,-627,-1424,-656,-1451,-729,-1512,-740,-1522,-752,-1531,-789,-1563,-789,-1564,-791,-1564,-791,-1565,-797,-1565,-797,-1564,-799,-1564,-799,-1563,-800,-1563,-845,-1529,-874,-1511,-874,-1510,-875,-1510,-875,-1508,-874,-1506,-824,-1482,-722,-1403,-648,-1341,-638,-1334,-629,-1326,-619,-1319,-597,-1301 +hole|-476,-1313,-455,-1295,-451,-1295,-403,-1328,-456,-1371,-480,-1392,-494,-1403,-549,-1379,-549,-1378,-550,-1378,-550,-1376,-506,-1338 +hole|-398,-1314,-413,-1303,-388,-1283,-376,-1272,-326,-1231,-269,-1266,-321,-1309,-332,-1319,-359,-1341,-373,-1332,-386,-1322 +hole|-421,-1357,-394,-1334,-358,-1359,-336,-1383,-398,-1416,-418,-1437,-483,-1408,-465,-1394 +hole|-346,-1401,-329,-1391,-314,-1412,-310,-1419,-310,-1422,-308,-1424,-308,-1426,-306,-1430,-306,-1432,-304,-1437,-304,-1455,-309,-1469,-312,-1476,-312,-1477,-313,-1477,-313,-1478,-315,-1478,-315,-1479,-317,-1479,-319,-1480,-322,-1480,-322,-1479,-324,-1479,-369,-1459,-386,-1451,-408,-1442,-388,-1422,-380,-1419 +hole|-353,-1477,-321,-1492,-357,-1546,-412,-1522,-427,-1514,-464,-1498,-415,-1450,-402,-1456,-386,-1462 +hole|-336,-1536,-328,-1524,-261,-1544,-270,-1589,-328,-1585,-336,-1551,-339,-1540 +hole|-350,-1560,-348,-1560,-330,-1634,-340,-1762,-343,-1786,-346,-1830,-428,-1787,-450,-1773,-440,-1758,-432,-1742,-424,-1714,-422,-1701,-421,-1700,-412,-1668,-402,-1645,-352,-1561,-351,-1561,-351,-1560 +hole|-381,-1821,-362,-1832,-348,-1839,-348,-1841,-347,-1841,-352,-1886,-356,-1935,-357,-1935,-357,-1937,-358,-1937,-358,-1938,-360,-1938,-362,-1939,-365,-1939,-365,-1938,-367,-1938,-380,-1928,-512,-1842,-512,-1841,-513,-1841,-513,-1837,-512,-1837,-512,-1836,-493,-1820,-482,-1808,-456,-1783,-455,-1783,-455,-1782,-451,-1782,-451,-1783 +hole|-515,-1825,-521,-1830,-522,-1830,-522,-1831,-528,-1831,-542,-1822,-540,-1820,-584,-1791,-571,-1780,-557,-1789,-541,-1763,-533,-1752,-504,-1762,-506,-1765,-469,-1781,-486,-1799 +hole|-585,-1771,-571,-1780,-584,-1791,-599,-1782,-625,-1764,-640,-1755,-642,-1757,-664,-1738,-671,-1730,-673,-1727,-665,-1716,-619,-1733,-626,-1744 +hole|-660,-1688,-679,-1718,-689,-1699,-691,-1691,-699,-1672,-707,-1656,-720,-1636,-720,-1632,-712,-1624,-695,-1604,-680,-1589,-664,-1570,-622,-1524,-622,-1523,-621,-1523,-621,-1522,-619,-1522,-617,-1521,-613,-1521,-613,-1522,-611,-1522,-611,-1523,-572,-1549,-640,-1655 +hole|-685,-1579,-723,-1620,-723,-1621,-724,-1621,-724,-1622,-731,-1622,-731,-1621,-732,-1621,-747,-1605,-767,-1587,-776,-1581,-779,-1578,-780,-1578,-781,-1573,-780,-1573,-780,-1572,-779,-1572,-755,-1551,-692,-1498,-672,-1481,-625,-1513,-664,-1555,-671,-1564,-672,-1564 +hole|-821,-1570,-806,-1581,-891,-1654,-935,-1692,-936,-1692,-936,-1693,-938,-1693,-938,-1692,-940,-1692,-940,-1691,-941,-1691,-966,-1611,-973,-1591,-975,-1582,-989,-1541,-962,-1543,-947,-1543,-899,-1519,-894,-1519,-874,-1533,-856,-1544 +hole|-649,-1481,-662,-1473,-614,-1431,-586,-1450,-582,-1453,-580,-1454,-576,-1456,-575,-1456,-575,-1457,-570,-1458,-567,-1459,-563,-1459,-561,-1460,-556,-1460,-554,-1459,-550,-1459,-548,-1458,-546,-1458,-535,-1452,-535,-1451,-514,-1436,-492,-1416,-490,-1416,-426,-1445,-474,-1491,-505,-1499,-520,-1502,-536,-1507,-545,-1509,-566,-1539,-585,-1525,-613,-1507,-626,-1497,-639,-1489 +hole|-581,-1440,-605,-1423,-561,-1385,-502,-1411,-544,-1446,-549,-1448,-552,-1449,-555,-1449,-557,-1450,-560,-1450,-562,-1449,-566,-1449,-568,-1448,-574,-1445 +hole|-537,-1516,-482,-1501,-403,-1537,-362,-1555,-398,-1615,-448,-1594,-480,-1579,-495,-1573,-541,-1552,-556,-1546,-556,-1545,-557,-1545,-557,-1543,-556,-1543 +hole|-430,-1614,-405,-1625,-419,-1653,-423,-1662,-425,-1670,-428,-1676,-432,-1689,-441,-1730,-451,-1755,-453,-1757,-455,-1762,-465,-1775,-502,-1759,-504,-1761,-533,-1751,-525,-1740,-519,-1729,-518,-1729,-506,-1707,-494,-1677,-491,-1664,-490,-1663,-490,-1652,-493,-1646,-493,-1644,-499,-1637,-501,-1636,-501,-1635,-503,-1634,-505,-1632,-521,-1625,-522,-1625,-522,-1624,-523,-1624,-523,-1621,-502,-1610,-479,-1596,-477,-1596,-477,-1595,-472,-1595,-472,-1596 +hole|-546,-1747,-560,-1768,-561,-1768,-561,-1769,-566,-1769,-566,-1768,-606,-1742,-607,-1742,-607,-1739,-606,-1739,-590,-1713,-575,-1686,-560,-1650,-557,-1644,-556,-1644,-556,-1643,-555,-1643,-555,-1642,-554,-1642,-554,-1641,-553,-1641,-553,-1640,-551,-1639,-547,-1636,-542,-1634,-540,-1634,-538,-1633,-533,-1633,-531,-1634,-529,-1634,-520,-1638,-518,-1638,-518,-1639,-516,-1639,-510,-1644,-509,-1644,-507,-1648,-506,-1648,-506,-1650,-505,-1650,-505,-1653,-504,-1653,-504,-1660,-510,-1680,-527,-1717 +hole|-608,-1716,-618,-1730,-640,-1723,-664,-1714,-635,-1668,-624,-1649,-606,-1623,-599,-1610,-588,-1594,-564,-1555,-492,-1586,-491,-1586,-491,-1590,-492,-1590,-551,-1625,-554,-1626,-564,-1633,-565,-1635,-567,-1636,-573,-1644,-590,-1685,-599,-1701 +hole|-858,-1483,-889,-1498,-889,-1499,-894,-1499,-894,-1498,-896,-1498,-937,-1471,-924,-1459,-902,-1440,-881,-1421,-813,-1362,-775,-1385,-745,-1402,-795,-1441,-804,-1447,-813,-1455,-836,-1472 +hole|-136,-497,-139,-502,-140,-494,-131,-486 +hole|-166,-491,-208,-468,-170,-430,-157,-484,-164,-491 +hole|-134,-461,-150,-477,-163,-424,-136,-398,-103,-368,-62,-393 +hole|-106,-353,-165,-409,-167,-397,-164,-387,-159,-377,-151,-368,-146,-364,-118,-346,-77,-317,2,-266,61,-229,104,-201,108,-203,119,-196,78,-257,32,-302,6,-329,-30,-363,-57,-389,-61,-379 diff --git a/src/test/resources/projection-expected.txt b/src/test/resources/projection-expected.txt new file mode 100644 index 0000000..b58e7ed --- /dev/null +++ b/src/test/resources/projection-expected.txt @@ -0,0 +1,34 @@ +project|0|0|0.000000|-0.000000 +project|35.681236|139.767125|15558805.184640|4256848.120220 +project|51.5074|-0.1278|-14226.630923|6711542.475588 +project|-33.8688|151.2093|16832542.279207|-4011198.647308 +project|-1.2921|36.8219|4098995.158041|-143848.107271 +project|64.1466|-21.9426|-2442639.058680|9387089.649838 +project|0|180|-20037508.342789|-0.000000 +project|0|-180|-20037508.342789|-0.000000 +project|0|90|10018754.171395|-0.000000 +project|0|-90|-10018754.171395|-0.000000 +project|85.05112878|0|0.000000|20037508.343039 +project|-85.05112878|0|0.000000|-20037508.343039 +project|85.1|0|0.000000|20037508.343039 +project|86|0|0.000000|20037508.343039 +project|89|0|0.000000|20037508.343039 +project|89.999|0|0.000000|20037508.343039 +project|90|0|0.000000|20037508.343039 +project|-90|0|0.000000|-20037508.343039 +project|0|190|-18924313.434857|-0.000000 +project|0|-190|18924313.434857|-0.000000 +project|0|360|0.000000|-0.000000 +project|0|-360|0.000000|-0.000000 +project|35.681236|189.767125|-18950236.961275|4256848.120220 +unproject|0|0|0.000000|0.000000 +unproject|15556463.769352|4257881.238407|35.688774|139.746092 +unproject|-14226.343867|6711665.221216|51.508086|-0.127797 +unproject|16832005.123478|-4011119.083890|-33.868207|151.204475 +unproject|20037508.342789|20037508.342789|85.051129|180.000000 +unproject|-20037508.342789|-20037508.342789|-85.051129|-180.000000 +unproject|20037508.342789|0|0.000000|180.000000 +unproject|0|20037508.342789|85.051129|0.000000 +unproject|0|-20037508.342789|-85.051129|0.000000 +unproject|21148622.5|0|0.000000|-170.018692 +unproject|-21148622.5|0|0.000000|170.018692 diff --git a/src/test/resources/projection-vectors.txt b/src/test/resources/projection-vectors.txt new file mode 100644 index 0000000..a1de78e --- /dev/null +++ b/src/test/resources/projection-vectors.txt @@ -0,0 +1,74 @@ +# Web Mercator 適合ベクタ。android-sdk / ios-sdk / react-sdk で同一のファイル。 +# +# ## これは何か +# +# `zoom-golden.txt` とは別物。あちらは移行前のプロバイダが返した値の記録で、 +# 既知の不具合(ios-for-mapbox のオフセット欠落)まで保存している。こちらは +# 「3 プラットフォームの**現在の実装**が同じ答えを出すか」を見るための入力。 +# +# provider に依存しない純粋な計算だけを対象にする。provider ごとのカメラモデル +# の差は正当なので、ここには入れない。 +# +# ## 形式 +# +# project|| 緯度経度 -> EPSG:3857 メートル +# unproject|| EPSG:3857 メートル -> 緯度経度 +# +# 出力は `%.6f`(マイクロメートル / ナノ度)で揃える。f64 のノイズより十分粗く、 +# 実装差より十分細かい。言語ごとの既定の数値表記(Kotlin の 1.49E7 など)を +# 避けるために桁を固定している。 +# +# ## 何を狙った入力か +# +# 端の扱いが実装で割れる。極、日付変更線の外側、Web Mercator の定義端 +# (±85.05112878)を意図的に含めてある。 + +# --- 通常域 --- +project|0|0 +project|35.681236|139.767125 +project|51.5074|-0.1278 +project|-33.8688|151.2093 +project|-1.2921|36.8219 +project|64.1466|-21.9426 + +# --- 赤道と子午線 --- +project|0|180 +project|0|-180 +project|0|90 +project|0|-90 + +# --- Web Mercator の定義端 --- +project|85.05112878|0 +project|-85.05112878|0 + +# --- 定義端の外側。クランプするかどうかで割れる --- +project|85.1|0 +project|86|0 +project|89|0 +project|89.999|0 +project|90|0 +project|-90|0 + +# --- 日付変更線の外側。wrap するかどうかで割れる --- +project|0|190 +project|0|-190 +project|0|360 +project|0|-360 +project|35.681236|189.767125 + +# --- 逆変換:通常域 --- +unproject|0|0 +unproject|15556463.769352|4257881.238407 +unproject|-14226.343867|6711665.221216 +unproject|16832005.123478|-4011119.083890 + +# --- 逆変換:端 --- +unproject|20037508.342789|20037508.342789 +unproject|-20037508.342789|-20037508.342789 +unproject|20037508.342789|0 +unproject|0|20037508.342789 +unproject|0|-20037508.342789 + +# --- 逆変換:範囲外。x が 1 周を超える --- +unproject|21148622.5|0 +unproject|-21148622.5|0