From 779f644ae8fb0198c2eda87ac77e00f2cc82bb0e Mon Sep 17 00:00:00 2001 From: xivk Date: Tue, 10 Oct 2023 14:12:26 +0200 Subject: [PATCH] Added countatzoom for tileset. --- .../Collections/TileTreeSetExtensions.cs | 30 +++++++++++++++++++ src/TilesMath/TilesMath.csproj | 2 +- .../Collections/TileTreeSetExtensionsTests.cs | 30 +++++++++++++++++++ 3 files changed, 61 insertions(+), 1 deletion(-) create mode 100644 test/TilesMath.Tests/Collections/TileTreeSetExtensionsTests.cs diff --git a/src/TilesMath/Collections/TileTreeSetExtensions.cs b/src/TilesMath/Collections/TileTreeSetExtensions.cs index 2827706..bfb1865 100644 --- a/src/TilesMath/Collections/TileTreeSetExtensions.cs +++ b/src/TilesMath/Collections/TileTreeSetExtensions.cs @@ -31,4 +31,34 @@ public static IEnumerable ToEnumerableAtZoom(this TileTreeSet set, int zoo } } } + + /// + /// Calculates the number of tiles at the given zoom level. + /// + /// The set. + /// The zoom level. + /// The number of tiles the set represents at the given zoom. + /// When tiles are found at a higher zoom level in the set it is not possible to enumerate. + public static long CountAtZoom(this TileTreeSet set, int zoom) + { + var count = 0L; + foreach (var tile in set) + { + if (tile.Zoom == zoom) + { + count++; + } + else if (tile.Zoom < zoom) + { + count += (long)System.Math.Pow(4, zoom - tile.Zoom); + } + else + { + throw new Exception( + $"Cannot enumerate this set at {zoom}, found at tile at a higher zoom level: {tile.Zoom}"); + } + } + + return count; + } } diff --git a/src/TilesMath/TilesMath.csproj b/src/TilesMath/TilesMath.csproj index 188a16f..a9b44bb 100644 --- a/src/TilesMath/TilesMath.csproj +++ b/src/TilesMath/TilesMath.csproj @@ -4,7 +4,7 @@ net6.0 enable enable - 0.0.7 + 0.0.8 TilesMath ANYWAYS BV A tiny library for tiles math. diff --git a/test/TilesMath.Tests/Collections/TileTreeSetExtensionsTests.cs b/test/TilesMath.Tests/Collections/TileTreeSetExtensionsTests.cs new file mode 100644 index 0000000..66ed52a --- /dev/null +++ b/test/TilesMath.Tests/Collections/TileTreeSetExtensionsTests.cs @@ -0,0 +1,30 @@ +using TilesMath.Collections; + +namespace TilesMath.Tests.Collections; + +public class TileTreeSetExtensionsTests +{ + [Fact] + public void TileTreeSet_SetWithTileZero_CountAtZoom2_ShouldBe16() + { + var set = new TileTreeSet { Tile.Create(0, 0, 0) }; + + Assert.Equal(16, set.CountAtZoom(2)); + } + + [Fact] + public void TileTreeSet_SetWithTileZero_CountAtZoom14_ShouldBe268435456() + { + var set = new TileTreeSet { Tile.Create(0, 0, 0) }; + + Assert.Equal(268435456, set.CountAtZoom(14)); + } + + [Fact] + public void TileTreeSet_SetWithOneZoom14Tile_CountAtZoom14_ShouldBe1() + { + var set = new TileTreeSet { Tile.Create(0, 0, 14) }; + + Assert.Equal(1, set.CountAtZoom(14)); + } +}