< Summary

Class:Itinero.Network.Tiles.NetworkTile
Assembly:Itinero
File(s):/home/runner/work/routing2/routing2/src/Itinero/Network/Tiles/NetworkTile.Attributes.cs
/home/runner/work/routing2/routing2/src/Itinero/Network/Tiles/NetworkTile.cs
/home/runner/work/routing2/routing2/src/Itinero/Network/Tiles/NetworkTile.Diffs.cs
/home/runner/work/routing2/routing2/src/Itinero/Network/Tiles/NetworkTile.Geo.cs
/home/runner/work/routing2/routing2/src/Itinero/Network/Tiles/NetworkTile.Serialization.cs
/home/runner/work/routing2/routing2/src/Itinero/Network/Tiles/NetworkTile.TurnCosts.cs
Covered lines:938
Uncovered lines:281
Coverable lines:1219
Total lines:1982
Line coverage:76.9% (938 of 1219)
Covered branches:290
Total branches:374
Branch coverage:77.5% (290 of 374)
Tag:284_38118444584

Metrics

MethodBranch coverage Cyclomatic complexity Line coverage
.ctor(...)100%1100%
TrimAttributes()100%4100%
SetAttributes(...)83.33%683.33%
GetGlobalEdgeId(...)50%4100%
GetAttributes()87.5%880%
AddOrGetString(...)100%4100%
WriteAttributesTo(...)100%4100%
ReadAttributesFrom(...)100%4100%
ReadAttributesFrom(...)0%20%
WriteAttributesTo(...)0%20%
EnsureCapacity(...)100%2100%
.ctor(...)100%2100%
.ctor(...)100%1100%
Clone()100%1100%
get_TileId()100%1100%
get_VertexCount()100%1100%
get_EdgeTypeMapId()100%1100%
AddVertex(...)100%1100%
HasVertex(...)100%2100%
TryGetVertex(...)100%2100%
AddEdge(...)80.76%2691.54%
DeleteEdge(...)100%2100%
IsEdgeDeleted(...)100%2100%
get_HasDeletedEdges()100%1100%
RemoveDeletedEdges()83.33%2488.88%
CloneForEdgeTypeMap(...)66.66%1283.07%
Trim()100%6100%
VertexEdgePointer(...)100%1100%
EncodeVertex(...)100%2100%
DecodeVertex(...)100%2100%
DecodeEdgeCrossId(...)100%1100%
GetEdgeCrossPointer(...)100%1100%
EncodePointer(...)100%1100%
DecodePointer(...)100%1100%
SetDynamicUIn32Nullable(...)100%1100%
GetTailHeadOrder(...)100%1100%
DecodeEdgePointerId(...)100%1100%
WriteEdgesAndVerticesTo(...)83.33%682.35%
ReadEdgesAndVerticesFrom(...)83.33%685%
ReadEdgesAndVerticesFrom(...)0%40%
WriteEdgesAndVerticesTo(...)0%40%
.ctor(...)100%1100%
get_MaxLonDiff()100%1100%
get_MaxLatDiff()100%1100%
InvalidateDiffs()100%1100%
EnsureDiffs(...)80%5087.69%
.ctor(...)100%1100%
SetCoordinate(...)77.77%1876.31%
GetCoordinate(...)100%4100%
ComputeBox()100%1100%
FromLocalCoordinates(...)100%1100%
ToLocalCoordinates(...)100%1100%
SetShape(...)93.75%1696.77%
GetShape()86.36%2291.83%
WriteGeoTo(...)100%6100%
ReadGeoFrom(...)100%6100%
ReadGeoFrom(...)0%20%
WriteGeoTo(...)0%20%
TrimShapes()100%2100%
WriteTo(...)100%1100%
ReadFrom(...)50%286.66%
ReadFromBuffer(...)0%20%
ReadFrom(...)100%10%
ToBytes()0%20%
WriteToBuffer(...)100%10%
GetSerializedSizeUpperBound()0%40%
.ctor(...)100%1100%
AddTurnCosts(...)88.63%4485%
GetTurnCosts()68.18%2263.79%
SetTailHeadOrder(...)85.71%1494.28%
WriteTurnCostsTo(...)50%450%
ReadTurnCostsFrom(...)50%457.14%
ReadTurnCostsFrom(...)0%20%
WriteTurnCostsTo(...)0%20%
TrimTurnCosts()100%2100%

File(s)

/home/runner/work/routing2/routing2/src/Itinero/Network/Tiles/NetworkTile.Attributes.cs

#LineLine coverage
 1using System;
 2using System.Collections.Generic;
 3using System.IO;
 4using Itinero.Data;
 5using Itinero.IO;
 6using Itinero.Network.Storage;
 7using Itinero.Network.Tiles.Standalone.Global;
 8
 9namespace Itinero.Network.Tiles;
 10
 11internal partial class NetworkTile
 12{
 13    /// <summary>
 14    /// Stores the attributes, starting with the number of attributes and then alternating key-value pairs.
 15    /// </summary>
 16    private byte[] _attributes;
 17
 276718    private uint _nextAttributePointer = 0;
 19
 20    /// <summary>
 21    /// Stores each string once.
 22    /// </summary>
 23    private string[] _strings;
 24
 276725    private uint _nextStringId = 0;
 26
 27    /// Shrinks the attribute buffers to what they hold. See NetworkTile.Trim.
 28    private void TrimAttributes()
 192829    {
 192830        if (_attributes.Length > _nextAttributePointer)
 190131        {
 190132            Array.Resize(ref _attributes, (int)_nextAttributePointer);
 190133        }
 34
 382935        if (_strings.Length > _nextStringId) Array.Resize(ref _strings, (int)_nextStringId);
 192836    }
 37
 38    private uint SetAttributes(IEnumerable<(string key, string value)> attributes, GlobalEdgeId? globalEdgeId)
 6926439    {
 40        // ensure enough space for the globalEdgeId header (up to 20 bytes).
 6926441        EnsureCapacity(ref _attributes, _nextAttributePointer + 21L, 256);
 42
 43        // save position before globalEdgeId — GetAttributes/GetGlobalEdgeId read from here.
 6926444        var start = _nextAttributePointer;
 45
 6926446        if (globalEdgeId == null)
 6195347        {
 6195348            _nextAttributePointer += _attributes.SetDynamicInt64Nullable(_nextAttributePointer, null);
 6195349        }
 50        else
 731151        {
 731152            _nextAttributePointer += _attributes.SetDynamicInt64Nullable(_nextAttributePointer, globalEdgeId.Value.EdgeI
 731153            _nextAttributePointer += _attributes.SetDynamicUInt32(_nextAttributePointer, globalEdgeId.Value.Tail);
 731154            _nextAttributePointer += _attributes.SetDynamicUInt32(_nextAttributePointer, globalEdgeId.Value.Head);
 731155        }
 56
 6926457        long cPos = _nextAttributePointer;
 6926458        long p = _nextAttributePointer + 1;
 6926459        var c = 0;
 71837460        foreach (var (key, value) in attributes)
 25529161        {
 25529162            EnsureCapacity(ref _attributes, p + 17, 256);
 63
 25529164            var id = this.AddOrGetString(key);
 25529165            p += _attributes.SetDynamicUInt32(p, id);
 25529166            id = this.AddOrGetString(value);
 25529167            p += _attributes.SetDynamicUInt32(p, id);
 68
 25529169            c++;
 25529170            if (c == 255)
 071            {
 072                _attributes[(int)cPos] = 255;
 073                c = 0;
 074                cPos = p;
 075                p++;
 076            }
 25529177        }
 78
 6926479        EnsureCapacity(ref _attributes, cPos + 1, 256);
 80
 6926481        _attributes[(int)cPos] = (byte)c;
 82
 6926483        _nextAttributePointer = (uint)p;
 84
 6926485        return start;
 6926486    }
 87
 88    internal GlobalEdgeId? GetGlobalEdgeId(uint? pointer)
 369889    {
 369890        if (pointer == null) return null;
 91
 369892        var p = pointer.Value;
 369893        p += _attributes.GetDynamicInt64Nullable(p, out var edgeId);
 369894        if (edgeId == null) return null;
 369895        p += _attributes.GetDynamicUInt32(p, out var tail);
 369896        p += _attributes.GetDynamicUInt32(p, out var head);
 97
 369898        return GlobalEdgeId.Create(edgeId.Value, tail, head);
 369899    }
 100
 101    internal IEnumerable<(string key, string value)> GetAttributes(uint? pointer)
 2790102    {
 3366103        if (pointer == null) yield break;
 104
 2214105        var p = pointer.Value;
 2214106        p += _attributes.GetDynamicInt64Nullable(p, out var edgeId);
 2214107        if (edgeId != null)
 0108        {
 0109            p += _attributes.GetDynamicUInt32(p, out _);
 0110            p += _attributes.GetDynamicUInt32(p, out _);
 0111        }
 112
 113        int count;
 114        do
 2214115        {
 2214116            count = _attributes[(int)p];
 2214117            p++;
 118
 28290119            for (var i = 0; i < count; i++)
 12266120            {
 12266121                p += _attributes.GetDynamicUInt32(p, out var keyId);
 12266122                p += _attributes.GetDynamicUInt32(p, out var valId);
 123
 12266124                yield return (_strings[(int)keyId], _strings[(int)valId]);
 11931125            }
 3758126        } while (count == 255);
 1879127    }
 128
 129    /// <summary>
 130    /// Calls into <see cref="AddOrGetString"/> and how many entries they compared.
 131    /// </summary>
 132    /// <remarks>
 133    /// AddOrGetString is a linear scan over the tile's strings, run per key and value written, and a
 134    /// cached tile starts with a full table. Counting comparisons says whether that matters.
 135    /// </remarks>
 136    internal static long StringLookups;
 137
 138    internal static long StringComparisons;
 139
 140    private uint AddOrGetString(string s)
 510582141    {
 510582142        System.Threading.Interlocked.Increment(ref StringLookups);
 510582143        System.Threading.Interlocked.Add(ref StringComparisons, _nextStringId);
 144
 58493298145        for (uint i = 0; i < _nextStringId; i++)
 29222579146        {
 29222579147            var existing = _strings[(int)i];
 29222579148            if (existing == s)
 486512149            {
 486512150                return i;
 151            }
 28736067152        }
 153
 24070154        EnsureCapacity(ref _strings, _nextStringId + 1L, 256);
 155
 24070156        var id = _nextStringId;
 24070157        _nextStringId++;
 158
 24070159        _strings[(int)id] = s;
 24070160        return id;
 510582161    }
 162
 163    private void WriteAttributesTo(Stream stream)
 8164    {
 8165        stream.WriteVarUInt32(_nextAttributePointer);
 44166        for (var i = 0; i < _nextAttributePointer; i++)
 14167        {
 14168            stream.WriteByte(_attributes[i]);
 14169        }
 170
 8171        stream.WriteVarUInt32(_nextStringId);
 36172        for (var i = 0; i < _nextStringId; i++)
 10173        {
 10174            stream.WriteWithSize(_strings[i]);
 10175        }
 8176    }
 177
 178    private void ReadAttributesFrom(Stream stream)
 8179    {
 8180        _nextAttributePointer = stream.ReadVarUInt32();
 8181        Array.Resize(ref _attributes, (int)_nextAttributePointer);
 44182        for (var i = 0; i < _nextAttributePointer; i++)
 14183        {
 14184            _attributes[i] = (byte)stream.ReadByte();
 14185        }
 186
 8187        _nextStringId = stream.ReadVarUInt32();
 8188        Array.Resize(ref _strings, (int)_nextStringId);
 36189        for (var i = 0; i < _nextStringId; i++)
 10190        {
 10191            _strings[i] = stream.ReadWithSizeString();
 10192        }
 8193    }
 194
 195    private void ReadAttributesFrom(byte[] data, ref int offset)
 0196    {
 0197        _nextAttributePointer = BitCoderBuffer.GetVarUInt32(data, ref offset);
 0198        Array.Resize(ref _attributes, (int)_nextAttributePointer);
 0199        Buffer.BlockCopy(data, offset, _attributes, 0, (int)_nextAttributePointer);
 0200        offset += (int)_nextAttributePointer;
 201
 0202        _nextStringId = BitCoderBuffer.GetVarUInt32(data, ref offset);
 0203        Array.Resize(ref _strings, (int)_nextStringId);
 0204        for (var i = 0; i < _nextStringId; i++)
 0205        {
 0206            _strings[i] = BitCoderBuffer.GetWithSizeString(data, ref offset);
 0207        }
 0208    }
 209
 210    private void WriteAttributesTo(byte[] data, ref int offset)
 0211    {
 0212        BitCoderBuffer.SetVarUInt32(data, ref offset, _nextAttributePointer);
 0213        Buffer.BlockCopy(_attributes, 0, data, offset, (int)_nextAttributePointer);
 0214        offset += (int)_nextAttributePointer;
 215
 0216        BitCoderBuffer.SetVarUInt32(data, ref offset, _nextStringId);
 0217        for (var i = 0; i < _nextStringId; i++)
 0218        {
 0219            BitCoderBuffer.SetWithSizeString(data, ref offset, _strings[i]);
 0220        }
 0221    }
 222}

/home/runner/work/routing2/routing2/src/Itinero/Network/Tiles/NetworkTile.cs

#LineLine coverage
 1using System;
 2using System.Collections.Generic;
 3using System.IO;
 4using Itinero.IO;
 5using Itinero.Network.Storage;
 6using Itinero.Network.Tiles.Standalone.Global;
 7using Itinero.Network.TurnCosts;
 8
 9namespace Itinero.Network.Tiles;
 10
 11internal partial class NetworkTile
 12{
 13    private const int DefaultSizeIncrease = 16;
 14
 15    /// <summary>
 16    /// Makes sure a buffer can hold <paramref name="required"/> elements, growing it geometrically.
 17    /// </summary>
 18    /// <remarks>
 19    /// Fixed-increment growth made appending to a large tile quadratic, and a cached tile is sized to
 20    /// its content so the first boundary edge resizes it. Capacity is invisible to the file format.
 21    /// </remarks>
 22    private static void EnsureCapacity<T>(ref T[] array, long required, int minimumIncrease)
 95010423    {
 186953224        if (array.Length >= required) return;
 25
 3067626        var grown = array.Length + Math.Max(minimumIncrease, array.Length >> 3);
 3067627        Array.Resize(ref array, (int)Math.Max(required, grown));
 95010428    }
 29
 30    private readonly uint _tileId;
 31    private readonly int _zoom; // the zoom level.
 32    private readonly Guid _edgeTypeMapId; // the edge type index id.
 33
 276734    private uint _nextVertexId = 0; // the next vertex id.
 35
 36    // the pointers, per vertex, to their first edge.
 37    // TODO: investigate if it's worth storing these with less precision, one tile will never contain this much data.
 38    // TODO: investigate if we can not use one-increasing vertex ids but also use their pointers like with the edges.
 39    private uint[] _pointers;
 40    private uint _nextCrossTileId; // the next id for an edge that crosses tile boundaries.
 41    private uint[] _crossEdgePointers; // points to the cross tile boundary edges.
 42
 43    // the next edge id.
 276744    private uint _nextEdgeId = 0;
 45
 46    // the edges.
 47    private byte[] _edges;
 48
 49    /// <summary>
 50    /// Creates a new tile.
 51    /// </summary>
 52    /// <param name="zoom">The zoom level.</param>
 53    /// <param name="tileId">The tile id.</param>
 54    /// <param name="edgeTypeMapId">The edge type index id.</param>
 274755    public NetworkTile(int zoom, uint tileId, Guid? edgeTypeMapId = null)
 274756    {
 274757        _zoom = zoom;
 274758        _tileId = tileId;
 274759        (_boxLeft, _boxTop, _boxLonStep, _boxLatStep) = this.ComputeBox();
 274760        _edgeTypeMapId = edgeTypeMapId ?? Guid.Empty;
 274761        _nextCrossTileId = 0;
 62
 274763        _pointers = new uint[0];
 274764        _edges = new byte[0];
 274765        _crossEdgePointers = new uint[0];
 66
 274767        _coordinates = new byte[0];
 274768        _shapes = new byte[0];
 274769        _attributes = new byte[0];
 274770        _strings = new string[0];
 274771    }
 72
 2073    private NetworkTile(int zoom, uint tileId, Guid edgeTypeMapId, uint nextCrossTileId, uint[] pointers,
 2074        byte[] edges,
 2075        uint[] crossEdgePointers, byte[] coordinates, byte[] shapes,
 2076        byte[] attributes,
 2077        string[] strings, byte[] turnCosts, uint nextVertexId, uint nextEdgeId,
 2078        uint nextAttributePointer,
 2079        uint nextShapePointer, uint nextStringId)
 2080    {
 2081        _zoom = zoom;
 2082        _tileId = tileId;
 2083        (_boxLeft, _boxTop, _boxLonStep, _boxLatStep) = this.ComputeBox();
 2084        _edgeTypeMapId = edgeTypeMapId;
 2085        _nextCrossTileId = nextCrossTileId;
 2086        _pointers = pointers;
 2087        _edges = edges;
 2088        _crossEdgePointers = crossEdgePointers;
 89
 2090        _coordinates = coordinates;
 2091        _shapes = shapes;
 2092        _attributes = attributes;
 2093        _strings = strings;
 2094        _turnCosts = turnCosts;
 95
 2096        _nextVertexId = nextVertexId;
 2097        _nextEdgeId = nextEdgeId;
 2098        _nextAttributePointer = nextAttributePointer;
 2099        _nextShapePointer = nextShapePointer;
 20100        _nextStringId = nextStringId;
 20101    }
 102
 103    /// <summary>
 104    /// Clones this graph tile.
 105    /// </summary>
 106    /// <returns>The copy of this tile.</returns>
 107    public NetworkTile Clone()
 14108    {
 14109        return new(_zoom, _tileId, _edgeTypeMapId, _nextCrossTileId, (uint[])_pointers.Clone(), (byte[])_edges.Clone(),
 14110            (uint[])_crossEdgePointers.Clone(),
 14111            (byte[])_coordinates.Clone(), (byte[])_shapes.Clone(), (byte[])_attributes.Clone(), (string[])_strings.Clone
 14112            _nextVertexId,
 14113            _nextEdgeId, _nextAttributePointer, _nextShapePointer, _nextStringId);
 14114    }
 115
 116    /// <summary>
 117    /// Gets the tile id.
 118    /// </summary>
 16369913119    public uint TileId => _tileId;
 120
 121    /// <summary>
 122    /// Gets the number of vertices.
 123    /// </summary>
 3832812124    public uint VertexCount => _nextVertexId;
 125
 126    /// <summary>
 127    /// Gets the edge type map id.
 128    /// </summary>
 4278565129    public Guid EdgeTypeMapId => _edgeTypeMapId;
 130
 131    /// <summary>
 132    /// Adds a new vertex and returns its id.
 133    /// </summary>
 134    /// <param name="longitude">The longitude.</param>
 135    /// <param name="latitude">The latitude.</param>
 136    /// <param name="e">The elevation in meters.</param>
 137    /// <returns>The ID of the new vertex.</returns>
 138    public VertexId AddVertex(double longitude, double latitude, float? e = null)
 46556139    {
 140        // set coordinate.
 46556141        this.SetCoordinate(_nextVertexId, longitude, latitude, e);
 142
 143        // create id.
 46556144        var vertexId = new VertexId(_tileId, _nextVertexId);
 46556145        _nextVertexId++;
 146
 147        // make room.
 46556148        ArrayBaseExtensions.EnsureMinimumSize(ref _pointers, vertexId.LocalId, DefaultSizeIncrease);
 149
 46556150        return vertexId;
 46556151    }
 152
 153    /// <summary>
 154    /// Returns true if the vertex exists.
 155    /// </summary>
 156    /// <param name="vertex"></param>
 157    /// <returns></returns>
 158    public bool HasVertex(VertexId vertex)
 7234159    {
 7234160        if (vertex.LocalId >= _nextVertexId)
 1842161        {
 1842162            return false;
 163        }
 164
 5392165        return true;
 7234166    }
 167
 168    /// <summary>
 169    /// Gets the vertex with the given id.
 170    /// </summary>
 171    /// <param name="vertex">The vertex.</param>
 172    /// <param name="longitude">The longitude.</param>
 173    /// <param name="latitude">The latitude.</param>
 174    /// <param name="elevation">The elevation.</param>
 175    /// <returns>True if the vertex exists.</returns>
 176    public bool TryGetVertex(VertexId vertex, out double longitude, out double latitude, out float? elevation)
 5662444177    {
 5662444178        longitude = default;
 5662444179        latitude = default;
 5662444180        elevation = null;
 5662444181        if (vertex.LocalId >= _nextVertexId)
 5182        {
 5183            return false;
 184        }
 185
 5662439186        this.GetCoordinate(vertex.LocalId, out longitude, out latitude, out elevation);
 5662439187        return true;
 5662444188    }
 189
 190    /// <summary>
 191    /// Adds a new edge and returns its id.
 192    /// </summary>
 193    /// <param name="vertex1">The first vertex.</param>
 194    /// <param name="vertex2">The second vertex.</param>
 195    /// <param name="shape">The shape."</param>
 196    /// <param name="attributes">The attributes."</param>
 197    /// <param name="edgeId">The edge id if this edge is a part of another tile.</param>
 198    /// <param name="edgeTypeId">The edge type id, if any.</param>
 199    /// <param name="length">The length in centimeters.</param>
 200    /// <param name="globalEdgeId">The global edge id, if any.</param>
 201    /// <returns>The new edge id.</returns>
 202    public EdgeId AddEdge(VertexId vertex1, VertexId vertex2,
 203        IEnumerable<(double longitude, double latitude, float? e)>? shape = null,
 204        IEnumerable<(string key, string value)>? attributes = null, EdgeId? edgeId = null, uint? edgeTypeId = null,
 205        uint? length = null, GlobalEdgeId? globalEdgeId = null)
 65349206    {
 207        // Edge set changed → cached MaxLonDiff/MaxLatDiff are now stale.
 65349208        this.InvalidateDiffs();
 209
 65349210        if (vertex2.TileId != _tileId)
 4526211        {
 212            // this edge crosses tiles boundaries, it need special treatment and a stable id.
 213            // because the edge originates in this tile, this tile is responsible for generating the id.
 4526214            if (edgeId != null) throw new ArgumentException(
 0215                    "The edge id shouldn't be a given, it should be generated by the originating tile.",
 0216                    nameof(edgeId));
 4526217            if (vertex1.TileId != _tileId) throw new ArgumentException("None of the two vertices in this edge are in thi
 0218                    nameof(vertex1));
 219
 220            // generate a new cross tile id and store pointer to edge.
 4526221            edgeId = EdgeId.CrossEdgeId(_tileId, _nextCrossTileId);
 4526222            ArrayBaseExtensions.EnsureMinimumSize(ref _crossEdgePointers, _nextCrossTileId + 1);
 4526223            _crossEdgePointers[_nextCrossTileId] = _nextEdgeId;
 4526224            _nextCrossTileId++;
 4526225        }
 60823226        else if (vertex1.TileId != _tileId)
 4525227        {
 228            // this edge crosses tiles boundaries, it need special treatment and a stable id.
 229            // because the edge originates in another tile it should already have an id.
 4525230            if (edgeId == null) throw new ArgumentException(
 0231                    "Cannot add an edge that doesn't start in this tile without a proper edge id.",
 0232                    nameof(edgeId));
 4525233            if (edgeId.Value.TileId != vertex1.TileId) throw new ArgumentException("The edge id doesn't match the tile i
 0234                    nameof(edgeId));
 4525235        }
 236        else
 56298237        {
 238            // this edge starts in this tile, it get an id from this tile.
 56298239            edgeId = new EdgeId(_tileId, _nextEdgeId);
 56298240        }
 241
 242        // write the edge data.
 65349243        var newEdgePointer = _nextEdgeId;
 65349244        var size = EncodeVertex(ref _edges, _tileId, _nextEdgeId, vertex1);
 65349245        _nextEdgeId += size;
 65349246        size = EncodeVertex(ref _edges, _tileId, _nextEdgeId, vertex2);
 65349247        _nextEdgeId += size;
 248
 249        // get previous pointers if vertex already has edges
 250        // set the new pointers.
 65349251        uint? v1p = null;
 65349252        if (vertex1.TileId == _tileId)
 60824253        {
 60824254            v1p = _pointers[vertex1.LocalId].DecodeNullableData();
 60824255            _pointers[vertex1.LocalId] = newEdgePointer.EncodeToNullableData();
 60824256        }
 257
 65349258        uint? v2p = null;
 65349259        if (vertex2.TileId == _tileId)
 60823260        {
 60823261            v2p = _pointers[vertex2.LocalId].DecodeNullableData();
 60823262            _pointers[vertex2.LocalId] = newEdgePointer.EncodeToNullableData();
 60823263        }
 264
 265        // set next pointers.
 65349266        size = EncodePointer(ref _edges, _nextEdgeId, v1p);
 65349267        _nextEdgeId += size;
 65349268        size = EncodePointer(ref _edges, _nextEdgeId, v2p);
 65349269        _nextEdgeId += size;
 270
 271        // write edge id explicitly if not in this edge.
 65349272        if (vertex1.TileId != vertex2.TileId)
 9051273        {
 274            // this data will only be there for edges crossing tile boundaries.
 9051275            _nextEdgeId += (uint)_edges.SetDynamicUInt32(_nextEdgeId,
 9051276                edgeId.Value.LocalId - EdgeId.MinCrossId);
 9051277        }
 278
 279        // write edge profile id.
 65349280        _nextEdgeId += SetDynamicUIn32Nullable(ref _edges, _nextEdgeId, edgeTypeId);
 281
 282        // write length.
 65349283        _nextEdgeId += SetDynamicUIn32Nullable(ref _edges, _nextEdgeId, length);
 284
 285        // set tail and head order.
 65349286        _edges.SetTailHeadOrder(_nextEdgeId, null, null);
 65349287        _nextEdgeId++;
 288
 289        // take care of shape if any.
 65349290        uint? shapePointer = null;
 65349291        if (shape != null)
 56264292        {
 56264293            shapePointer = this.SetShape(shape);
 56264294        }
 295
 65349296        size = EncodePointer(ref _edges, _nextEdgeId, shapePointer);
 65349297        _nextEdgeId += size;
 298
 299        // take care of attributes if any.
 65349300        uint? attributesPointer = null;
 65349301        if (attributes != null || globalEdgeId != null)
 59925302        {
 59925303            attributesPointer = this.SetAttributes(attributes ?? [], globalEdgeId);
 59925304        }
 305
 65349306        size = EncodePointer(ref _edges, _nextEdgeId, attributesPointer);
 65349307        _nextEdgeId += size;
 308
 65349309        return edgeId.Value;
 65349310    }
 311
 312    private HashSet<EdgeId>? _deletedEdges;
 313
 314    /// <summary>
 315    /// Marks the given edge as deleted.
 316    /// </summary>
 317    /// <param name="edge">The edge to delete.</param>
 318    internal void DeleteEdge(EdgeId edge)
 10319    {
 10320        _deletedEdges ??= [];
 10321        _deletedEdges.Add(edge);
 10322        this.InvalidateDiffs();
 10323    }
 324
 325    /// <summary>
 326    /// Returns true if the edge is deleted.
 327    /// </summary>
 328    /// <param name="edge">The edge.</param>
 329    /// <returns>True if the edge was deleted.</returns>
 330    internal bool IsEdgeDeleted(EdgeId edge)
 6568177331    {
 13136348332        if (_deletedEdges == null) return false;
 333
 6334        return _deletedEdges.Contains(edge);
 6568177335    }
 336
 337    /// <summary>
 338    /// Returns true if there are deleted edges.
 339    /// </summary>
 738340    internal bool HasDeletedEdges => _deletedEdges != null;
 341
 342    /// <summary>
 343    /// Removes all the deleted edges.
 344    /// </summary>
 345    /// <remarks>This changes all the edges if all edges written after a deleted edge.</remarks>
 346    internal void RemoveDeletedEdges()
 10347    {
 10348        if (_deletedEdges == null) return;
 10349        this.InvalidateDiffs();
 350
 351        // reset vertex pointers.
 340352        for (var i = 0; i < _pointers.Length; i++)
 160353        {
 160354            _pointers[i] = 0;
 160355        }
 356
 357        // redo edges, skipping deleted edges.
 10358        var nextEdgeId = _nextEdgeId;
 10359        var p = 0U;
 10360        var newP = 0U;
 24361        while (p < nextEdgeId)
 14362        {
 363            // read edge data.
 14364            var currentEdgeId = p;
 14365            p += this.DecodeVertex(p, out var local1Id, out var tile1Id);
 14366            var vertex1 = new VertexId(tile1Id, local1Id);
 14367            p += this.DecodeVertex(p, out var local2Id, out var tile2Id);
 14368            var vertex2 = new VertexId(tile2Id, local2Id);
 14369            p += this.DecodePointer(p, out _);
 14370            p += this.DecodePointer(p, out _);
 14371            uint? crossEdgeId = null;
 14372            if (tile1Id != tile2Id)
 4373            {
 4374                p += _edges.GetDynamicUInt32(p, out var c);
 4375                crossEdgeId = c;
 4376            }
 377
 14378            p += _edges.GetDynamicUInt32Nullable(p, out var edgeTypeId);
 14379            p += _edges.GetDynamicUInt32Nullable(p, out var length);
 14380            var tailHeadOrder = _edges[p];
 14381            p++;
 14382            p += this.DecodePointer(p, out var shapePointer);
 14383            p += this.DecodePointer(p, out var attributePointer);
 384
 385            // check if edge was deleted.
 20386            if (_deletedEdges.Contains(new EdgeId(_tileId, currentEdgeId))) continue;
 8387            if (crossEdgeId.HasValue)
 4388            {
 8389                if (_deletedEdges.Contains(EdgeId.CrossEdgeId(vertex1.TileId, crossEdgeId.Value))) continue;
 0390            }
 391
 392            // no need to overwrite identical data.
 4393            if (p == newP) continue;
 394
 395            // write edge data again.
 4396            var newEdgePointer = newP;
 4397            newP += EncodeVertex(ref _edges, _tileId, newP, vertex1);
 4398            newP += EncodeVertex(ref _edges, _tileId, newP, vertex2);
 4399            uint? v1p = null;
 4400            if (vertex1.TileId == _tileId)
 4401            {
 4402                v1p = _pointers[vertex1.LocalId].DecodeNullableData();
 4403                _pointers[vertex1.LocalId] = newEdgePointer.EncodeToNullableData();
 4404            }
 405
 4406            uint? v2P = null;
 4407            if (vertex2.TileId == _tileId)
 4408            {
 4409                v2P = _pointers[vertex2.LocalId].DecodeNullableData();
 4410                _pointers[vertex2.LocalId] = newEdgePointer.EncodeToNullableData();
 4411            }
 412
 4413            newP += EncodePointer(ref _edges, newP, v1p);
 4414            newP += EncodePointer(ref _edges, newP, v2P);
 4415            if (crossEdgeId != null)
 0416            {
 0417                newP += (uint)_edges.SetDynamicUInt32(newP, crossEdgeId.Value);
 0418                if (vertex1.TileId == _tileId)
 0419                {
 0420                    _crossEdgePointers[crossEdgeId.Value] = newEdgePointer;
 0421                }
 0422            }
 423
 4424            newP += _edges.SetDynamicUInt32Nullable(newP, edgeTypeId);
 4425            newP += _edges.SetDynamicUInt32Nullable(newP, length);
 4426            _edges[newP] = tailHeadOrder;
 4427            newP++;
 4428            newP += EncodePointer(ref _edges, newP, shapePointer);
 4429            newP += EncodePointer(ref _edges, newP, attributePointer);
 4430        }
 431
 10432        _nextEdgeId = newP;
 10433        _deletedEdges = null;
 10434    }
 435
 436    internal NetworkTile CloneForEdgeTypeMap(
 437        (Guid id, Func<IEnumerable<(string key, string value)>, uint> func) edgeTypeMap)
 6438    {
 6439        var edges = new byte[_edges.Length];
 6440        var pointers = new uint[_pointers.Length];
 6441        var crossEdgePointers = new uint[_crossEdgePointers.Length];
 6442        var nextEdgeId = _nextEdgeId;
 6443        var p = 0U;
 6444        var newP = 0U;
 16445        while (p < nextEdgeId)
 10446        {
 447            // read edge data.
 10448            p += this.DecodeVertex(p, out var local1Id, out var tile1Id);
 10449            var vertex1 = new VertexId(tile1Id, local1Id);
 10450            p += this.DecodeVertex(p, out var local2Id, out var tile2Id);
 10451            var vertex2 = new VertexId(tile2Id, local2Id);
 10452            p += this.DecodePointer(p, out _);
 10453            p += this.DecodePointer(p, out _);
 10454            uint? crossEdgeId = null;
 10455            if (tile1Id != tile2Id)
 0456            {
 0457                p += (uint)_edges.GetDynamicUInt32(p, out var c);
 0458                crossEdgeId = c;
 0459            }
 460
 10461            p += _edges.GetDynamicUInt32Nullable(p, out var _);
 10462            p += _edges.GetDynamicUInt32Nullable(p, out var length);
 10463            var tailHeadOrder = _edges[p];
 10464            p++;
 10465            p += this.DecodePointer(p, out var shapePointer);
 10466            p += this.DecodePointer(p, out var attributePointer);
 467
 468            // generate new edge type id.
 10469            var newEdgeTypeId = edgeTypeMap.func(this.GetAttributes(attributePointer));
 470
 471            // write edge data again.
 10472            var newEdgePointer = newP;
 10473            newP += EncodeVertex(ref edges, _tileId, newP, vertex1);
 10474            newP += EncodeVertex(ref edges, _tileId, newP, vertex2);
 10475            uint? v1p = null;
 10476            if (vertex1.TileId == _tileId)
 10477            {
 10478                v1p = pointers[vertex1.LocalId].DecodeNullableData();
 10479                pointers[vertex1.LocalId] = newEdgePointer.EncodeToNullableData();
 10480            }
 481
 10482            uint? v2p = null;
 10483            if (vertex2.TileId == _tileId)
 10484            {
 10485                v2p = pointers[vertex2.LocalId].DecodeNullableData();
 10486                pointers[vertex2.LocalId] = newEdgePointer.EncodeToNullableData();
 10487            }
 488
 10489            newP += EncodePointer(ref edges, newP, v1p);
 10490            newP += EncodePointer(ref edges, newP, v2p);
 10491            if (crossEdgeId != null)
 0492            {
 0493                newP += edges.SetDynamicUInt32(newP, crossEdgeId.Value);
 0494                if (vertex1.TileId == _tileId)
 0495                {
 0496                    crossEdgePointers[crossEdgeId.Value] = newEdgePointer;
 0497                }
 0498            }
 499
 10500            newP += edges.SetDynamicUInt32Nullable(newP, newEdgeTypeId);
 10501            newP += edges.SetDynamicUInt32Nullable(newP, length);
 10502            edges[newP] = tailHeadOrder;
 10503            newP++;
 10504            newP += EncodePointer(ref edges, newP, shapePointer);
 10505            newP += EncodePointer(ref edges, newP, attributePointer);
 10506        }
 507
 6508        return new NetworkTile(_zoom, _tileId, edgeTypeMap.id, _nextCrossTileId, pointers, edges, crossEdgePointers,
 6509            _coordinates,
 6510            _shapes, _attributes, _strings, _turnCosts, _nextVertexId, _nextEdgeId,
 6511            _nextAttributePointer, _nextShapePointer, _nextStringId);
 6512    }
 513
 514    /// <summary>
 515    /// Shrinks every appendable buffer to what it actually holds.
 516    /// </summary>
 517    /// <remarks>
 518    /// Growing by an eighth leaves slack in arrays resident for the process's life; hot measured −2.4%
 519    /// without this. Caller must hold this tile's write lock: it replaces the arrays.
 520    /// </remarks>
 521    internal void Trim()
 1928522    {
 3856523        if (_pointers.Length > _nextVertexId) Array.Resize(ref _pointers, (int)_nextVertexId);
 3829524        if (_edges.Length > _nextEdgeId) Array.Resize(ref _edges, (int)_nextEdgeId);
 1928525        if (_crossEdgePointers.Length > _nextCrossTileId)
 629526        {
 629527            Array.Resize(ref _crossEdgePointers, (int)_nextCrossTileId);
 629528        }
 529
 1928530        this.TrimAttributes();
 1928531        this.TrimShapes();
 1928532        this.TrimTurnCosts();
 1928533    }
 534
 535    internal uint VertexEdgePointer(uint vertex)
 1141968536    {
 1141968537        return _pointers[vertex];
 1141968538    }
 539
 540    internal static byte EncodeVertex(ref byte[] edges, uint localTileId, uint location, VertexId vertexId)
 130726541    {
 130726542        if (vertexId.TileId == localTileId)
 121675543        {
 544            // same tile, only store local id.
 121675545            EnsureCapacity(ref edges, location + 6L, DefaultSizeIncrease);
 546
 121675547            return edges.SetDynamicUInt32(location, vertexId.LocalId);
 548        }
 549
 550        // other tile, store full id.
 9051551        EnsureCapacity(ref edges, location + 11L, DefaultSizeIncrease);
 552
 9051553        var encodedId = vertexId.Encode();
 9051554        return edges.SetDynamicUInt64(location, encodedId);
 130726555    }
 556
 557    internal byte DecodeVertex(uint location, out uint localId, out uint tileId)
 13156584558    {
 13156584559        var size = _edges.GetDynamicUInt64(location, out var encodedId);
 13156584560        if (encodedId < uint.MaxValue)
 13029299561        {
 13029299562            localId = (uint)encodedId;
 13029299563            tileId = _tileId;
 13029299564            return size;
 565        }
 566
 127285567        VertexId.Decode(encodedId, out tileId, out localId);
 127285568        return size;
 13156584569    }
 570
 571    internal byte DecodeEdgeCrossId(uint location, out uint edgeCrossId)
 125802572    {
 125802573        var s = _edges.GetDynamicUInt32(location, out var c);
 125802574        edgeCrossId = EdgeId.MinCrossId + c;
 125802575        return s;
 125802576    }
 577
 578    internal uint GetEdgeCrossPointer(uint edgeCrossId)
 52605579    {
 52605580        return _crossEdgePointers[edgeCrossId];
 52605581    }
 582
 583    internal static byte EncodePointer(ref byte[] edges, uint location, uint? pointer)
 261452584    {
 585        // TODO: save the diff instead of the full pointer.
 261452586        EnsureCapacity(ref edges, location + 6L, DefaultSizeIncrease);
 587
 261452588        return edges.SetDynamicUInt32(location,
 261452589            pointer.EncodeAsNullableData());
 261452590    }
 591
 592    internal byte DecodePointer(uint location, out uint? pointer)
 14512006593    {
 14512006594        var size = _edges.GetDynamicUInt32(location, out var data);
 14512006595        pointer = data.DecodeNullableData();
 14512006596        return size;
 14512006597    }
 598
 599    internal static byte SetDynamicUIn32Nullable(ref byte[] edges, uint pointer, uint? data)
 130698600    {
 130698601        EnsureCapacity(ref edges, pointer + 6L, DefaultSizeIncrease);
 602
 130698603        return edges.SetDynamicUInt32Nullable(pointer, data);
 130698604    }
 605
 606    internal void GetTailHeadOrder(uint location, ref byte? tail, ref byte? head)
 6578267607    {
 6578267608        _edges.GetTailHeadOrder(location, ref tail, ref head);
 6578267609    }
 610
 611    internal byte DecodeEdgePointerId(uint location, out uint? edgeProfileId)
 13156534612    {
 13156534613        return _edges.GetDynamicUInt32Nullable(location, out edgeProfileId);
 13156534614    }
 615
 616    private void WriteEdgesAndVerticesTo(Stream stream)
 8617    {
 618        // write vertex pointers.
 8619        stream.WriteVarUInt32(_nextVertexId);
 42620        for (var i = 0; i < _nextVertexId; i++)
 13621        {
 13622            stream.WriteVarUInt32(_pointers[i]);
 13623        }
 624
 625        // write edges.
 8626        stream.WriteVarUInt32(_nextEdgeId);
 106627        for (var i = 0; i < _nextEdgeId; i++)
 45628        {
 45629            stream.WriteByte(_edges[i]);
 45630        }
 631
 632        // write cross edge pointers.
 8633        stream.WriteVarUInt32(_nextCrossTileId);
 16634        for (var i = 0; i < _nextCrossTileId; i++)
 0635        {
 0636            stream.WriteVarUInt32(_crossEdgePointers[i]);
 0637        }
 8638    }
 639
 640    private void ReadEdgesAndVerticesFrom(Stream stream)
 8641    {
 642        // read vertex pointers.
 8643        _nextVertexId = stream.ReadVarUInt32();
 8644        Array.Resize(ref _pointers, (int)_nextVertexId);
 42645        for (var i = 0; i < _nextVertexId; i++)
 13646        {
 13647            _pointers[i] = stream.ReadVarUInt32();
 13648        }
 649
 650        // read edges.
 8651        _nextEdgeId = stream.ReadVarUInt32();
 8652        Array.Resize(ref _edges, (int)_nextEdgeId);
 106653        for (var i = 0; i < _nextEdgeId; i++)
 45654        {
 45655            _edges[i] = (byte)stream.ReadByte();
 45656        }
 657
 658        // read cross tile edge pointers.
 8659        _nextCrossTileId = stream.ReadVarUInt32();
 8660        Array.Resize(ref _crossEdgePointers, (int)_nextCrossTileId);
 16661        for (var i = 0; i < _nextCrossTileId; i++)
 0662        {
 0663            _crossEdgePointers[i] = stream.ReadVarUInt32();
 0664        }
 8665    }
 666
 667    private void ReadEdgesAndVerticesFrom(byte[] data, ref int offset)
 0668    {
 0669        _nextVertexId = BitCoderBuffer.GetVarUInt32(data, ref offset);
 0670        Array.Resize(ref _pointers, (int)_nextVertexId);
 0671        for (var i = 0; i < _nextVertexId; i++)
 0672        {
 0673            _pointers[i] = BitCoderBuffer.GetVarUInt32(data, ref offset);
 0674        }
 675
 0676        _nextEdgeId = BitCoderBuffer.GetVarUInt32(data, ref offset);
 0677        Array.Resize(ref _edges, (int)_nextEdgeId);
 0678        Buffer.BlockCopy(data, offset, _edges, 0, (int)_nextEdgeId);
 0679        offset += (int)_nextEdgeId;
 680
 0681        _nextCrossTileId = BitCoderBuffer.GetVarUInt32(data, ref offset);
 0682        Array.Resize(ref _crossEdgePointers, (int)_nextCrossTileId);
 0683        for (var i = 0; i < _nextCrossTileId; i++)
 0684        {
 0685            _crossEdgePointers[i] = BitCoderBuffer.GetVarUInt32(data, ref offset);
 0686        }
 0687    }
 688
 689    private void WriteEdgesAndVerticesTo(byte[] data, ref int offset)
 0690    {
 0691        BitCoderBuffer.SetVarUInt32(data, ref offset, _nextVertexId);
 0692        for (var i = 0; i < _nextVertexId; i++)
 0693        {
 0694            BitCoderBuffer.SetVarUInt32(data, ref offset, _pointers[i]);
 0695        }
 696
 0697        BitCoderBuffer.SetVarUInt32(data, ref offset, _nextEdgeId);
 0698        Buffer.BlockCopy(_edges, 0, data, offset, (int)_nextEdgeId);
 0699        offset += (int)_nextEdgeId;
 700
 0701        BitCoderBuffer.SetVarUInt32(data, ref offset, _nextCrossTileId);
 0702        for (var i = 0; i < _nextCrossTileId; i++)
 0703        {
 0704            BitCoderBuffer.SetVarUInt32(data, ref offset, _crossEdgePointers[i]);
 0705        }
 0706    }
 707}

/home/runner/work/routing2/routing2/src/Itinero/Network/Tiles/NetworkTile.Diffs.cs

#LineLine coverage
 1namespace Itinero.Network.Tiles;
 2
 3/// <summary>
 4/// Per-tile geographic extent bounds used by the tile-bounded snap algorithm
 5/// in <c>EdgeSearch.SnapInBoxAsync</c>. See
 6/// <c>src/Itinero/Network/Search/snap-algorithm.md</c> for the design.
 7///
 8/// <para>
 9/// <see cref="MaxLonDiff"/> and <see cref="MaxLatDiff"/> bound how far any
 10/// edge starting at a vertex in this tile can reach in each axis. They are
 11/// the maxima of (edge.bbox.maxLon − edge.bbox.minLon) and
 12/// (edge.bbox.maxLat − edge.bbox.minLat) over every edge with at least one
 13/// vertex in the tile. Cross-tile edges contribute to both endpoint tiles'
 14/// diffs (each tile sees them once during its own per-vertex iteration).
 15/// </para>
 16///
 17/// <para>
 18/// Computed lazily on first access via <see cref="EnsureDiffs"/>, which
 19/// takes a network reference so that cross-tile edges' remote endpoints
 20/// can be resolved to their actual coordinates. The lazy contract: the
 21/// snap path's <c>NotifyBox</c> has already loaded the partner tiles by
 22/// the time the snap algorithm asks for diffs. If a partner tile somehow
 23/// isn't loaded, we fall back to the partner tile's geographic bbox
 24/// (~tile-width-wide over-estimate) — correct but loose.
 25/// </para>
 26///
 27/// <para>
 28/// Invalidated to <see cref="double.NaN"/> whenever an edge is added or
 29/// removed, so late boundary edges added by neighbouring tiles'
 30/// <c>AddStandaloneTile</c> calls don't leave stale values.
 31/// </para>
 32/// </summary>
 33internal partial class NetworkTile
 34{
 276735    private double _maxLonDiff = double.NaN;
 276736    private double _maxLatDiff = double.NaN;
 37
 38    /// <summary>
 39    /// Max lon-span across all edges with a vertex in this tile. Returns
 40    /// <see cref="double.NaN"/> if <see cref="EnsureDiffs"/> hasn't been
 41    /// called yet. Callers should invoke <see cref="EnsureDiffs"/> first.
 42    /// </summary>
 1087943    public double MaxLonDiff => _maxLonDiff;
 44
 45    /// <summary>
 46    /// Max lat-span across all edges with a vertex in this tile. See
 47    /// <see cref="MaxLonDiff"/>.
 48    /// </summary>
 1087949    public double MaxLatDiff => _maxLatDiff;
 50
 51    /// <summary>
 52    /// Reset the cached diffs. Call from any mutation that could change
 53    /// the tile's edge set (AddEdge, DeleteEdge, RemoveDeletedEdges).
 54    /// </summary>
 55    private void InvalidateDiffs()
 6536956    {
 6536957        _maxLonDiff = double.NaN;
 6536958        _maxLatDiff = double.NaN;
 6536959    }
 60
 61    /// <summary>
 62    /// Compute the diffs if not already cached. Takes a network reference
 63    /// so cross-tile edges can resolve their remote endpoint's actual
 64    /// coordinate. If the partner tile isn't loaded, falls back to the
 65    /// partner's geographic bbox (correct but loose).
 66    /// </summary>
 67    internal void EnsureDiffs(Itinero.Network.Enumerators.Edges.IEdgeEnumerable network)
 552068    {
 1080969        if (!double.IsNaN(_maxLonDiff)) return;
 70
 71        // Walk every edge once per endpoint that's in this tile. Intra-tile
 72        // edges are seen twice; max is idempotent so that's fine. Cross-tile
 73        // edges are seen once (from the local endpoint's pointer chain),
 74        // which is enough — the partner tile sees them independently from
 75        // its own side.
 23176        double maxLon = 0;
 23177        double maxLat = 0;
 78
 23179        var enumerator = new NetworkTileEnumerator();
 23180        enumerator.MoveTo(this);
 81
 5597282        for (uint v = 0; v < _nextVertexId; v++)
 2775583        {
 2775584            var vertexId = new VertexId(_tileId, v);
 2775585            if (!enumerator.MoveTo(vertexId)) continue;
 2775586            if (!this.TryGetVertex(vertexId, out var tailLon, out var tailLat, out _)) continue;
 87
 10375288            while (enumerator.MoveNext())
 7599789            {
 7599790                var minLon = tailLon;
 7599791                var maxLonE = tailLon;
 7599792                var minLat = tailLat;
 7599793                var maxLatE = tailLat;
 94
 95                // Resolve the head endpoint's actual coordinate. For
 96                // intra-tile edges it's right here; for cross-tile edges
 97                // we ask the network for the partner tile.
 7599798                var headResolved = false;
 15199499                double headLon = 0, headLat = 0;
 75997100                if (enumerator.Head.TileId == _tileId)
 73260101                {
 73260102                    if (this.TryGetVertex(enumerator.Head, out headLon, out headLat, out _))
 73260103                    {
 73260104                        headResolved = true;
 73260105                    }
 73260106                }
 107                else
 2737108                {
 2737109                    var partnerTile = network.GetTileForRead(enumerator.Head.TileId);
 2737110                    if (partnerTile != null &&
 2737111                        partnerTile.TryGetVertex(enumerator.Head, out headLon, out headLat, out _))
 2737112                    {
 2737113                        headResolved = true;
 2737114                    }
 2737115                }
 116
 75997117                if (headResolved)
 75997118                {
 111586119                    if (headLon < minLon) minLon = headLon;
 75724120                    else if (headLon > maxLonE) maxLonE = headLon;
 111064121                    if (headLat < minLat) minLat = headLat;
 75886122                    else if (headLat > maxLatE) maxLatE = headLat;
 75997123                }
 124                else
 0125                {
 126                    // Partner tile isn't loaded — fall back to its bbox.
 127                    // Over-estimates by up to ~one tile-width but stays
 128                    // correct (the per-vertex predicate built on this
 129                    // bound will be looser, never wrongly prune).
 0130                    var (hMinLon, hMinLat, hMaxLon, hMaxLat) =
 0131                        TileStatic.GetTileBoundingBox(_zoom, enumerator.Head.TileId);
 0132                    if (hMinLon < minLon) minLon = hMinLon;
 0133                    if (hMaxLon > maxLonE) maxLonE = hMaxLon;
 0134                    if (hMinLat < minLat) minLat = hMinLat;
 0135                    if (hMaxLat > maxLatE) maxLatE = hMaxLat;
 0136                }
 137
 138                // Shape points (intermediate).
 397573139                foreach (var (sLon, sLat, _) in enumerator.Shape)
 84791140                {
 89131141                    if (sLon < minLon) minLon = sLon;
 85105142                    else if (sLon > maxLonE) maxLonE = sLon;
 90001143                    if (sLat < minLat) minLat = sLat;
 83738144                    else if (sLat > maxLatE) maxLatE = sLat;
 84791145                }
 146
 75997147                var dLon = maxLonE - minLon;
 75997148                var dLat = maxLatE - minLat;
 76579149                if (dLon > maxLon) maxLon = dLon;
 76511150                if (dLat > maxLat) maxLat = dLat;
 75997151            }
 27755152        }
 153
 231154        _maxLonDiff = maxLon;
 231155        _maxLatDiff = maxLat;
 5520156    }
 157}

/home/runner/work/routing2/routing2/src/Itinero/Network/Tiles/NetworkTile.Geo.cs

#LineLine coverage
 1using System;
 2using System.Collections.Generic;
 3using System.IO;
 4using Itinero.IO;
 5using Itinero.Network.Storage;
 6
 7namespace Itinero.Network.Tiles;
 8
 9internal partial class NetworkTile
 10{
 11    private const int CoordinateSizeInBytes = 3; // 3 bytes = 24 bits = 4096 x 4096.
 12    private const int TileResolutionInBits = CoordinateSizeInBytes * 8 / 2;
 13    private const int ElevationSizeInBytes = 2; // 2 bytes = 16 bits = [-32768, 32767], using dm as resolution
 14
 15    // the vertex coordinates.
 16    private byte[] _coordinates;
 17    private int? _elevation; // the tile elevation.
 18
 19    // the shapes.
 276720    private uint _nextShapePointer = 0;
 21    private byte[] _shapes;
 22
 23    private void SetCoordinate(uint localId, double longitude, double latitude, float? e)
 4655624    {
 25        // set elevation if needed.
 4655626        if (_elevation != null && e == null)
 027        {
 028            throw new ArgumentNullException(nameof(e),
 029                "Elevation was set before, either always set elevation or never set elevation.");
 30        }
 31
 4655632        if (_elevation == null && e != null)
 1333        {
 1334            if (localId != 0)
 035            {
 036                throw new ArgumentNullException(nameof(e),
 037                    "Elevation was not set before, either always set elevation or never set elevation.");
 38            }
 39
 1340            _elevation = (int)(e * 10);
 1341        }
 42
 43        // make sure coordinates fit.
 44        uint tileCoordinatePointer;
 4655645        if (_elevation == null)
 4651846        {
 47            // don't store elevation.
 4651848            tileCoordinatePointer = localId * CoordinateSizeInBytes * 2;
 4651849            ArrayBaseExtensions.EnsureMinimumSize(ref _coordinates, tileCoordinatePointer + (CoordinateSizeInBytes * 2),
 4651850                DefaultSizeIncrease);
 4651851        }
 52        else
 3853        {
 54            // store elevation.
 3855            tileCoordinatePointer = localId * ((CoordinateSizeInBytes * 2) + ElevationSizeInBytes);
 3856            ArrayBaseExtensions.EnsureMinimumSize(ref _coordinates, tileCoordinatePointer + (CoordinateSizeInBytes * 2) 
 3857                DefaultSizeIncrease);
 3858        }
 59
 60        // write coordinates.
 4655661        var (x, y) = this.ToLocalCoordinates(longitude, latitude);
 4655662        _coordinates.SetFixed(tileCoordinatePointer, CoordinateSizeInBytes, x);
 4655663        _coordinates.SetFixed(tileCoordinatePointer + CoordinateSizeInBytes, CoordinateSizeInBytes, y);
 64
 65        // write elevation.
 4655666        if (_elevation != null)
 3867        {
 3868            if (e == null)
 069            {
 070                throw new ArgumentNullException(nameof(e),
 071                    "Elevation was set before, either always set elevation or never set elevation.");
 72            }
 73
 3874            var offset = (int)(e.Value * 10) - _elevation.Value;
 3875            _coordinates.SetFixed(tileCoordinatePointer + CoordinateSizeInBytes + CoordinateSizeInBytes,
 3876                ElevationSizeInBytes, offset);
 3877        }
 4655678    }
 79
 80    private void GetCoordinate(uint localId, out double longitude, out double latitude, out float? elevation)
 566243981    {
 566243982        var tileCoordinatePointer = _elevation == null
 566243983            ? localId * CoordinateSizeInBytes * 2
 566243984            : localId * ((CoordinateSizeInBytes * 2) + ElevationSizeInBytes);
 85
 86        const int resolution = (1 << TileResolutionInBits) - 1;
 566243987        _coordinates.GetFixed(tileCoordinatePointer, CoordinateSizeInBytes, out var x);
 566243988        _coordinates.GetFixed(tileCoordinatePointer + CoordinateSizeInBytes, CoordinateSizeInBytes, out var y);
 566243989        elevation = null;
 566243990        if (_elevation != null)
 8991        {
 8992            _coordinates.GetFixed(tileCoordinatePointer + CoordinateSizeInBytes + CoordinateSizeInBytes,
 8993                ElevationSizeInBytes, out var offset);
 8994            elevation = (_elevation.Value + offset) / 10.0f;
 8995        }
 96
 566243997        this.FromLocalCoordinates(x, y, out longitude, out latitude);
 566243998    }
 99
 100    // Box and step size are the same for every vertex in the tile; computing them per
 101    // coordinate read cost two Math.Sinh, two Math.Atan and four Math.Pow each time.
 102    private readonly double _boxLeft;
 103
 104    private readonly double _boxTop;
 105
 106    private readonly double _boxLonStep;
 107
 108    private readonly double _boxLatStep;
 109
 110    /// The local-coordinate resolution every call site uses; a compile-time constant.
 111    private const int CoordinateResolution = (1 << TileResolutionInBits) - 1;
 112
 113    private (double left, double top, double lonStep, double latStep) ComputeBox()
 2767114    {
 2767115        var (minLon, minLat, maxLon, maxLat) = TileStatic.GetTileBoundingBox(_zoom, _tileId);
 116
 2767117        return (minLon, maxLat,
 2767118            (maxLon - minLon) / CoordinateResolution,
 2767119            (maxLat - minLat) / CoordinateResolution);
 2767120    }
 121
 122    /// Tile-local integer coordinates to lon/lat, using the cached box.
 123    private void FromLocalCoordinates(int x, int y, out double longitude, out double latitude)
 7122314124    {
 7122314125        longitude = _boxLeft + (_boxLonStep * x);
 7122314126        latitude = _boxTop - (_boxLatStep * y);
 7122314127    }
 128
 129    /// Lon/lat to tile-local integer coordinates, using the cached box.
 130    private (int x, int y) ToLocalCoordinates(double longitude, double latitude) =>
 132118131        ((int)((longitude - _boxLeft) / _boxLonStep), (int)((_boxTop - latitude) / _boxLatStep));
 132
 133    private uint SetShape(IEnumerable<(double longitude, double latitude, float? e)> shape)
 56264134    {
 135        const int resolution = (1 << TileResolutionInBits) - 1;
 56264136        var originalPointer = _nextShapePointer;
 56264137        var blockPointer = originalPointer;
 56264138        var pointer = blockPointer + 1;
 139
 140        // make sure there is space for the block pointer.
 56264141        ArrayBaseExtensions.EnsureMinimumSize(ref _shapes, blockPointer);
 142
 56264143        var coordinateBlockSize = 8;
 56264144        if (_elevation != null)
 24145        {
 24146            coordinateBlockSize += 4;
 24147        }
 148
 56264149        using var enumerator = shape.GetEnumerator();
 56264150        var count = 0;
 56264151        (int x, int y, int? eOffset) previous = (int.MaxValue, int.MaxValue, null);
 141826152        while (enumerator.MoveNext())
 85562153        {
 85562154            var current = enumerator.Current;
 85562155            var (x, y) =
 85562156                this.ToLocalCoordinates(current.longitude, current.latitude);
 85562157            int? eOffset = null;
 85562158            var e = current.e ?? 0;
 85562159            if (_elevation != null)
 15160            {
 15161                eOffset = (int)(e * 10) - _elevation.Value;
 15162            }
 163
 164            // make sure there is space for this coordinate.
 85562165            ArrayBaseExtensions.EnsureMinimumSize(ref _shapes, pointer + coordinateBlockSize);
 166
 167            // store coordinate.
 85562168            if (count == 0)
 24222169            {
 170                // first coordinate.
 24222171                pointer += (uint)_shapes.SetDynamicInt32(pointer, x);
 24222172                pointer += (uint)_shapes.SetDynamicInt32(pointer, y);
 24222173                if (eOffset != null)
 7174                {
 7175                    pointer += (uint)_shapes.SetDynamicInt32(pointer, eOffset.Value);
 7176                }
 24222177            }
 178            else
 61340179            {
 180                // calculate diff and then store.
 61340181                var diffX = x - previous.x;
 61340182                var diffY = y - previous.y;
 61340183                pointer += (uint)_shapes.SetDynamicInt32(pointer, diffX);
 61340184                pointer += (uint)_shapes.SetDynamicInt32(pointer, diffY);
 61340185                if (eOffset != null)
 8186                {
 8187                    if (previous.eOffset == null)
 0188                    {
 0189                        throw new ArgumentException("Not all points have elevation set.");
 190                    }
 191
 8192                    var diffE = eOffset.Value - previous.eOffset.Value;
 8193                    pointer += (uint)_shapes.SetDynamicInt32(pointer, diffE);
 8194                }
 61340195            }
 196
 85562197            count++;
 198
 85562199            if (count == 255)
 1200            {
 201                // start a new block, assign 255.
 1202                _shapes[(int)blockPointer] = 255;
 1203                blockPointer = pointer;
 1204                pointer = blockPointer + 1;
 1205                count = 0;
 1206            }
 207
 85562208            previous = (x, y, eOffset);
 85562209        }
 210
 211        // a block is still open, close it.
 56264212        _shapes[(int)blockPointer] = (byte)count;
 56264213        _nextShapePointer = pointer;
 214
 56264215        return originalPointer;
 56264216    }
 217
 218    internal IEnumerable<(double longitude, double latitude, float? e)> GetShape(uint? pointer)
 1327145219    {
 1327145220        if (pointer == null)
 10104221        {
 10104222            yield break;
 223        }
 224
 1317041225        var p = pointer.Value;
 226
 227        const int resolution = (1 << TileResolutionInBits) - 1;
 1317041228        var count = -1;
 1317041229        (int x, int y, int? eOffset) previous = (int.MaxValue, int.MaxValue, null);
 1317042230        while (true)
 1317042231        {
 1317042232            count = _shapes[(int)p];
 1317042233            p++;
 234
 5551776235            for (var i = 0; i < count; i++)
 1459875236            {
 1459875237                p += (uint)_shapes.GetDynamicInt32(p, out var x);
 1459875238                p += (uint)_shapes.GetDynamicInt32(p, out var y);
 1459875239                int? eOffset = null;
 1459875240                if (_elevation != null)
 16241                {
 16242                    p += (uint)_shapes.GetDynamicInt32(p, out var e);
 16243                    eOffset = e;
 16244                }
 245
 1459875246                if (i > 0)
 1019862247                {
 1019862248                    x = previous.x + x;
 1019862249                    y = previous.y + y;
 1019862250                    if (_elevation != null)
 8251                    {
 8252                        if (previous.eOffset == null)
 0253                        {
 0254                            throw new ArgumentException("Not all points have elevation set.");
 255                        }
 256
 8257                        eOffset = previous.eOffset.Value + eOffset;
 8258                    }
 1019862259                }
 260
 1459875261                int? elevation = null;
 1459875262                if (_elevation != null)
 16263                {
 16264                    if (eOffset == null)
 0265                    {
 0266                        throw new ArgumentException("Not all points have elevation set.");
 267                    }
 268
 16269                    elevation = _elevation.Value + eOffset.Value;
 16270                }
 271
 1459875272                this.FromLocalCoordinates(x, y, out var longitude,
 1459875273                    out var latitude);
 1459875274                yield return (longitude, latitude, elevation / 10.0f);
 275
 1458846276                previous = (x, y, eOffset);
 1458846277            }
 278
 2632025279            if (count < 255) break;
 1280        }
 1316012281    }
 282
 283    private void WriteGeoTo(Stream stream)
 8284    {
 8285        stream.WriteVarInt32Nullable(_elevation);
 286
 287        // write vertex locations.
 8288        var coordinateSize = CoordinateSizeInBytes * 2;
 8289        if (_elevation != null)
 2290        {
 2291            coordinateSize += ElevationSizeInBytes;
 2292        }
 293
 8294        var coordinateBytes = _nextVertexId * coordinateSize;
 184295        for (var i = 0; i < coordinateBytes; i++)
 84296        {
 84297            stream.WriteByte(_coordinates[i]);
 84298        }
 299
 300        // write shape locations.
 8301        stream.WriteVarUInt32(_nextShapePointer);
 74302        for (var i = 0; i < _nextShapePointer; i++)
 29303        {
 29304            stream.WriteByte(_shapes[i]);
 29305        }
 8306    }
 307
 308    private void ReadGeoFrom(Stream stream)
 8309    {
 8310        _elevation = stream.ReadVarInt32Nullable();
 311
 312        // read vertex locations.
 8313        var coordinateSize = CoordinateSizeInBytes * 2;
 8314        if (_elevation != null)
 2315        {
 2316            coordinateSize += ElevationSizeInBytes;
 2317        }
 318
 8319        var coordinateBytes = _nextVertexId * coordinateSize;
 8320        Array.Resize(ref _coordinates, (int)coordinateBytes);
 184321        for (var i = 0; i < coordinateBytes; i++)
 84322        {
 84323            _coordinates[i] = (byte)stream.ReadByte();
 84324        }
 325
 8326        _nextShapePointer = stream.ReadVarUInt32();
 8327        Array.Resize(ref _shapes, (int)_nextShapePointer);
 74328        for (var i = 0; i < _nextShapePointer; i++)
 29329        {
 29330            _shapes[i] = (byte)stream.ReadByte();
 29331        }
 8332    }
 333
 334    private void ReadGeoFrom(byte[] data, ref int offset)
 0335    {
 0336        _elevation = BitCoderBuffer.GetVarInt32Nullable(data, ref offset);
 337
 0338        var coordinateSize = CoordinateSizeInBytes * 2;
 0339        if (_elevation != null)
 0340        {
 0341            coordinateSize += ElevationSizeInBytes;
 0342        }
 343
 0344        var coordinateBytes = (int)(_nextVertexId * coordinateSize);
 0345        Array.Resize(ref _coordinates, coordinateBytes);
 0346        Buffer.BlockCopy(data, offset, _coordinates, 0, coordinateBytes);
 0347        offset += coordinateBytes;
 348
 0349        _nextShapePointer = BitCoderBuffer.GetVarUInt32(data, ref offset);
 0350        Array.Resize(ref _shapes, (int)_nextShapePointer);
 0351        Buffer.BlockCopy(data, offset, _shapes, 0, (int)_nextShapePointer);
 0352        offset += (int)_nextShapePointer;
 0353    }
 354
 355    private void WriteGeoTo(byte[] data, ref int offset)
 0356    {
 0357        BitCoderBuffer.SetVarInt32Nullable(data, ref offset, _elevation);
 358
 0359        var coordinateSize = CoordinateSizeInBytes * 2;
 0360        if (_elevation != null)
 0361        {
 0362            coordinateSize += ElevationSizeInBytes;
 0363        }
 364
 0365        var coordinateBytes = (int)(_nextVertexId * coordinateSize);
 0366        Buffer.BlockCopy(_coordinates, 0, data, offset, coordinateBytes);
 0367        offset += coordinateBytes;
 368
 0369        BitCoderBuffer.SetVarUInt32(data, ref offset, _nextShapePointer);
 0370        Buffer.BlockCopy(_shapes, 0, data, offset, (int)_nextShapePointer);
 0371        offset += (int)_nextShapePointer;
 0372    }
 373
 374    /// Shrinks the shape buffer to what it holds. See NetworkTile.Trim.
 375    private void TrimShapes()
 1928376    {
 3798377        if (_shapes.Length > _nextShapePointer) Array.Resize(ref _shapes, (int)_nextShapePointer);
 1928378    }
 379}

/home/runner/work/routing2/routing2/src/Itinero/Network/Tiles/NetworkTile.Serialization.cs

#LineLine coverage
 1using System;
 2using System.IO;
 3using Itinero.IO;
 4
 5namespace Itinero.Network.Tiles;
 6
 7internal partial class NetworkTile
 8{
 9    public void WriteTo(Stream stream)
 810    {
 11        const int version = 1;
 812        stream.WriteVarInt32(version);
 13
 14        // write tile id/zoom.
 815        stream.WriteVarInt32(_zoom);
 816        stream.WriteVarUInt32(_tileId);
 817        stream.WriteGuid(_edgeTypeMapId);
 18
 19        // write vertices and edges.
 820        this.WriteEdgesAndVerticesTo(stream);
 21
 22        // write attributes.
 823        this.WriteAttributesTo(stream);
 24
 25        // write shapes.
 826        this.WriteGeoTo(stream);
 27
 28        // write turn costs.
 829        this.WriteTurnCostsTo(stream);
 830    }
 31
 32    public static NetworkTile ReadFrom(Stream stream)
 833    {
 834        var version = stream.ReadVarInt32();
 835        if (version != 1)
 036        {
 037            throw new InvalidDataException("Cannot deserialize tiles: Invalid version #.");
 38        }
 39
 40        // read tile id.
 841        var zoom = stream.ReadVarInt32();
 842        var tileId = stream.ReadVarUInt32();
 843        var edgeTypeMapId = stream.ReadGuid();
 44
 45        // create the tile.
 846        var graphTile = new NetworkTile(zoom, tileId, edgeTypeMapId);
 47
 48        // read vertices and edges.
 849        graphTile.ReadEdgesAndVerticesFrom(stream);
 50
 51        // read attributes.
 852        graphTile.ReadAttributesFrom(stream);
 53
 54        // read shapes.
 855        graphTile.ReadGeoFrom(stream);
 56
 57        // read turn costs.
 858        graphTile.ReadTurnCostsFrom(stream);
 59
 860        return graphTile;
 861    }
 62
 63    internal static NetworkTile ReadFromBuffer(byte[] data, ref int offset)
 064    {
 065        var version = BitCoderBuffer.GetVarInt32(data, ref offset);
 066        if (version != 1)
 067        {
 068            throw new InvalidDataException("Cannot deserialize tiles: Invalid version #.");
 69        }
 70
 071        var zoom = BitCoderBuffer.GetVarInt32(data, ref offset);
 072        var tileId = BitCoderBuffer.GetVarUInt32(data, ref offset);
 073        var edgeTypeMapId = BitCoderBuffer.GetGuid(data, ref offset);
 74
 075        var graphTile = new NetworkTile(zoom, tileId, edgeTypeMapId);
 76
 077        graphTile.ReadEdgesAndVerticesFrom(data, ref offset);
 078        graphTile.ReadAttributesFrom(data, ref offset);
 079        graphTile.ReadGeoFrom(data, ref offset);
 080        graphTile.ReadTurnCostsFrom(data, ref offset);
 81
 082        return graphTile;
 083    }
 84
 85    public static NetworkTile ReadFrom(byte[] data, int offset)
 086    {
 087        return ReadFromBuffer(data, ref offset);
 088    }
 89
 90    public byte[] ToBytes()
 091    {
 092        var maxSize = this.GetSerializedSizeUpperBound();
 093        var buffer = new byte[maxSize];
 094        var offset = 0;
 095        this.WriteToBuffer(buffer, ref offset);
 096        if (offset == maxSize) return buffer;
 097        var result = new byte[offset];
 098        Buffer.BlockCopy(buffer, 0, result, 0, offset);
 099        return result;
 0100    }
 101
 102    internal void WriteToBuffer(byte[] data, ref int offset)
 0103    {
 104        const int version = 1;
 0105        BitCoderBuffer.SetVarInt32(data, ref offset, version);
 0106        BitCoderBuffer.SetVarInt32(data, ref offset, _zoom);
 0107        BitCoderBuffer.SetVarUInt32(data, ref offset, _tileId);
 0108        BitCoderBuffer.SetGuid(data, ref offset, _edgeTypeMapId);
 109
 0110        this.WriteEdgesAndVerticesTo(data, ref offset);
 0111        this.WriteAttributesTo(data, ref offset);
 0112        this.WriteGeoTo(data, ref offset);
 0113        this.WriteTurnCostsTo(data, ref offset);
 0114    }
 115
 116    internal int GetSerializedSizeUpperBound()
 0117    {
 0118        var size = 5 + 5 + 5 + 16;
 119
 0120        size += 5 + (int)_nextVertexId * 5;
 0121        size += 5 + (int)_nextEdgeId;
 0122        size += 5 + (int)_nextCrossTileId * 5;
 123
 0124        size += 5 + (int)_nextAttributePointer;
 0125        size += 5;
 0126        for (var i = 0; i < _nextStringId; i++)
 0127        {
 0128            size += 8 + System.Text.Encoding.Unicode.GetByteCount(_strings[i]);
 0129        }
 130
 0131        size += 5;
 0132        var coordinateSize = CoordinateSizeInBytes * 2;
 0133        if (_elevation != null) coordinateSize += ElevationSizeInBytes;
 0134        size += (int)(_nextVertexId * coordinateSize);
 0135        size += 5 + (int)_nextShapePointer;
 136
 0137        size += 5 + _turnCostPointers.Length * 5;
 0138        size += 5 + (int)_turnCostPointer;
 139
 0140        return size;
 0141    }
 142}

/home/runner/work/routing2/routing2/src/Itinero/Network/Tiles/NetworkTile.TurnCosts.cs

#LineLine coverage
 1using System;
 2using System.Collections.Generic;
 3using System.IO;
 4using System.Linq;
 5using Itinero.IO;
 6using Itinero.Network.Storage;
 7using Itinero.Network.TurnCosts;
 8
 9namespace Itinero.Network.Tiles;
 10
 11internal partial class NetworkTile
 12{
 276713    private uint _turnCostPointer = 0;
 276714    private uint[] _turnCostPointers = new uint[0];
 276715    private byte[] _turnCosts = new byte[0];
 16
 17    /// Returns false when the vertex has no order budget left, see OrderCoder.
 18    internal bool AddTurnCosts(VertexId vertex, uint turnCostType,
 19        EdgeId[] edges, uint[,] costs, IEnumerable<(string key, string value)> attributes,
 20        IEnumerable<EdgeId>? prefix = null)
 934621    {
 934622        prefix ??= ArraySegment<EdgeId>.Empty;
 23
 24        // enumerate the edges associated with the vertex.
 934625        var enumerator = new NetworkTileEnumerator();
 934626        enumerator.MoveTo(this);
 934627        if (!enumerator.MoveTo(vertex))
 028        {
 029            throw new ArgumentException($"Cannot add turn costs to a vertex that doesn't exist.",
 030                nameof(vertex));
 31        }
 32
 33        // determine max existing order, perhaps there are other turn costs already.
 934634        var orders = new byte?[edges.Length];
 934635        var max = -1;
 2907136        while (enumerator.MoveNext())
 1972537        {
 2925238            if (!enumerator.TailOrder.HasValue) continue;
 1110539            if (enumerator.TailOrder.Value <= max) continue;
 40
 929141            max = enumerator.TailOrder.Value;
 929142        }
 43
 44        // orders are assigned from max + 1 up and packed into 4 bits, so check the budget
 45        // before writing any of them - a partial assignment would corrupt the tile.
 934646        enumerator.Reset();
 934647        var needed = 0;
 2907148        while (enumerator.MoveNext())
 1972549        {
 2072250            if (Array.IndexOf(edges, enumerator.EdgeId) == -1) continue;
 2824951            if (enumerator.TailOrder.HasValue) continue;
 52
 920753            needed++;
 920754        }
 55
 935356        if (max + needed > OrderCoder.MaxOrderHeadTail) return false;
 57
 58        // assign missing orders if any.
 933959        enumerator.Reset();
 933960        var next = max + 1;
 2892461        while (enumerator.MoveNext())
 1958562        {
 63            // only assign orders of edges that are used.
 1958564            var i = Array.IndexOf(edges, enumerator.EdgeId);
 2049265            if (i == -1) continue;
 66
 67            // edge is used, assign or reuse existing.
 1867868            var order = enumerator.TailOrder;
 1867869            if (order == null)
 916070            {
 71                // get next order.
 916072                order = (byte)next;
 916073                next++;
 74
 75                // set order, it's different.
 916076                if (enumerator.Forward)
 457777                {
 78                    // if the edge is forward the tail in the enumerator is also the tail in the edge.
 457779                    this.SetTailHeadOrder(enumerator.EdgePointer, order, enumerator.HeadOrder);
 457780                }
 81                else
 458382                {
 83                    // if the edge is backward the tail in the enumerator is head in the edge.
 458384                    this.SetTailHeadOrder(enumerator.EdgePointer, enumerator.TailOrder, order);
 458385                }
 916086            }
 87
 1867888            orders[i] = order;
 1867889        }
 90
 91        // reversed order array.
 933992        var count = next;
 933993        var reversedOrders = new byte?[count];
 5603494        for (var i = 0; i < orders.Length; i++)
 1867895        {
 1867896            var order = orders[i];
 1867897            if (order == null)
 098            {
 099                continue;
 100            }
 101
 18678102            reversedOrders[order.Value] = (byte)i;
 18678103        }
 104
 105        // make sure there is space in the pointers table.
 106        // and initialize new slots with null.
 11338107        while (_turnCostPointers.Length <= vertex.LocalId)
 1999108        {
 1999109            Array.Resize(ref _turnCostPointers, (int)_nextVertexId);
 1999110        }
 111
 112        // make sure there is space in the turn cost array.
 113        // and initialize new slots with null.
 9339114        var maxLength = _turnCostPointer + 5 + 1 + (count * count * 5) + 5;
 9339115        EnsureCapacity(ref _turnCosts, maxLength + 1, DefaultSizeIncrease);
 116
 117        // update pointer to reflect new data.
 9339118        var previousPointer = _turnCostPointers[(int)vertex.LocalId].DecodeNullableData();
 9339119        _turnCostPointers[(int)vertex.LocalId] = _turnCostPointer.EncodeToNullableData();
 120
 121        // write turn cost types.
 9339122        _turnCostPointer += _turnCosts.SetDynamicUInt32(_turnCostPointer, turnCostType);
 123
 124        // write attributes.
 9339125        var a = this.SetAttributes(attributes, null);
 9339126        _turnCostPointer += _turnCosts.SetDynamicUInt32(_turnCostPointer, a);
 127
 128        // write prefix sequence.
 129        // Use Int64 so the same-tile/foreign-tile signal (sign of the encoded value) round-trips
 130        // correctly for any uint LocalId, including CrossEdgeIds where LocalId >= 0x7FFFFFFF.
 131        // (Int32 would silently overflow-wrap to a positive value when LocalId has the high bit set,
 132        // making the reader misread foreign edges as same-tile and skip the tile id varint.)
 9339133        var prefixEdges = new List<EdgeId>(prefix);
 9339134        _turnCostPointer += _turnCosts.SetDynamicUInt32(_turnCostPointer, (uint)prefixEdges.Count);
 28017135        foreach (var prefixEdge in prefixEdges)
 0136        {
 0137            if (prefixEdge.TileId == _tileId)
 0138            {
 0139                _turnCostPointer += _turnCosts.SetDynamicInt64(_turnCostPointer, (long)prefixEdge.LocalId);
 0140            }
 141            else
 0142            {
 0143                _turnCostPointer += _turnCosts.SetDynamicInt64(_turnCostPointer, -(long)prefixEdge.LocalId - 1);
 0144                _turnCostPointer += _turnCosts.SetDynamicUInt32(_turnCostPointer, prefixEdge.TileId);
 0145            }
 0146        }
 147
 148        // write turn costs.
 9339149        _turnCosts[(int)_turnCostPointer] = (byte)count;
 9339150        _turnCostPointer++;
 57240151        for (var x = 0; x < count; x++)
 19281152        {
 19281153            var xOrder = reversedOrders[x];
 121360154            for (var y = 0; y < count; y++)
 41399155            {
 41399156                var yOrder = reversedOrders[y];
 157
 158                // get cost from original matrix.
 41399159                uint cost = 0;
 41399160                if (xOrder != null && yOrder != null)
 37356161                {
 37356162                    cost = costs[xOrder.Value, yOrder.Value];
 37356163                }
 164
 165                // write cost.
 41399166                _turnCostPointer += (uint)_turnCosts.SetDynamicUInt32(_turnCostPointer, cost);
 41399167            }
 19281168        }
 169
 170        // write previous turn cost pointer at the end.
 9339171        _turnCostPointer +=
 9339172            (uint)_turnCosts.SetDynamicUInt32(_turnCostPointer, previousPointer.EncodeAsNullableData());
 173
 9339174        return true;
 9346175    }
 176
 177    internal IEnumerable<(uint turnCostType, IEnumerable<(string key, string value)> attributes, uint cost,
 178            IEnumerable<EdgeId> prefixEdges)>
 179        GetTurnCosts(VertexId vertex, byte fromOrder, byte toOrder)
 19197180    {
 19197181        if (_turnCostPointers.Length <= vertex.LocalId)
 0182        {
 0183            yield break;
 184        }
 185
 19197186        var pointerNullable = _turnCostPointers[(int)vertex.LocalId].DecodeNullableData();
 19197187        if (pointerNullable == null)
 0188        {
 0189            yield break;
 190        }
 191
 19197192        var pointer = pointerNullable.Value;
 40790193        while (true)
 40790194        {
 195            // return turn cost type.
 40790196            pointer += (uint)_turnCosts.GetDynamicUInt32(pointer, out var turnCostType);
 197
 198            // read attributes.
 40790199            pointer += (uint)_turnCosts.GetDynamicUInt32(pointer, out var a);
 40790200            var attributes = this.GetAttributes(a);
 201
 202            // read prefix edges.
 203            // Pair with the Int64 writer above; Int32 would mis-decode the sign for CrossEdgeIds.
 40790204            IEnumerable<EdgeId> prefixEdges = ArraySegment<EdgeId>.Empty;
 40790205            pointer += (uint)_turnCosts.GetDynamicUInt32(pointer, out var prefixEdgeCount);
 40790206            if (prefixEdgeCount > 0)
 0207            {
 0208                var prefixEdgesList = new List<EdgeId>();
 0209                while (prefixEdgeCount > 0)
 0210                {
 0211                    pointer += (uint)_turnCosts.GetDynamicInt64(pointer, out var signedLocalId);
 0212                    if (signedLocalId >= 0)
 0213                    {
 0214                        prefixEdgesList.Add(new EdgeId(this.TileId, (uint)signedLocalId));
 0215                    }
 216                    else
 0217                    {
 0218                        pointer += (uint)_turnCosts.GetDynamicUInt32(pointer, out var tileId);
 0219                        prefixEdgesList.Add(new EdgeId(tileId, (uint)(-signedLocalId - 1)));
 0220                    }
 221
 0222                    prefixEdgeCount--;
 0223                }
 224
 0225                prefixEdges = prefixEdgesList;
 0226            }
 227
 228            // read turn cost table.
 40790229            var max = _turnCosts[(int)pointer];
 40790230            pointer++;
 231
 250738232            for (var x = 0; x < max; x++)
 84634233            {
 525984234                for (var y = 0; y < max; y++)
 178413235                {
 178413236                    pointer += (uint)_turnCosts.GetDynamicUInt32(pointer, out var cost);
 178413237                    if (fromOrder != x || toOrder != y)
 138008238                    {
 138008239                        continue;
 240                    }
 241
 40405242                    if (cost != 0)
 19196243                    {
 19196244                        yield return (turnCostType, attributes, cost, prefixEdges);
 19141245                    }
 40350246                }
 84579247            }
 248
 249            // get pointer to next turn cost table.
 40735250            _turnCosts.GetDynamicUInt32(pointer, out var p);
 40735251            pointerNullable = p.DecodeNullableData();
 40735252            if (pointerNullable == null)
 19142253            {
 19142254                break;
 255            }
 256
 21593257            pointer = pointerNullable.Value;
 21593258        }
 19142259    }
 260
 261    internal void SetTailHeadOrder(uint pointer, byte? tailOrder, byte? headOrder)
 10090262    {
 263        // skip over vertices and next-pointers.
 10090264        uint size = this.DecodeVertex(pointer, out _, out var t1);
 10090265        pointer += size;
 10090266        size = this.DecodeVertex(pointer, out _, out var t2);
 10090267        pointer += size;
 10090268        size = this.DecodePointer(pointer, out _);
 10090269        pointer += size;
 10090270        size = this.DecodePointer(pointer, out _);
 10090271        pointer += size;
 272
 273        // skip edge id if needed.
 10090274        if (t1 != t2)
 1478275        {
 1478276            size = _edges.GetDynamicUInt32(pointer, out _);
 1478277            pointer += size;
 1478278        }
 279
 280        // skip over length/type.
 10090281        size = this.DecodeEdgePointerId(pointer, out _);
 10090282        pointer += size;
 10090283        size = this.DecodeEdgePointerId(pointer, out _);
 10090284        pointer += size;
 285
 286        // get existing head/tail order.
 10090287        byte? existingTailOrder = null;
 10090288        byte? existingHeadOrder = null;
 10090289        this.GetTailHeadOrder(pointer, ref existingTailOrder, ref existingHeadOrder);
 290
 291        // set tail order if there is a value.
 10090292        if (tailOrder.HasValue)
 5191293        {
 5191294            if (existingTailOrder.HasValue && existingTailOrder.Value != tailOrder.Value)
 0295                throw new InvalidOperationException("An edge tail or head order can only be set once.");
 5191296            existingTailOrder = tailOrder;
 5191297        }
 298
 299        // set head order if there is a value.
 10090300        if (headOrder.HasValue)
 5138301        {
 5138302            if (existingHeadOrder.HasValue && existingHeadOrder.Value != headOrder.Value)
 0303                throw new InvalidOperationException("An edge tail or head order can only be set once.");
 5138304            existingHeadOrder = headOrder;
 5138305        }
 306
 10090307        _edges.SetTailHeadOrder(pointer, existingTailOrder, existingHeadOrder);
 10090308    }
 309
 310    private void WriteTurnCostsTo(Stream stream)
 8311    {
 8312        stream.WriteVarUInt32((uint)_turnCostPointers.Length);
 16313        for (var i = 0; i < _turnCostPointers.Length; i++)
 0314        {
 0315            stream.WriteVarUInt32(_turnCostPointers[i]);
 0316        }
 317
 8318        stream.WriteVarUInt32(_turnCostPointer);
 16319        for (var i = 0; i < _turnCostPointer; i++)
 0320        {
 0321            stream.WriteByte(_turnCosts[i]);
 0322        }
 8323    }
 324
 325    private void ReadTurnCostsFrom(Stream stream)
 8326    {
 8327        var turnCostPointersSize = stream.ReadVarUInt32();
 8328        Array.Resize(ref _turnCostPointers, (int)turnCostPointersSize);
 16329        for (var i = 0; i < turnCostPointersSize; i++)
 0330        {
 0331            _turnCostPointers[i] = stream.ReadVarUInt32();
 0332        }
 333
 8334        _turnCostPointer = stream.ReadVarUInt32();
 8335        Array.Resize(ref _turnCosts, (int)_turnCostPointer);
 16336        for (var i = 0; i < _turnCostPointer; i++)
 0337        {
 0338            _turnCosts[i] = (byte)stream.ReadByte();
 0339        }
 8340    }
 341
 342    private void ReadTurnCostsFrom(byte[] data, ref int offset)
 0343    {
 0344        var turnCostPointersSize = BitCoderBuffer.GetVarUInt32(data, ref offset);
 0345        Array.Resize(ref _turnCostPointers, (int)turnCostPointersSize);
 0346        for (var i = 0; i < turnCostPointersSize; i++)
 0347        {
 0348            _turnCostPointers[i] = BitCoderBuffer.GetVarUInt32(data, ref offset);
 0349        }
 350
 0351        _turnCostPointer = BitCoderBuffer.GetVarUInt32(data, ref offset);
 0352        Array.Resize(ref _turnCosts, (int)_turnCostPointer);
 0353        Buffer.BlockCopy(data, offset, _turnCosts, 0, (int)_turnCostPointer);
 0354        offset += (int)_turnCostPointer;
 0355    }
 356
 357    private void WriteTurnCostsTo(byte[] data, ref int offset)
 0358    {
 0359        BitCoderBuffer.SetVarUInt32(data, ref offset, (uint)_turnCostPointers.Length);
 0360        for (var i = 0; i < _turnCostPointers.Length; i++)
 0361        {
 0362            BitCoderBuffer.SetVarUInt32(data, ref offset, _turnCostPointers[i]);
 0363        }
 364
 0365        BitCoderBuffer.SetVarUInt32(data, ref offset, _turnCostPointer);
 0366        Buffer.BlockCopy(_turnCosts, 0, data, offset, (int)_turnCostPointer);
 0367        offset += (int)_turnCostPointer;
 0368    }
 369
 370    /// Shrinks the turn cost buffer to what it holds. See NetworkTile.Trim.
 371    private void TrimTurnCosts()
 1928372    {
 3793373        if (_turnCosts.Length > _turnCostPointer) Array.Resize(ref _turnCosts, (int)_turnCostPointer);
 1928374    }
 375}