コード例 #1
0
        /// <summary>
        /// Creates a new router db stream target.
        /// </summary>
        public RouterDbStreamTarget(RouterDb db, VehicleCache vehicleCache, bool allCore = false,
                                    int minimumStages            = 1, IEnumerable <ITwoPassProcessor> processors = null, bool processRestrictions = false,
                                    float simplifyEpsilonInMeter = .1f)
        {
            _db      = db;
            _allCore = allCore;
            _simplifyEpsilonInMeter = simplifyEpsilonInMeter;

            _vehicleCache = vehicleCache;
            _vehicleTypes = new HashSet <string>();
            _nodeIndex    = new NodeIndex();

            foreach (var vehicle in _vehicleCache.Vehicles)
            {
                foreach (var vehicleType in vehicle.VehicleTypes)
                {
                    _vehicleTypes.Add(vehicleType);
                }
            }

            foreach (var vehicle in _vehicleCache.Vehicles)
            {
                db.AddSupportedVehicle(vehicle);
            }

            if (processors == null)
            {
                processors = new List <ITwoPassProcessor>();
            }
            this.Processors = new List <ITwoPassProcessor>(processors);

            this.InitializeDefaultProcessors(processRestrictions);
        }
コード例 #2
0
        /// <summary>
        /// Loads all OSM data in the given bounding box by using routable tiles.
        /// </summary>
        /// <param name="db">The routerdb to fill.</param>
        /// <param name="box">The bounding box to fetch tiles for.</param>
        public static void LoadOsmDataFromTiles(this RouterDb db, Box box, bool keepGlobalIds = true, VehicleCache vehicleCache = null)
        {
            // build the tile range.
            var tileRange = new TileRange(box, Zoom);

            // build the vehicle cache.
            if (vehicleCache == null)
            {
                vehicleCache = new VehicleCache(db.GetSupportedVehicles().ToArray());
            }

            // get all the tiles and build the routerdb.
            var globalIdMap = db.ExtractGlobalIds();

            db.Network.GeometricGraph.Graph.MarkAsMulti(); // when loading data we need a multigraph.
            foreach (var tile in tileRange)
            {
                db.AddOsmTile(globalIdMap, tile);
            }

            // keep global ids if it's a requirement.
            if (keepGlobalIds)
            {
                db.AddOrUpdateGlobalIds(globalIdMap);
            }

            // sort the network.
            db.Sort();

            // optimize the network by applying simplifications.
            db.OptimizeNetwork();

            // compress the network.
            db.Compress();
        }
コード例 #3
0
        void OnEntityMounted(BaseMountable entity, BasePlayer player)
        {
            if (entity == null | player == null)
            {
                return;
            }

            if (!permission.UserHasPermission(player.UserIDString, perm))
            {
                return;
            }

            if (GetPlayer(player))
            {
                RemoveVehicleByPlayer(player);
            }

            if (onlyDriver)
            {
                if (!(entity.ShortPrefabName == "miniheliseat" | entity.ShortPrefabName == "standingdriver" | entity.ShortPrefabName == "smallboatdriver"))
                {
                    return;
                }
            }

            VehicleCache vehicle = new VehicleCache();

            vehicle.player = player;
            vehicle.entity = entity;
            vehicles.Add(vehicle);

            CreateUI(vehicle);
        }
コード例 #4
0
 public ExportVehicleInfo(VehicleCache vehicles, string fileName)
 {
     _vehicleCache = vehicles;
     //bucketSortVehicles(vehicles);
     //string file = Resources.Settings.TempFolder + DateTime.Now.ToFileTimeUtc().ToString() + ".xls";
     string currFileName = fileName;
     Workbook wb = new Workbook();
     createExcelFile(wb, currFileName);
 }
コード例 #5
0
ファイル: ShapeFileReader.cs プロジェクト: jerryfaust/routing
        /// <summary>
        /// Creates a new reader.
        /// </summary>
        public ShapefileReader(RouterDb routerDb, IList <ShapefileDataReader> shapefileReaders, Vehicle[] vehicles, string sourceVertexColumn, string targetVertexColumn)
        {
            _routerDb           = routerDb;
            _shapefileReaders   = shapefileReaders;
            _vehicles           = vehicles;
            _sourceVertexColumn = sourceVertexColumn;
            _targetVertexColumn = targetVertexColumn;

            _vehicleCache = new VehicleCache(vehicles);
        }
コード例 #6
0
        public static async Task <VehicleData> RequestVINAsync(string vin)
        {
            if (!VehicleCache.CheckCache(vin))
            {
                VINModel vinData = await VINController.GetVinFlatAsync(vin);

                VehicleData output = VINParser.ParseVINModel <VehicleData>(vinData.Results[0]);
                VehicleCache.Add(output);
                return(output);
            }
            else
            {
                return(VehicleCache.Get(vin));
            }
        }
コード例 #7
0
 private void bucketSortVehicles(VehicleCache vehicles)
 {
     foreach (var currVehicle in vehicles)
     {
         if (isSold(currVehicle))
         {
             updateSoldVehicleList(currVehicle, createDateKey(currVehicle, PropertyId.SaleDate));
         }
         if(isPurchased(currVehicle))
         {
             updatePurchasedVehicleList(currVehicle, createDateKey(currVehicle, PropertyId.PurchaseDate));
         }
     }
     //TODO: Sort Data structure; tough since the keys are strings
     return;
 }
コード例 #8
0
ファイル: ShapeFileReader.cs プロジェクト: lulzzz/geo
        /// <summary>
        /// Creates a new reader.
        /// </summary>
        public ShapefileReader(RouterDb routerDb, IList <ShapefileDataReader> shapefileReaders, Vehicle[] vehicles, string sourceVertexColumn, string targetVertexColumn)
        {
            _routerDb           = routerDb;
            _shapefileReaders   = shapefileReaders;
            _vehicles           = vehicles;
            _sourceVertexColumn = sourceVertexColumn;
            _targetVertexColumn = targetVertexColumn;

            _vehicleCache = new VehicleCache(vehicles);

            if (string.IsNullOrEmpty(_sourceVertexColumn) &&
                string.IsNullOrEmpty(_targetVertexColumn))
            { // check for these in the vehicle(s).
                foreach (var vehicle in vehicles)
                {
                    var profileSourceVertex = string.Empty;
                    var profileTargetVertex = string.Empty;

                    if (vehicle.Parameters != null &&
                        vehicle.Parameters.TryGetValue("source_vertex", out profileSourceVertex) &&
                        vehicle.Parameters.TryGetValue("target_vertex", out profileTargetVertex))
                    {
                        if (string.IsNullOrWhiteSpace(_sourceVertexColumn))
                        {
                            _sourceVertexColumn = profileSourceVertex;
                        }
                        else if (_sourceVertexColumn != profileSourceVertex)
                        {
                            throw new Exception(string.Format(
                                                    "Cannot configure shapefile reader: Multiple vehicle definitions but different source vertex column defined: {0} and {1} found.",
                                                    _sourceVertexColumn, profileSourceVertex));
                        }

                        if (string.IsNullOrWhiteSpace(_targetVertexColumn))
                        {
                            _targetVertexColumn = profileTargetVertex;
                        }
                        else if (_targetVertexColumn != profileTargetVertex)
                        {
                            throw new Exception(string.Format(
                                                    "Cannot configure shapefile reader: Multiple vehicle definitions but different target vertex column defined: {0} and {1} found.",
                                                    _targetVertexColumn, profileTargetVertex));
                        }
                    }
                }
            }
        }
コード例 #9
0
        public void CreateUI(VehicleCache vehicle)
        {
            var element = UIHelper.NewCuiElement("SHOWFUEL_UI", UIHelper.HexToRGBA(backgroundColor, backgroundTransparency), GetMinDock(), GetMaxDock());

            if (ImageLibrary == null || !useIcon)
            {
                UIHelper.CreatePanel(ref element, "SHOWFUEL_UI", UIHelper.HexToRGBA(backgroundColor, backgroundTransparency), "0.0 0.0", "1.0 1.0");
                UIHelper.CreateLabel(ref element, "SHOWFUEL_UI", "x" + vehicle.GetFuelAmount(), 14, "0.1 0.1", "0.9 0.9");
                CuiHelper.AddUi(vehicle.player, element);
            }
            else
            {
                string icon = GetImage(imageURL);
                UIHelper.CreatePanel(ref element, "SHOWFUEL_UI", UIHelper.HexToRGBA(backgroundColor, backgroundTransparency), "0.0 0.0", "1.0 1.0");
                UIHelper.LoadImage(ref element, "SHOWFUEL_UI", icon, "0.1 0.2", "0.7 0.8");
                UIHelper.CreateLabel(ref element, "SHOWFUEL_UI", "x" + vehicle.GetFuelAmount(), 11, "0.1 0.1", "0.9 0.4", TextAnchor.MiddleRight);
                CuiHelper.AddUi(vehicle.player, element);
            }
        }
コード例 #10
0
        /// <summary>
        /// Loads all OSM data in the given bounding box by using routable tiles.
        /// </summary>
        /// <param name="db">The routerdb to fill.</param>
        /// <param name="box">The bounding box to fetch tiles for.</param>
        /// <param name="keepGlobalIds">Flag to keep the global ids.</param>
        /// <param name="baseUrl">The base url of the routeable tile source.</param>
        /// <param name="vehicleCache">The vehicle cache to use.</param>
        public static void LoadOsmDataFromTiles(this RouterDb db, Box box, string baseUrl = TileParser.BaseUrl, bool keepGlobalIds = true, VehicleCache vehicleCache = null)
        {
            // build the tile range.
            var tileRange = new TileRange(box, Zoom);

            // build the vehicle cache.
            if (vehicleCache == null)
            {
                vehicleCache = new VehicleCache(db.GetSupportedVehicles().ToArray());
            }

            // get all the tiles and build the routerdb.
            var globalIdMap = db.ExtractGlobalIds();

            db.Network.GeometricGraph.Graph.MarkAsMulti(); // when loading data we need a multigraph.
            var tiles = tileRange.ToList();

            for (var t = 0; t < tiles.Count; t++)
            {
                var tile = tiles[t];

                Logger.Log(nameof(RouterDbExtensions), Logging.TraceEventType.Information,
                           $"Loading tile {t+1}/{tiles.Count}: {tile}({tile.LocalId})");
                db.AddOsmTile(globalIdMap, tile, vehicleCache, baseUrl);
            }

            // keep global ids if it's a requirement.
            if (keepGlobalIds)
            {
                db.AddOrUpdateGlobalIds(globalIdMap);
            }

            // sort the network.
            db.Sort();

            // optimize the network by applying simplifications.
            db.OptimizeNetwork();

            // compress the network.
            db.Compress();
        }
コード例 #11
0
        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            searchParam.Clear();

            string assignedTo = cmbAssignedTo.Text;
            if (!string.IsNullOrEmpty(assignedTo))
            {
                searchParam.Add(VehicleCacheTaskSearchKey.AssignedTo, assignedTo);
            }

            string category = cmbCategory.Text;
            if (!string.IsNullOrEmpty(category))
            {
                searchParam.Add(VehicleCacheTaskSearchKey.Category, category);
            }

            cache = new VehicleCache(Settings.VehiclePath, searchParam);

            UpdateUI();
            lblTotalCount.Content = cache.Count.ToString();
        }
コード例 #12
0
 public void UpdateUI(VehicleCache vehicle)
 {
     CuiHelper.DestroyUi(vehicle.player, "SHOWFUEL_UI");
     CreateUI(vehicle);
 }
コード例 #13
0
ファイル: CacheManager.cs プロジェクト: rogertoma/CarDepot
        public static void UpdateAllVehicleCache()
        {
            VehicleCache vehicleTemplCache = new VehicleCache(Settings.VehiclePath, new Dictionary<VehicleCacheSearchKey, string>(), true);
            _allVehicleCache = vehicleTemplCache;
            CustomerCache customerTempCache = new CustomerCache();
            _allCustomerCache = customerTempCache;

            _updateingCache = false;
        }
コード例 #14
0
 public void SetContent(VehicleCache vehicleCache)
 {
     cache = vehicleCache;
     InitializeList();
 }
コード例 #15
0
        /// <summary>
        /// Normalizes nothing but the access tags.
        /// </summary>
        public static void NormalizeAccess(this IAttributeCollection tags, VehicleCache vehicleCache, Vehicle vehicle, string highwayType, IAttributeCollection profileTags)
        {
            var access = vehicleCache.CanTraverse(new AttributeCollection(new Attribute("highway", highwayType)), vehicle, false);

            tags.NormalizeAccess(profileTags, access, vehicle.VehicleTypes);
        }
コード例 #16
0
ファイル: CacheManager.cs プロジェクト: rogertoma/CarDepot
 private static void LoadCache()
 {
     try
     {
         _userCache = new UserCache();
         _allVehicleCache = new VehicleCache(Settings.VehiclePath,
             new Dictionary<VehicleCacheSearchKey, string>());
         _allCustomerCache = new CustomerCache();
     }
     catch (Exception ex)
     {
         MessageBox.Show("ERROR: CacheManager: LoadCache\n" + ex.StackTrace);
     }
 }
コード例 #17
0
        /// <summary>
        /// Adds data from an individual tile.
        /// </summary>
        /// <param name="routerDb">The router db to fill.</param>
        /// <param name="globalIdMap">The global id map.</param>
        /// <param name="tile">The tile to load.</param>
        /// <param name="vehicleCache">The vehicle cache.</param>
        /// <param name="baseUrl">The base url of the routable tile source.</param>
        internal static bool AddOsmTile(this RouterDb routerDb, GlobalIdMap globalIdMap, Tile tile,
                                        VehicleCache vehicleCache = null, string baseUrl = BaseUrl)
        {
            var updated = false;

            try
            {
                var url    = baseUrl + $"/{tile.Zoom}/{tile.X}/{tile.Y}";
                var stream = DownloadFunc(url);
                if (stream == null)
                {
                    return(false);
                }

                var nodeLocations = new Dictionary <long, (Coordinate location, bool inTile)>();
                var waysData      = new Dictionary <long, (List <long> nodes, AttributeCollection attributes)>();
                var nodes         = new HashSet <long>();
                var coreNodes     = new HashSet <long>();
                using (var textReader = new StreamReader(stream))
                {
                    var json       = textReader.ReadToEnd();
                    var jsonObject = JObject.Parse(json);

                    if (!(jsonObject["@graph"] is JArray graph))
                    {
                        return(false);
                    }

                    foreach (var graphObject in graph)
                    {
                        if (!(graphObject["@id"] is JToken idToken))
                        {
                            continue;
                        }
                        var id = idToken.Value <string>();

                        if (id == null)
                        {
                            continue;
                        }

                        if (id.StartsWith("http://www.openstreetmap.org/node/"))
                        {
                            // parse as a node.
                            var nodeId = long.Parse(id.Substring("http://www.openstreetmap.org/node/".Length,
                                                                 id.Length - "http://www.openstreetmap.org/node/".Length));

                            if (!(graphObject["geo:long"] is JToken longToken))
                            {
                                continue;
                            }
                            var lon = longToken.Value <double>();
                            if (!(graphObject["geo:lat"] is JToken latToken))
                            {
                                continue;
                            }
                            var lat = latToken.Value <double>();

                            // determine if node is in tile or not.
                            var inTile = Tile.WorldToTile(lon, lat,
                                                          tile.Zoom).LocalId == tile.LocalId;
                            nodeLocations[nodeId] = (new Coordinate((float)lat, (float)lon),
                                                     inTile);
                        }
                        else if (id.StartsWith("http://www.openstreetmap.org/way/"))
                        {
                            // parse as a way.
                            var wayId = long.Parse(id.Substring("http://www.openstreetmap.org/way/".Length,
                                                                id.Length - "http://www.openstreetmap.org/way/".Length));

                            // interpret all tags with defined semantics.
                            var attributes = GetTags(graphObject, ReverseMappingLazy.Value);
                            attributes.AddOrReplace("way_id", wayId.ToInvariantString());
                            attributes.AddOrReplace("tile_x", tile.X.ToInvariantString());
                            attributes.AddOrReplace("tile_y", tile.Y.ToInvariantString());

                            // include all raw tags (if any).
                            if ((graphObject["osm:hasTag"] is JArray rawTags))
                            {
                                for (var n = 0; n < rawTags.Count; n++)
                                {
                                    var rawTag = rawTags[n];
                                    if (!(rawTag is JValue rawTagValue))
                                    {
                                        continue;
                                    }

                                    var keyValue      = rawTagValue.Value <string>();
                                    var keyValueSplit = keyValue.Split('=');
                                    if (keyValueSplit.Length != 2)
                                    {
                                        continue;
                                    }

                                    attributes.AddOrReplace(keyValueSplit[0], keyValueSplit[1]);
                                }
                            }

                            // parse nodes.
                            if (!(graphObject["osm:hasNodes"] is JArray wayNodes))
                            {
                                continue;
                            }

                            var nodeIds = new List <long>();
                            for (var n = 0; n < wayNodes.Count; n++)
                            {
                                var nodeToken    = wayNodes[n];
                                var nodeIdString = nodeToken.Value <string>();
                                var nodeId       = long.Parse(nodeIdString.Substring(
                                                                  "http://www.openstreetmap.org/node/".Length,
                                                                  nodeIdString.Length - "http://www.openstreetmap.org/node/".Length));
                                nodeIds.Add(nodeId);

                                if (n == 0 || n == wayNodes.Count - 1)
                                {
                                    // first and last nodes always core.
                                    coreNodes.Add(nodeId);
                                }
                                else if (nodes.Contains(nodeId))
                                {
                                    // second time this node was hit.
                                    coreNodes.Add(nodeId);
                                }

                                nodes.Add(nodeId);
                            }

                            waysData[wayId] = (nodeIds, attributes);
                        }
                        else if (id.StartsWith("http://www.openstreetmap.org/relation/"))
                        {
                            // parse as a relation.
                            // TODO: parse as a relation.
                        }
                    }

                    var shape = new List <Coordinate>();
                    foreach (var wayPairs in waysData)
                    {
                        // prepare for next way.
                        shape.Clear();
                        var previousVertex = Itinero.Constants.NO_VERTEX;

                        // get way data.
                        var wayNodes   = wayPairs.Value.nodes;
                        var attributes = wayPairs.Value.attributes;

                        // verify way data and spit out a warning if a way has <= 1 node.
                        if (wayNodes.Count <= 1)
                        {
                            Itinero.Logging.Logger.Log($"{nameof(TileParser)}.{nameof(AddOsmTile)}",
                                                       TraceEventType.Warning,
                                                       $"A way was detected with <= 1 nodes.");
                            continue;
                        }

                        // iterate over the way segments and add them as edges or part of the next edge.
                        for (var n = 0; n < wayNodes.Count - 1; n++)
                        {
                            var node1Id = wayNodes[n];
                            var node2Id = wayNodes[n + 1];

                            // get the nodes data.
                            if (!nodeLocations.TryGetValue(node1Id, out var node1Data))
                            {
                                Itinero.Logging.Logger.Log(nameof(TileParser), TraceEventType.Warning,
                                                           $"Could not load way {wayPairs.Key} in {tile}: node {node1Id} missing.");
                                break;
                            }

                            if (!nodeLocations.TryGetValue(node2Id, out var node2Data))
                            {
                                Itinero.Logging.Logger.Log(nameof(TileParser), TraceEventType.Warning,
                                                           $"Could not load way {wayPairs.Key} in {tile}: node {node2Id} missing.");
                                break;
                            }

                            // add attributes and move on if failed.
                            var(profile, meta) = AddProfileAndMeta(routerDb, vehicleCache, attributes);
                            if (profile == ushort.MaxValue)
                            {
                                continue;
                            }

                            // always add segments that cross tile boundaries.
                            // TODO: we can probably do better and add only one of the nodes as core but for now to keep complexity down we add both.
                            if (!node1Data.inTile || !node2Data.inTile)
                            {
                                coreNodes.Add(node1Id);
                                coreNodes.Add(node2Id);
                            }

                            // if node1 is core make sure to add it.
                            if (coreNodes.Contains(node1Id))
                            {
                                // add node1 as vertex but check if it already exists.
                                if (!globalIdMap.TryGet(node1Id, out var vertex))
                                {
                                    vertex = routerDb.Network.VertexCount;
                                    routerDb.Network.AddVertex(vertex, node1Data.location.Latitude,
                                                               node1Data.location.Longitude);
                                    globalIdMap.Set(node1Id, vertex);
                                    updated = true;
                                }

                                // check if this segment wasn't just opened the iteration before.
                                if (vertex != previousVertex)
                                {
                                    // close previous segment if any.
                                    if (previousVertex != Itinero.Constants.NO_VERTEX)
                                    {
                                        routerDb.Network.AddEdge(previousVertex, vertex,
                                                                 new Data.Network.Edges.EdgeData()
                                        {
                                            MetaId   = meta,
                                            Distance = Distance(routerDb, previousVertex, vertex, shape),
                                            Profile  = profile
                                        }, new ShapeEnumerable(shape));
                                        updated = true;
                                        shape.Clear();
                                    }

                                    // start a new segment if the end of this one is in tile.
                                    previousVertex = Itinero.Constants.NO_VERTEX;
                                    if (node1Data.inTile)
                                    {
                                        previousVertex = vertex;
                                    }
                                }
                            }

                            // if the second node is also core, close the segment.
                            if (coreNodes.Contains(node2Id))
                            {
                                // add node2 as vertex but check if it already exists.
                                if (!globalIdMap.TryGet(node2Id, out var vertex))
                                {
                                    vertex = routerDb.Network.VertexCount;
                                    routerDb.Network.AddVertex(vertex, node2Data.location.Latitude,
                                                               node2Data.location.Longitude);
                                    globalIdMap.Set(node2Id, vertex);
                                    updated = true;
                                }

                                // if this segment overlaps, always add it.
                                if (!node1Data.inTile || !node2Data.inTile)
                                {
                                    if (!globalIdMap.TryGet(node1Id, out previousVertex))
                                    {
                                        throw new Exception(
                                                  "Cannot add segment overlapping tile boundary, node should have already been added.");
                                    }
                                    routerDb.Network.AddEdge(previousVertex, vertex, new Data.Network.Edges.EdgeData()
                                    {
                                        MetaId   = meta,
                                        Distance = Distance(routerDb, previousVertex, vertex, shape),
                                        Profile  = profile
                                    }, new ShapeEnumerable(shape));
                                    updated = true;
                                    shape.Clear();
                                }
                                else
                                {
                                    // close previous segment if any.
                                    if (previousVertex != Itinero.Constants.NO_VERTEX)
                                    {
                                        routerDb.Network.AddEdge(previousVertex, vertex,
                                                                 new Data.Network.Edges.EdgeData()
                                        {
                                            MetaId   = meta,
                                            Distance = Distance(routerDb, previousVertex, vertex, shape),
                                            Profile  = profile
                                        }, new ShapeEnumerable(shape));
                                        updated = true;
                                        shape.Clear();
                                    }
                                }

                                // start a new segment if the end of this one is in tile.
                                previousVertex = Itinero.Constants.NO_VERTEX;
                                if (node2Data.inTile)
                                {
                                    previousVertex = vertex;
                                }
                            }
                            else
                            {
                                // add as shape point if there is an active segment.
                                if (previousVertex != Itinero.Constants.NO_VERTEX)
                                {
                                    shape.Add(node2Data.location);
                                }
                            }
                        }
                    }

                    return(updated);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return(updated);
            }
        }
コード例 #18
0
        private static (ushort profile, uint meta) AddProfileAndMeta(RouterDb routerDb, VehicleCache vehicleCache, AttributeCollection attributes)
        {
            // add the edge if the attributes are of use to the vehicles defined.
            var wayAttributes    = attributes;
            var profileWhiteList = new Whitelist();

            if (!vehicleCache.AddToWhiteList(wayAttributes, profileWhiteList))
            {
                return(ushort.MaxValue, uint.MaxValue);
            }

            // way has some use.
            // build profile and meta-data.
            var profileTags = new AttributeCollection();
            var metaTags    = new AttributeCollection();

            foreach (var tag in wayAttributes)
            {
                if (profileWhiteList.Contains(tag.Key))
                {
                    profileTags.AddOrReplace(tag);
                }
                else if (vehicleCache.Vehicles.IsOnProfileWhiteList(tag.Key))
                {
                    metaTags.AddOrReplace(tag);
                }
                else if (vehicleCache.Vehicles.IsOnMetaWhiteList(tag.Key))
                {
                    metaTags.AddOrReplace(tag);
                }
            }

            if (!vehicleCache.AnyCanTraverse(profileTags))
            {
                // way has no use of any profile.
                return(ushort.MaxValue, uint.MaxValue);
            }

            // get profile and meta-data id's.
            var profileCount = routerDb.EdgeProfiles.Count;
            var profile      = routerDb.EdgeProfiles.Add(profileTags);

            if (profileCount != routerDb.EdgeProfiles.Count)
            {
                var stringBuilder = new StringBuilder();
                foreach (var att in profileTags)
                {
                    stringBuilder.Append(att.Key);
                    stringBuilder.Append('=');
                    stringBuilder.Append(att.Value);
                    stringBuilder.Append(' ');
                }

                Logger.Log(nameof(TileParser), Logging.TraceEventType.Information,
                           "Normalized: # profiles {0}: {1}", routerDb.EdgeProfiles.Count,
                           stringBuilder.ToInvariantString());
            }

            if (profile > Data.Edges.EdgeDataSerializer.MAX_PROFILE_COUNT)
            {
                throw new Exception(
                          "Maximum supported profiles exceeded, make sure only routing tags are included in the profiles.");
            }

            var meta = routerDb.EdgeMeta.Add(metaTags);

            return((ushort)profile, meta);
        }
コード例 #19
0
        public void LoadPanel(IAdminObject item)
        {
            var customer = item as CustomerAdminObject;
            if (customer == null)
            {
                return;
            }

            _customer = customer;

            LoadAllChildren(ContactCardGrid, item);

            addtionalContentControl.ListChanged += addtionalContentControl_ListChanged;

            Dictionary<VehicleCacheSearchKey, string> searchParam = new Dictionary<VehicleCacheSearchKey, string>();
            searchParam.Add(VehicleCacheSearchKey.CustomerId, item.GetValue(PropertyId.Id));

            VehicleCache cache = new VehicleCache(Settings.VehiclePath, searchParam);
            LstCustomerVehicles.SetContent(cache);
        }
コード例 #20
0
        private void BtnSearch_Click(object sender, RoutedEventArgs e)
        {
            LstSearchResults.Clear();

            Dictionary<VehicleCacheSearchKey, string> searchParam = new Dictionary<VehicleCacheSearchKey, string>();
            searchParam.Add(VehicleCacheSearchKey.FromDate, dpFrom.SelectedDate.ToString());
            searchParam.Add(VehicleCacheSearchKey.ToDate, dpTo.SelectedDate.ToString());
            if (!string.IsNullOrEmpty(txtVinSearch.Text))
            {
                searchParam.Add(VehicleCacheSearchKey.VinNumber, txtVinSearch.Text);
            }

            if (!string.IsNullOrEmpty(txtYearSearch.Text))
            {
                searchParam.Add(VehicleCacheSearchKey.Year, txtYearSearch.Text);
            }

            if (!string.IsNullOrEmpty(txtMakeSearch.Text))
            {
                searchParam.Add(VehicleCacheSearchKey.Make, txtMakeSearch.Text);
            }

            if (!string.IsNullOrEmpty(txtModelSearch.Text))
            {
                searchParam.Add(VehicleCacheSearchKey.Model, txtModelSearch.Text);
            }

            if (cbSold.IsChecked == true)
            {
                searchParam.Add(VehicleCacheSearchKey.IsSold, null);
            }

            if (cbWasAvailable.IsChecked == true)
            {
                searchParam.Add(VehicleCacheSearchKey.WasAvailable, null);
            }

            if (cbAvailable.IsChecked == true)
            {
                searchParam.Add(VehicleCacheSearchKey.IsAvailable, null);
            }

            if (cbWasPurchased.IsChecked == true)
            {
                searchParam.Add(VehicleCacheSearchKey.WasPurchased, null);
            }

            if (cbSoldNotDelivered.IsChecked == true)
            {
                searchParam.Add(VehicleCacheSearchKey.IncludeSoldNotDelivered, null);
            }

            cache = new VehicleCache(Settings.VehiclePath, searchParam);
            LstSearchResults.SetContent(cache);
            lblTotalCount.Content = cache.Count.ToString();
        }
コード例 #21
0
        /// <summary>
        /// Adds data from an individual tile.
        /// </summary>
        /// <param name="routerDb">The router db to fill.</param>
        /// <param name="globalIdMap">The global id map.</param>
        /// <param name="tile">The tile to load.</param>
        internal static void AddOsmTile(this RouterDb routerDb, GlobalIdMap globalIdMap, Tile tile,
                                        VehicleCache vehicleCache = null)
        {
            var url    = BaseUrl + $"/{tile.Zoom}/{tile.X}/{tile.Y}";
            var stream = Download.DownloadHelper.Download(url);

            if (stream == null)
            {
                return;
            }

            Logger.Log(nameof(TileParser), Logging.TraceEventType.Information,
                       $"Loading tile: {tile}");

            // build the vehicle cache.
            if (vehicleCache == null)
            {
                vehicleCache = new VehicleCache(routerDb.GetSupportedVehicles().ToArray());
            }

            var nodeLocations = new Dictionary <long, Coordinate>();

            using (var textReader = new StreamReader(stream))
            {
                var jsonObject = JObject.Parse(textReader.ReadToEnd());

                if (!(jsonObject["@graph"] is JArray graph))
                {
                    return;
                }

                foreach (var graphObject in graph)
                {
                    if (!(graphObject["@id"] is JToken idToken))
                    {
                        continue;
                    }
                    var id = idToken.Value <string>();

                    if (id == null)
                    {
                        continue;
                    }

                    if (id.StartsWith("http://www.openstreetmap.org/node/"))
                    {
                        var nodeId = long.Parse(id.Substring("http://www.openstreetmap.org/node/".Length,
                                                             id.Length - "http://www.openstreetmap.org/node/".Length));

                        if (globalIdMap.TryGet(nodeId, out var vertexId))
                        {
                            continue;
                        }

                        if (!(graphObject["geo:long"] is JToken longToken))
                        {
                            continue;
                        }
                        var lon = longToken.Value <double>();
                        if (!(graphObject["geo:lat"] is JToken latToken))
                        {
                            continue;
                        }
                        var lat = latToken.Value <double>();

                        nodeLocations[nodeId] = new Coordinate((float)lat, (float)lon);
                    }
                    else if (id.StartsWith("http://www.openstreetmap.org/way/"))
                    {
                        var attributes = new AttributeCollection();
                        foreach (var child in graphObject.Children())
                        {
                            if (!(child is JProperty property))
                            {
                                continue;
                            }

                            if (property.Name == "@id" ||
                                property.Name == "osm:nodes" ||
                                property.Name == "@type")
                            {
                                continue;
                            }

                            if (property.Name == "rdfs:label")
                            {
                                attributes.AddOrReplace("name", property.Value.Value <string>());
                                continue;
                            }

                            var key = property.Name;
                            if (key.StartsWith("osm:"))
                            {
                                key = key.Substring(4, key.Length - 4);
                            }

                            var value = property.Value.Value <string>();
                            if (value.StartsWith("osm:"))
                            {
                                value = value.Substring(4, value.Length - 4);
                            }

                            attributes.AddOrReplace(key, value);
                        }

                        // add the edge if the attributes are of use to the vehicles defined.
                        var wayAttributes    = attributes;
                        var profileWhiteList = new Whitelist();
                        if (!vehicleCache.AddToWhiteList(wayAttributes, profileWhiteList))
                        {
                            continue;
                        }

                        // way has some use.
                        // build profile and meta-data.
                        var profileTags = new AttributeCollection();
                        var metaTags    = new AttributeCollection();
                        foreach (var tag in wayAttributes)
                        {
                            if (profileWhiteList.Contains(tag.Key))
                            {
                                profileTags.AddOrReplace(tag);
                            }
                            else if (vehicleCache.Vehicles.IsOnProfileWhiteList(tag.Key))
                            {
                                metaTags.AddOrReplace(tag);
                            }
                            else if (vehicleCache.Vehicles.IsOnMetaWhiteList(tag.Key))
                            {
                                metaTags.AddOrReplace(tag);
                            }
                        }

                        if (!vehicleCache.AnyCanTraverse(profileTags))
                        {
                            // way has some use, add all of it's nodes to the index.
                            continue;
                        }

                        // get profile and meta-data id's.
                        var profileCount = routerDb.EdgeProfiles.Count;
                        var profile      = routerDb.EdgeProfiles.Add(profileTags);
                        if (profileCount != routerDb.EdgeProfiles.Count)
                        {
                            var stringBuilder = new StringBuilder();
                            foreach (var att in profileTags)
                            {
                                stringBuilder.Append(att.Key);
                                stringBuilder.Append('=');
                                stringBuilder.Append(att.Value);
                                stringBuilder.Append(' ');
                            }

                            Logger.Log(nameof(TileParser), Logging.TraceEventType.Information,
                                       "Normalized: # profiles {0}: {1}", routerDb.EdgeProfiles.Count,
                                       stringBuilder.ToInvariantString());
                        }

                        if (profile > Data.Edges.EdgeDataSerializer.MAX_PROFILE_COUNT)
                        {
                            throw new Exception(
                                      "Maximum supported profiles exceeded, make sure only routing tags are included in the profiles.");
                        }
                        var meta = routerDb.EdgeMeta.Add(metaTags);

                        if (!(graphObject["osm:nodes"] is JArray nodes))
                        {
                            continue;
                        }

                        // add first as vertex.
                        var node = nodes[0];
                        if (!(node is JToken nodeToken))
                        {
                            continue;
                        }
                        var nodeIdString = nodeToken.Value <string>();
                        var nodeId       = long.Parse(nodeIdString.Substring("http://www.openstreetmap.org/node/".Length,
                                                                             nodeIdString.Length - "http://www.openstreetmap.org/node/".Length));
                        if (!globalIdMap.TryGet(nodeId, out var previousVertex))
                        {
                            if (!nodeLocations.TryGetValue(nodeId, out var nodeLocation))
                            {
                                throw new Exception($"Could not load tile {tile}: node {nodeId} missing.");
                            }
                            previousVertex = routerDb.Network.VertexCount;
                            routerDb.Network.AddVertex(previousVertex, nodeLocation.Latitude, nodeLocation.Longitude);
                            globalIdMap.Set(nodeId, previousVertex);
                        }

                        // add last as vertex.
                        node      = nodes[nodes.Count - 1];
                        nodeToken = (node as JToken);
                        if (nodeToken == null)
                        {
                            continue;
                        }
                        nodeIdString = nodeToken.Value <string>();
                        nodeId       = long.Parse(nodeIdString.Substring("http://www.openstreetmap.org/node/".Length,
                                                                         nodeIdString.Length - "http://www.openstreetmap.org/node/".Length));
                        if (!globalIdMap.TryGet(nodeId, out var vertexId))
                        {
                            if (!nodeLocations.TryGetValue(nodeId, out var nodeLocation))
                            {
                                throw new Exception($"Could not load tile {tile}: node {nodeId} missing.");
                            }
                            vertexId = routerDb.Network.VertexCount;
                            routerDb.Network.AddVertex(vertexId, nodeLocation.Latitude, nodeLocation.Longitude);
                            globalIdMap.Set(nodeId, vertexId);
                        }

                        var shape = new List <Coordinate>();
                        for (var n = 1; n < nodes.Count; n++)
                        {
                            node      = nodes[n];
                            nodeToken = node as JToken;
                            if (node == null)
                            {
                                continue;
                            }
                            nodeIdString = nodeToken.Value <string>();
                            nodeId       = long.Parse(nodeIdString.Substring("http://www.openstreetmap.org/node/".Length,
                                                                             nodeIdString.Length - "http://www.openstreetmap.org/node/".Length));

                            if (globalIdMap.TryGet(nodeId, out vertexId))
                            {
                                shape.Insert(0, routerDb.Network.GetVertex(previousVertex));
                                shape.Add(routerDb.Network.GetVertex(vertexId));
                                var distance = Itinero.LocalGeo.Coordinate.DistanceEstimateInMeter(shape);
                                if (distance > Itinero.Constants.DefaultMaxEdgeDistance)
                                {
                                    distance = Itinero.Constants.DefaultMaxEdgeDistance;
                                }

                                shape.RemoveAt(0);
                                shape.RemoveAt(shape.Count - 1);
                                routerDb.Network.AddEdge(previousVertex, vertexId, new Data.Network.Edges.EdgeData()
                                {
                                    MetaId   = meta,
                                    Distance = distance,
                                    Profile  = (ushort)profile
                                }, new ShapeEnumerable(shape));
                                shape.Clear();

                                previousVertex = vertexId;
                            }
                            else
                            {
                                if (!nodeLocations.TryGetValue(nodeId, out var nodeLocation))
                                {
                                    throw new Exception($"Could not load tile {tile}: node {nodeId} missing.");
                                }
                                shape.Add(nodeLocation);
                            }
                        }
                    }
                }
            }
        }
コード例 #22
0
        /// <summary>
        /// Splits the given tags into a normalized version, profile tags, and the rest in metatags.
        /// </summary>
        public static bool Normalize(IAttributeCollection tags, IAttributeCollection profileTags, VehicleCache vehicleCache)
        {
            if (tags == null || profileTags == null || vehicleCache == null)
            {
                return(false);
            }

            var normalizedTags = new HashSet <string>(new string[] { "highway", "maxspeed", "oneway", "oneway:bicycle",
                                                                     "cycleway", "junction", "access" });

            foreach (var vehicle in vehicleCache.Vehicles)
            {
                foreach (var vehicleType in vehicle.VehicleTypes)
                {
                    normalizedTags.Add(vehicleType);
                }
            }

            string highway;

            if (!tags.TryGetValue("highway", out highway))
            { // there is no highway tag, don't continue the search.
                return(false);
            }

            // add the highway tag.
            profileTags.AddOrReplace("highway", highway);

            // normalize maxspeed tags.
            tags.NormalizeMaxspeed(profileTags);

            // normalize oneway tags.
            tags.NormalizeOneway(profileTags);
            tags.NormalizeOnewayBicycle(profileTags);

            // normalize cyclceway.
            tags.NormalizeCycleway(profileTags);

            // normalize junction=roundabout tag.
            tags.NormalizeJunction(profileTags);

            // normalize access tags.
            foreach (var vehicle in vehicleCache.Vehicles)
            {
                tags.NormalizeAccess(vehicleCache, vehicle, highway, profileTags);
            }

            // add whitelisted tags but only when they haven't been considered for normalization.
            foreach (var vehicle in vehicleCache.Vehicles)
            {
                foreach (var key in vehicle.ProfileWhiteList)
                {
                    var value = string.Empty;
                    if (tags.TryGetValue(key, out value))
                    {
                        if (!normalizedTags.Contains(key))
                        {
                            profileTags.AddOrReplace(key, value);
                        }
                    }
                }
            }

            return(true);
        }
コード例 #23
0
        private void btnRefresh_Click(object sender, RoutedEventArgs e)
        {
            LstSearchResults.Clear();

            Dictionary<VehicleCacheSearchKey, string> searchParam = new Dictionary<VehicleCacheSearchKey, string>();
            searchParam.Add(VehicleCacheSearchKey.IsCheckedOut, null);

            _cache = new VehicleCache(Settings.VehiclePath, searchParam);
            LstSearchResults.SetContent(_cache);
        }