Пример #1
0
        long WriteRelationCache(OsmRelation osmRelation, OsmWay[] osmWays, OsmNode[] osmNodes)
        {
            long relationIndex = cacheData.Length;

            int p   = sizeof(int); // cacheblock-size
            var buf = cacheBuffer;

            p += osmRelation.WriteBinary(buf, p);
            p += ProtoBuf.WriteVarInt(buf, p, (ulong)osmWays.Length);
            var tmpWays = osmWays.ToArray();

            EncodeDelta(tmpWays);
            foreach (var way in tmpWays)
            {
                p += way.WriteBinary(buf, p);
            }
            p += ProtoBuf.WriteVarInt(buf, p, (ulong)osmNodes.Length);
            var tmpNodes = osmNodes.ToArray();

            EncodeDelta(tmpNodes);
            foreach (var node in tmpNodes)
            {
                p += node.WriteBinary(buf, p);
            }
            buf[0] = (byte)p;
            buf[1] = (byte)(p >> 8);
            buf[2] = (byte)(p >> 16);
            buf[3] = (byte)(p >> 24);

            cacheData.Position = relationIndex;
            cacheData.Write(buf, 0, p);
            return(relationIndex);
        }
Пример #2
0
 public abstract void RenderOsmObject(
     MapMakerSettings mapMakerSettings,
     MapDataAnalysis analysis,
     InMemoryOsmDatabase osmDatabase,
     OsmObjectBase osmObject,
     OsmRelation parentRelation,
     CGpsMapperMapWriter mapWriter);
Пример #3
0
        private bool ProcessNode(OsmNode node, OsmRelation relation)
        {
            // ignore untagged nodes (but not if they are part of a relation)
            if (false == node.IsTagged && relation == null)
            {
                return(false);
            }

            int layer = GetOsmObjectLayerNumber(node);

            if (currentRule.IsMatch(relation, node))
            {
                // if we are just running the first run on the rule engine
                // to detect levels and types that are used in the mapWriter
                if (justDetectLevelsAndTypesUsed)
                {
                    currentRule.MarkHardwareLevelsUsed(analysis);
                    currentRule.Template.RegisterType(currentRule.RuleName, mapMakerSettings.TypesRegistry, false);
                    return(true);
                }

                AddRenderElementCommandForNode(node, relation, layer, currentRule);
            }

            return(false);
        }
Пример #4
0
        private void AddRenderElementCommandForWay(
            OsmWay way,
            OsmRelation parentRelation,
            int elementLayer,
            RenderingRule renderingRule,
            bool isRelationsWay)
        {
            // ignore ways which are inner ways of a multipolygon relation
            if (false == multipolygonRelationsProcessor.IsWayUsedAsInnerPolygon(way.ObjectId))
            {
                // check if this way represents an outer way of multipolygon
                if (multipolygonRelationsProcessor.IsWayUsedAsOuterPolygon(way.ObjectId))
                {
                    // find all areas with holes object and apply the templates to them
                    foreach (OsmAreaWithHoles areaWithHoles in multipolygonRelationsProcessor.ListAreasWithHolesForSpecificWay(way.ObjectId))
                    {
                        ApplyTemplate(isRelationsWay, renderingRule, areaWithHoles, parentRelation);
                    }
                }
                // otherwise just apply the templates to the way
                else
                {
                    ApplyTemplate(isRelationsWay, renderingRule, way, parentRelation);
                }

                mapMakerSettings.MapContentStatistics.IncrementFeaturesCount(renderingRule.RuleName);
            }
        }
    /// <summary>
    /// Extract the relation information from the XML file and generates the corresponding
    /// instances.
    /// </summary>
    /// <param name="xmlNodeList">XML node</param>
    void GetRelations(XmlNodeList xmlNodeList)
    {
        foreach (XmlNode node in xmlNodeList)
        {
            OsmRelation relation = new OsmRelation(node);

            if (relation.Route == true)
            {
                relations.Add(relation);

                if (UserPreferences.PublicTransportRailways || UserPreferences.PublicTransportStreets)
                {
                    TagPublicTransportWays(relation);
                }

                if (UserPreferences.Stations)
                {
                    foreach (ulong NodeID in relation.StoppingNodeIDs)
                    {
                        try
                        {
                            nodes[NodeID].TransportLines.Add(relation.Name);
                            relation.StationNames.Add(nodes[NodeID].StationName);
                        }
                        catch (KeyNotFoundException)
                        {
                            continue;
                        }
                    }
                }
            }
        }
    }
Пример #6
0
 private void ApplyTemplate(
     bool isRelationsWay,
     RenderingRule renderingRule,
     OsmObjectBase osmObject,
     OsmRelation parentRelation)
 {
     renderingRule.Template.RenderOsmObject(mapMakerSettings, analysis, osmDataSource.OsmDatabase, osmObject, parentRelation, mapWriter);
 }
Пример #7
0
 private void AddRenderElementCommandForNode(
     OsmNode node,
     OsmRelation parentRelation,
     int elementLayer,
     RenderingRule renderingRule)
 {
     renderingRule.Template.RenderOsmObject(mapMakerSettings, analysis, osmDataSource.OsmDatabase, node, parentRelation, mapWriter);
     mapMakerSettings.MapContentStatistics.IncrementFeaturesCount(renderingRule.RuleName);
 }
        private void RelationRead(OsmRelation relation)
        {
            relationCount++;

            if (relationCount % 100 == 0)
            {
                UpdateStatus();
            }
        }
Пример #9
0
        public virtual bool IsMatch(OsmRelation parentRelation, OsmObjectBase osmElement)
        {
            if (selector == null)
            {
                return(true);
            }

            return(selector.IsMatch(parentRelation, osmElement));
        }
Пример #10
0
        public OsmObjectMother AddRelation()
        {
            OsmRelation relation = new OsmRelation(idCounter++);

            osmDatabase.AddRelation(relation);

            currentObject   = relation;
            currentRelation = relation;
            return(this);
        }
Пример #11
0
        private static void WriteRelation(XmlWriter writer, OsmRelation osmRelation)
        {
            writer.WriteStartElement(Constants.Constants.osmRelation);

            writer.WriteAttributeString(Constants.Constants.IdString, osmRelation.Id.ToString(CultureInfo.InvariantCulture));

            WriteMembers(writer, osmRelation.Members);
            WriteTags(writer, osmRelation.Tags);

            writer.WriteEndElement();
        }
    /// <summary>
    /// If public transport roads and railroads are activated in the options menu,
    /// this function will extract the last data informations from these nodes.
    /// </summary>
    /// <param name="r">XML node</param>
    void TagPublicTransportWays(OsmRelation r)
    {
        foreach (ulong WayID in r.WayIDs)
        {
            try
            {
                switch (r.TransportType)
                {
                case "subway":
                    ways[WayID].TransportLines.Add(r.Name);
                    ways[WayID].PublicTransportRailway = true;
                    ways[WayID].TransportTypes.Add("subway");
                    break;

                case "tram":
                    ways[WayID].TransportLines.Add(r.Name);
                    ways[WayID].PublicTransportRailway = true;
                    ways[WayID].TransportTypes.Add("tram");
                    break;

                case "train":
                    ways[WayID].TransportLines.Add(r.Name);
                    ways[WayID].PublicTransportRailway = true;
                    ways[WayID].TransportTypes.Add("train");
                    break;

                case "railway":
                    ways[WayID].TransportLines.Add(r.Name);
                    ways[WayID].PublicTransportRailway = true;
                    ways[WayID].TransportTypes.Add("railway");
                    break;

                case "light_rail":
                    ways[WayID].TransportLines.Add(r.Name);
                    ways[WayID].PublicTransportRailway = true;
                    ways[WayID].TransportTypes.Add("light_rail");
                    break;

                case "bus":
                    ways[WayID].TransportLines.Add(r.Name);
                    ways[WayID].PublicTransportStreet = true;
                    ways[WayID].TransportTypes.Add("bus");
                    break;
                }
            }
            catch (KeyNotFoundException)
            {
                continue;
            }
        }
    }
Пример #13
0
        private bool ProcessWay(
            OsmWay way,
            OsmRelation relation)
        {
            // ignore untagged ways (but not if they are part of a relation)
            if (false == way.IsTagged && relation == null)
            {
                return(false);
            }

            // ignore ways with less than 2 nodes
            if (way.NodesCount < 2)
            {
                return(false);
            }

            // ignore ways if they are designated as areas
            if (areaSelector.IsMatch(null, way))
            {
                return(false);
            }

            // ignore ways which are part of the multipolygon relation
            if (multipolygonRelationsProcessor.IsWayUsedAsOuterPolygon(way.ObjectId) ||
                multipolygonRelationsProcessor.IsWayUsedAsInnerPolygon(way.ObjectId))
            {
                return(false);
            }

            int layer = GetOsmObjectLayerNumber(way);

            if (currentRule.IsMatch(relation, way))
            {
                consumedWays.Add(way.ObjectId);

                // if we are just running the first run on the rule engine
                // to detect levels and types that are used in the mapWriter
                if (justDetectLevelsAndTypesUsed)
                {
                    currentRule.MarkHardwareLevelsUsed(analysis);
                    currentRule.Template.RegisterType(currentRule.RuleName, mapMakerSettings.TypesRegistry, false);
                    return(true);
                }

                AddRenderElementCommandForWay(way, relation, layer, currentRule, false);
            }

            return(false);
        }
Пример #14
0
    void GetRelation(XmlNodeList xmlNodeList)
    {
        foreach (XmlNode node in xmlNodeList)
        {
            OsmRelation rel = new OsmRelation(node);
            relations.Add(rel);

            if (rel.type == "multipolygon")
            {
                OsmWay item = ways.Find(x => x.ID == rel.members[0].nodeID);
                item.Height     = rel.Height;
                item.isBuilding = true;
                item.name       = rel.name;
            }
        }
    }
Пример #15
0
        public bool ReadRelation(long relationID, out OsmRelation osmRelation, out OsmWay[] osmWays, out OsmNode[] osmNodes)
        {
            long relationIndex = GetRelationIndex(relationID);

            if (relationIndex > 0) // cache found?
            {
                osmRelation = GetRelationData(relationIndex, out osmWays, out osmNodes);
                return(true);
            }

            ReadRelationDirect(relationID, out osmRelation, out osmWays, out osmNodes);

            relationIndex = WriteRelationCache(osmRelation, osmWays, osmNodes);
            WriteIndex(MemberType.Relation, relationID, relationIndex);

            return(osmRelation.id != 0);
        }
Пример #16
0
        private bool ProcessArea(
            OsmWay area,
            OsmRelation relation,
            RenderingRule rule,
            bool justDetectLevelsAndTypesUsed,
            HashSet <long> consumedAreas)
        {
            // ignore untagged ways (but not if they are part of a relation)
            if (false == area.IsTagged && relation == null)
            {
                return(false);
            }

            // ignore ways with less than 3 nodes
            if (area.NodesCount < 3)
            {
                return(false);
            }

            // ignore ways if they are neither designated as areas nor closed
            if (false == area.IsClosed && false == areaSelector.IsMatch(null, area))
            {
                return(false);
            }

            int layer = GetOsmObjectLayerNumber(area);

            if (rule.IsMatch(relation, area))
            {
                consumedAreas.Add(area.ObjectId);

                // if we are just running the first run on the rule engine
                // to detect levels and types that are used in the mapWriter
                if (justDetectLevelsAndTypesUsed)
                {
                    rule.MarkHardwareLevelsUsed(analysis);
                    rule.Template.RegisterType(rule.RuleName, mapMakerSettings.TypesRegistry, false);
                    return(true);
                }

                AddRenderElementCommandForWay(area, relation, layer, rule, false);
            }

            return(false);
        }
Пример #17
0
        public bool ReadRelationDirect(long relationID, out OsmRelation osmRelation, out OsmWay[] osmWays, out OsmNode[] osmNodes)
        {
            var rels = pbfReader.ReadRelations(relationID);

            if (rels.Length == 0)
            {
                osmRelation = default(OsmRelation);
                osmWays     = new OsmWay[0];
                osmNodes    = new OsmNode[0];
                return(false);
            }

            osmRelation = rels.First();

            osmWays = pbfReader.ReadWays(osmRelation.members.Where(x => x.type == MemberType.Way).Select(x => x.id).ToArray());
            Array.Sort(osmWays, (x, y) => x.id.CompareTo(y.id));
            int wayCount = 1;

            for (int i = 1; i < osmWays.Length; i++)
            {
                if (osmWays[i - 1].id == osmWays[i].id)
                {
                    continue;
                }
                osmWays[wayCount++] = osmWays[i];
            }
            Array.Resize(ref osmWays, wayCount);

            osmNodes = pbfReader.ReadNodes(osmWays.SelectMany(x => x.nodeIds).Concat(osmRelation.members.Where(x => x.type == MemberType.Node).Select(x => x.id)).ToArray());
            Array.Sort(osmNodes, (x, y) => x.id.CompareTo(y.id));
            int nodeCount = 1;

            for (int i = 1; i < osmNodes.Length; i++)
            {
                if (osmNodes[i - 1].id == osmNodes[i].id)
                {
                    continue;
                }
                osmNodes[nodeCount++] = osmNodes[i];
            }
            Array.Resize(ref osmNodes, nodeCount);

            return(true);
        }
        public void Add(OsmRelation relation, int typeId, IReadOnlyList <RelationItemInfo> itemInfos, BoundingRect rect)
        {
            if (relation == null)
            {
                throw new ArgumentNullException(nameof(relation));
            }
            if (itemInfos == null)
            {
                throw new ArgumentNullException(nameof(itemInfos));
            }
            if (rect == null)
            {
                throw new ArgumentNullException(nameof(rect));
            }

            startPositions.Add(new RelationLocation
            {
                Id     = relation.Id,
                Offset = stream.Position
            });

            idWriter.WriteIncrementOnly((ulong)relation.Id);
            writer.Write7BitEncodedInt((ulong)typeId);

            rect.WriteTo(writer);

            writer.Write7BitEncodedInt((ulong)relation.Items.Count);

            memberIdWriter.Reset();
            memberMidLatWriter.Reset();
            memberMidLonWriter.Reset();

            for (var index = 0; index < relation.Items.Count; index++)
            {
                var member = relation.Items[index];
                writer.Write((byte)member.MemberType);
                memberIdWriter.WriteZigZag(member.Id);
                writer.Write7BitEncodedInt(GetRoleId(member.Role));

                var info = itemInfos[index];
                memberMidLatWriter.WriteZigZag(info.MidLat);
                memberMidLonWriter.WriteZigZag(info.MidLon);
            }
        }
Пример #19
0
        /// <summary>
        /// Extracts all Relations of type "street" from OSM API Response XML
        /// </summary>
        private static List <OsmRelation> ExtractStreetRelations(XDocument xmlData)
        {
            Debug.Assert(xmlData.Root != null, "xmlData.Root == null");

            var osmStreetRelations = new List <OsmRelation>();

            foreach (var relationElement in xmlData.Root.Descendants(Constants.OsmXml.Tags.Relation))
            {
                // filter by tags
                var relationTags = relationElement.Elements(Constants.OsmXml.Tags.Tag).ToArray();
                if (!relationTags.Any(t =>
                                      t.Attribute(Constants.OsmXml.Attributes.K).Value == Constants.OsmXml.Values.Type &&
                                      t.Attribute(Constants.OsmXml.Attributes.V).Value == Constants.OsmXml.Values.Street))
                {
                    continue;
                }

                // create Relation
                var osmRelation = new OsmRelation
                {
                    Id        = Convert.ToInt64(relationElement.Attribute(Constants.OsmXml.Attributes.Id).Value),
                    MemberIds = new SortedSet <long>(),
                    Tags      = new Dictionary <string, string>()
                };
                // populate members of a Relation
                foreach (var memberElement in relationElement.Elements(Constants.OsmXml.Tags.Member))
                {
                    if (memberElement.Attribute(Constants.OsmXml.Attributes.Role).Value == Constants.OsmXml.Values.House)
                    {
                        osmRelation.MemberIds.Add(
                            Convert.ToInt64(memberElement.Attribute(Constants.OsmXml.Attributes.Ref).Value));
                    }
                }
                // populate tags
                foreach (var tagElement in relationTags)
                {
                    osmRelation.Tags.Add(tagElement.Attribute(Constants.OsmXml.Attributes.K).Value,
                                         tagElement.Attribute(Constants.OsmXml.Attributes.V).Value);
                }

                osmStreetRelations.Add(osmRelation);
            }
            return(osmStreetRelations);
        }
        private void ReadRelation(XElement el)
        {
            long     id        = el.GetAttributeLong("id");
            double   lat       = el.GetAttributeDouble("lat");
            double   lon       = el.GetAttributeDouble("lon");
            int      version   = el.GetAttributeInt("version");
            DateTime timestamp = el.GetAttributeDateTime("timestamp", DateTime.MinValue);
            int      changeset = el.GetAttributeInt("changeset");

            Dictionary <string, string> tags    = new Dictionary <string, string>();
            List <OsmMember>            members = new List <OsmMember>();

            foreach (var element in el.Nodes().OfType <XElement>().Where(e => e.Name == "tag"))
            {
                string key   = element.Attribute("k").Value;
                string value = element.Attribute("v").Value;
                tags.Add(key, value);
            }

            foreach (var element in el.Nodes().OfType <XElement>().Where(e => e.Name == "member"))
            {
                OsmMember member = new OsmMember()
                {
                    Type = element.Attribute("type")?.Value,
                    Ref  = long.Parse(element.Attribute("ref")?.Value),
                    Role = element.Attribute("role")?.Value,
                };

                members.Add(member);
            }

            OsmRelation relation = new OsmRelation()
            {
                Id        = id,
                Version   = version,
                Timestamp = timestamp,
                Changeset = changeset,
                Tags      = tags,
                Members   = members,
            };

            RelationRead(relation);
        }
Пример #21
0
        public override void RenderOsmObject(
            MapMakerSettings mapMakerSettings,
            MapDataAnalysis analysis,
            InMemoryOsmDatabase osmDatabase,
            OsmObjectBase osmObject,
            OsmRelation parentRelation,
            CGpsMapperMapWriter mapWriter)
        {
            mapWriter.AddSection("POLYGON")
            .AddTypeReference(TypeRegistration)
            .AddCoordinates(
                "Data",
                analysis.HardwareToLogicalLevelDictionary[TypeRegistration.MaxLevel],
                GetNodesForWay(osmDatabase, (OsmWay)osmObject));

            // rendering of holes
            if (osmObject is OsmAreaWithHoles)
            {
                OsmAreaWithHoles areaWithHoles = (OsmAreaWithHoles)osmObject;
                foreach (int holeWayId in areaWithHoles.EnumerateHolesWaysIds())
                {
                    OsmWay holeWay = osmDatabase.GetWay(holeWayId);
                    if (holeWay.NodesCount > 3)
                    {
                        mapWriter.AddCoordinates(
                            "Data",
                            analysis.HardwareToLogicalLevelDictionary[TypeRegistration.MaxLevel],
                            GetNodesForWay(osmDatabase, holeWay));
                    }
                }
            }

            mapWriter
            .Add("EndLevel", analysis.HardwareToLogicalLevelDictionary[TypeRegistration.MinLevel])
            ;

            if (this.TypeRegistration.Label != null && false == this.TypeRegistration.Label.IsConstant)
            {
                mapWriter.Add("Label", this.TypeRegistration.Label.BuildLabel(mapMakerSettings, osmObject, parentRelation));
            }
        }
Пример #22
0
        OsmRelation GetRelationData(long relationIndex, out OsmWay[] osmWays, out OsmNode[] osmNodes)
        {
            var buf = cacheBuffer;

            cacheData.Position = relationIndex;
            cacheData.Read(buf, 0, sizeof(int));

            int size = BitConverter.ToInt32(buf, 0) - sizeof(int);

            if (cacheData.Read(buf, sizeof(int), size) != size)
            {
                throw new IOException("EOF?");
            }

            int         p = sizeof(int);
            OsmRelation osmRelation;

            p += OsmRelation.ReadBinary(buf, p, out osmRelation);
            ulong tmp;

            p      += ProtoBuf.ReadVarInt(buf, p, out tmp);
            osmWays = new OsmWay[tmp];
            for (int i = 0; i < osmWays.Length; i++)
            {
                p += OsmWay.ReadBinary(buf, p, out osmWays[i]);
            }
            DecodeDelta(osmWays);
            p       += ProtoBuf.ReadVarInt(buf, p, out tmp);
            osmNodes = new OsmNode[tmp];
            for (int i = 0; i < osmNodes.Length; i++)
            {
                p += OsmNode.ReadBinary(buf, p, out osmNodes[i]);
            }
            DecodeDelta(osmNodes);
            if (p != size + sizeof(int))
            {
                throw new PbfParseException();
            }

            return(osmRelation);
        }
Пример #23
0
        public override void RenderOsmObject(
            MapMakerSettings mapMakerSettings,
            MapDataAnalysis analysis,
            InMemoryOsmDatabase osmDatabase,
            OsmObjectBase osmObject,
            OsmRelation parentRelation,
            CGpsMapperMapWriter mapWriter)
        {
            mapWriter.AddSection("POI")
            .AddTypeReference(TypeRegistration);

            // find the location to put the icon on
            OsmNode iconNode = null;

            if (osmObject is OsmNode)
            {
                iconNode = (OsmNode)osmObject;
            }
            else if (osmObject is OsmWay)
            {
                PointD2 location = Brejc.OsmLibrary.Helpers.OsmGeometryUtils.FindAreaCenterPoint(
                    (OsmWay)osmObject,
                    osmDatabase);
                iconNode = new OsmNode(1, location.X, location.Y);
            }
            else
            {
                throw new InvalidOperationException("Internal error.");
            }

            mapWriter
            .AddCoordinates("Data", analysis.HardwareToLogicalLevelDictionary[TypeRegistration.MaxLevel], iconNode)
            .Add("EndLevel", analysis.HardwareToLogicalLevelDictionary[TypeRegistration.MinLevel])
            ;

            if (this.TypeRegistration.Label != null && false == this.TypeRegistration.Label.IsConstant)
            {
                mapWriter.Add("Label", this.TypeRegistration.Label.BuildLabel(mapMakerSettings, osmObject, parentRelation));
            }
        }
Пример #24
0
        public override void RenderOsmObject(
            MapMakerSettings mapMakerSettings,
            MapDataAnalysis analysis,
            InMemoryOsmDatabase osmDatabase,
            OsmObjectBase osmObject,
            OsmRelation parentRelation,
            CGpsMapperMapWriter mapWriter)
        {
            mapWriter.AddSection("POLYLINE")
            .AddTypeReference(TypeRegistration)
            .AddCoordinates(
                "Data",
                analysis.HardwareToLogicalLevelDictionary[TypeRegistration.MaxLevel],
                GetNodesForWay(osmDatabase, (OsmWay)osmObject))
            .Add("EndLevel", analysis.HardwareToLogicalLevelDictionary[TypeRegistration.MinLevel])
            ;

            if (this.TypeRegistration.Label != null && false == this.TypeRegistration.Label.IsConstant)
            {
                mapWriter.Add("Label", this.TypeRegistration.Label.BuildLabel(mapMakerSettings, osmObject, parentRelation).ToUpperInvariant());
            }
        }
Пример #25
0
        public void BuildLabel(
            MapMakerSettings mapMakerSettings,
            StringBuilder label,
            OsmObjectBase osmObject,
            OsmRelation parentRelation,
            Tag osmTag)
        {
            if (keyName.StartsWith("relation:", StringComparison.OrdinalIgnoreCase))
            {
                string relationKeyName = keyName.Substring(9);

                if (parentRelation != null && parentRelation.HasTag(relationKeyName))
                {
                    // if there are no conditions attached, simply use the tag's value
                    if (null == conditionalElement)
                    {
                        label.Append(parentRelation.GetTagValue(relationKeyName));
                    }
                    else
                    {
                        // otherwise we must do some extra work
                        conditionalElement.BuildLabel(mapMakerSettings, label, osmObject, parentRelation, parentRelation.GetTag(relationKeyName));
                    }
                }
            }
            else if (osmObject.HasTag(keyName))
            {
                // if there are no conditions attached, simply use the tag's value
                if (null == conditionalElement)
                {
                    label.Append(osmObject.GetTagValue(keyName));
                }
                else
                {
                    // otherwise we must do some extra work
                    conditionalElement.BuildLabel(mapMakerSettings, label, osmObject, parentRelation, osmObject.GetTag(keyName));
                }
            }
        }
Пример #26
0
        public void BuildLabel(
            MapMakerSettings mapMakerSettings,
            StringBuilder label,
            OsmObjectBase osmObject,
            OsmRelation parentRelation,
            Tag osmTag)
        {
            try
            {
                string expandedString = regexFunction.Replace(
                    format,
                    delegate(Match match)
                {
                    string functionName = match.Groups["function"].Value;

                    if (false == registeredFunctions.ContainsKey(functionName))
                    {
                        throw new ArgumentException(
                            String.Format(
                                CultureInfo.InvariantCulture,
                                "Unknown label building function '{0}'",
                                functionName));
                    }

                    ILabelBuildingFunction function = registeredFunctions[functionName];
                    string result = function.Calculate(mapMakerSettings, osmObject, osmTag, parentRelation);

                    return(result);
                });

                label.Append(expandedString);
            }
            catch (Exception)
            {
                // an exception occurred, we do nothing
            }
        }
Пример #27
0
    /// <summary>
    /// We iterate over the relation instances to generate the Station objects and
    /// the corresponding station UIs.
    /// </summary>
    /// <param name="r">relation instance</param>
    void CreateStations(OsmRelation r)
    {
        foreach (ulong NodeID in r.StoppingNodeIDs)
        {
            GameObject station_object;
            GameObject stationUI_object;

            try
            {
                // If a station has already been created using a node position, a new station will not
                // be created there but the existing one will be augmented with the new information. This
                // avoids the case of multiple overlapping station object at one point.
                if (MapReader.nodes[NodeID].StationCreated == true)
                {
                    List <GameObject> allObjects = new List <GameObject>();
                    Scene             scene      = SceneManager.GetActiveScene();
                    scene.GetRootGameObjects(allObjects);

                    // We iterate over all Unity objects to find the station that has
                    // already been generated at the certain point.
                    for (int i = 5; i < allObjects.Count; i++)
                    {
                        if (allObjects[i].transform.position == MapReader.nodes[NodeID] - MapReader.bounds.Centre)
                        {
                            bool doubleFound = false;

                            // Here we check if the new information that is being added to the station object,
                            // has not already been stored inside the station object. This operation can be traced
                            // back to a bug which I encountered during development, where the same information
                            // was stored multiple times. The reason for this is still unclear, this is a workaround.
                            GameObject Dropdown    = allObjects[i].transform.GetChild(0).transform.GetChild(0).transform.GetChild(2).gameObject;
                            var        dropOptions = Dropdown.GetComponent <Dropdown>();
                            for (int j = 0; j < dropOptions.options.Count; j++)
                            {
                                for (int k = 0; k < MapReader.nodes[NodeID].TransportLines.Count; k++)
                                {
                                    if (dropOptions.options[j].text == MapReader.nodes[NodeID].TransportLines[k])
                                    {
                                        doubleFound = true;
                                        continue;
                                    }
                                }
                            }
                            if (!doubleFound)  // If no information is found, we add the new information here.
                            {
                                dropOptions.AddOptions(MapReader.nodes[NodeID].TransportLines);
                                if (r.TransportType == "bus")
                                {
                                    // Activates the bus symbol in the UI.
                                    allObjects[i].transform.GetChild(0).GetChild(0).transform.GetChild(4).gameObject.SetActive(true);
                                }
                                else
                                {
                                    // Activates the train symbol on the UI.
                                    allObjects[i].transform.GetChild(0).GetChild(0).transform.GetChild(5).gameObject.SetActive(true);
                                }
                                continue;
                            }
                        }
                    }
                    continue;
                }

                station_object = Instantiate(StationPrefab) as GameObject;
                OsmNode new_station          = MapReader.nodes[NodeID];
                Vector3 new_station_position = new_station - MapReader.bounds.Centre;
                station_object.transform.position = new_station_position;

                // Is being set so that on this position, no new stations are being generated.
                MapReader.nodes[NodeID].StationCreated = true;


                stationUI_object = Instantiate(StationUIPrefab) as GameObject;
                stationUI_object.transform.SetParent(station_object.transform.GetChild(0));
                stationUI_object.GetComponent <Canvas>().renderMode = RenderMode.WorldSpace;
                stationUI_object.transform.localPosition            = new Vector3(-15, 0, 0);

                GameObject station_text = stationUI_object.transform.GetChild(1).gameObject;
                station_text.transform.localPosition = new Vector3(0, 7, 0);
                Text OnScreenText = station_text.GetComponent <Text>();
                OnScreenText.text = MapReader.nodes[NodeID].StationName;

                GameObject TransportLineDropdown = stationUI_object.transform.GetChild(2).gameObject;
                var        dropDownOptions       = TransportLineDropdown.GetComponent <Dropdown>();
                dropDownOptions.AddOptions(MapReader.nodes[NodeID].TransportLines);

                stationUI_object.SetActive(false);

                if (r.TransportType == "bus")
                {
                    // Activates the bus symbol on the UI.
                    stationUI_object.transform.GetChild(4).gameObject.SetActive(true);
                }
                else
                {
                    // Activates the train symbol on the UI.
                    stationUI_object.transform.GetChild(5).gameObject.SetActive(true);
                }
            }
            catch (KeyNotFoundException)
            {
                continue;
            }
        }
    }
Пример #28
0
        public static OsmData Parse(string fileName, double minLon, double minLat, double maxLon, double maxLat)
        {
            OsmData osmData = new OsmData();

            AbstractOsmNode.parent = osmData;

            OsmNode     currentNode       = null;
            OsmWay      currentWay        = null;
            OsmRelation currentRelation   = null;
            bool        currentIsNode     = false;
            bool        currentIsWay      = false;
            bool        currentIsRelation = false;

            if (!File.Exists(fileName))
            {
                throw new FileNotFoundException();
            }

            using (XmlReader reader = XmlReader.Create(fileName))
            {
                while (reader.Read())
                {
                    if (reader.IsStartElement())
                    {
                        if (reader.NodeType == XmlNodeType.Element)
                        {
                            if (reader.Name == Constants.Constants.osmNode)
                            {
                                try
                                {
                                    double lat = double.Parse(reader.GetAttribute(Constants.Constants.LatString), CultureInfo.InvariantCulture);
                                    double lon = double.Parse(reader.GetAttribute(Constants.Constants.LonString), CultureInfo.InvariantCulture);

                                    if (osmData.bounds.MinLat <= lat && osmData.bounds.MaxLat >= lat && osmData.bounds.MinLon <= lon && osmData.bounds.MaxLon >= lon)
                                    {
                                        OsmNode newOsmNode = new OsmNode()
                                        {
                                            Id    = long.Parse(reader.GetAttribute(Constants.Constants.IdString)),
                                            Point = new Point()
                                            {
                                                Lat = double.Parse(reader.GetAttribute(Constants.Constants.LatString), CultureInfo.InvariantCulture),
                                                Lon = double.Parse(reader.GetAttribute(Constants.Constants.LonString), CultureInfo.InvariantCulture)
                                            }
                                        };

                                        osmData.Nodes.Add(newOsmNode.Id, newOsmNode);
                                        currentNode       = newOsmNode;
                                        currentIsNode     = true;
                                        currentIsWay      = false;
                                        currentIsRelation = false;
                                    }
                                    else
                                    {
                                        currentIsNode     = false;
                                        currentIsWay      = false;
                                        currentIsRelation = false;
                                    }
                                }
                                catch (Exception ex)
                                {
#if VERBOSE
                                    // Console.WriteLine(ex.Message);
#endif
                                }
                            }

                            else if (reader.Name == Constants.Constants.osmWay)
                            {
                                try
                                {
                                    OsmWay newOsmWay = new OsmWay()
                                    {
                                        Id = long.Parse(reader.GetAttribute(Constants.Constants.IdString)),
                                    };

                                    osmData.Ways.Add(newOsmWay.Id, newOsmWay);
                                    currentWay        = newOsmWay;
                                    currentIsNode     = false;
                                    currentIsWay      = true;
                                    currentIsRelation = false;
                                }
                                catch (Exception ex)
                                {
#if VERBOSE
                                    //Console.WriteLine(ex.Message);
#endif
                                }
                            }

                            else if (reader.Name == Constants.Constants.osmRelation)
                            {
                                try
                                {
                                    OsmRelation newOsmRelation = new OsmRelation()
                                    {
                                        Id = long.Parse(reader.GetAttribute(Constants.Constants.IdString))
                                    };

                                    osmData.Relations.Add(newOsmRelation.Id, newOsmRelation);
                                    currentRelation   = newOsmRelation;
                                    currentIsNode     = false;
                                    currentIsWay      = false;
                                    currentIsRelation = true;
                                }
                                catch (Exception ex)
                                {
#if VERBOSE
                                    //Console.WriteLine(ex.Message);
#endif
                                }
                            }

                            else if (reader.Name == Constants.Constants.osmTag)
                            {
                                try
                                {
                                    string     key    = reader.GetAttribute(Constants.Constants.KeyString);
                                    string     value  = reader.GetAttribute(Constants.Constants.ValueString);
                                    TagKeyEnum tagKey = EnumExtensions.GetTagKeyEnum <TagKeyEnum>(key);

                                    if (tagKey != TagKeyEnum.None)
                                    {
                                        if (currentIsNode && currentNode != null)
                                        {
                                            currentNode.Tags[tagKey] = value;
                                        }
                                        else if (currentIsWay && currentWay != null)
                                        {
                                            currentWay.Tags[tagKey] = value;
                                        }
                                        else if (currentIsRelation && currentRelation != null)
                                        {
                                            currentRelation.Tags[tagKey] = value;
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
#if VERBOSE
                                    // Console.WriteLine(ex.Message);
#endif
                                }
                            }

                            else if (reader.Name == Constants.Constants.osmNd)
                            {
                                try
                                {
                                    long refId = long.Parse(reader.GetAttribute(Constants.Constants.refString));

                                    if (currentWay != null && currentIsWay)
                                    {
                                        currentWay.Nds.Add(refId);
                                    }
                                }
                                catch (Exception ex)
                                {
#if VERBOSE
                                    // Console.WriteLine(ex.Message);
#endif
                                }
                            }

                            else if (reader.Name == Constants.Constants.osmMember)
                            {
                                try
                                {
                                    string role = reader.GetAttribute(Constants.Constants.roleString);
                                    RelationMemberRoleEnum roleEnum = EnumExtensions.GetTagKeyEnum <RelationMemberRoleEnum>(role);

                                    string type = reader.GetAttribute(Constants.Constants.typeString);
                                    RelationMemberTypeEnum typeEnum = EnumExtensions.GetTagKeyEnum <RelationMemberTypeEnum>(type);

                                    if (currentIsRelation && currentRelation != null)
                                    {
                                        currentRelation.Members.Add(new OsmMember()
                                        {
                                            Ref  = long.Parse(reader.GetAttribute(Constants.Constants.refString)),
                                            Role = roleEnum,
                                            Type = typeEnum
                                        });
                                    }
                                }
                                catch (Exception ex)
                                {
#if VERBOSE
                                    //Console.WriteLine(ex.Message);
#endif
                                }
                            }

                            else if (reader.Name == Constants.Constants.osmBounds)
                            {
                                double fileMinLat;
                                double fileMinLon;
                                double fileMaxLat;
                                double fileMaxLon;

                                try
                                {
                                    fileMinLat = double.Parse(reader.GetAttribute(Constants.Constants.MinLatString), System.Globalization.CultureInfo.InvariantCulture);
                                    fileMinLon = double.Parse(reader.GetAttribute(Constants.Constants.MinLonString), System.Globalization.CultureInfo.InvariantCulture);
                                    fileMaxLat = double.Parse(reader.GetAttribute(Constants.Constants.MaxLatString), System.Globalization.CultureInfo.InvariantCulture);
                                    fileMaxLon = double.Parse(reader.GetAttribute(Constants.Constants.MaxLonString), System.Globalization.CultureInfo.InvariantCulture);
                                }
                                catch (Exception)
                                {
                                    throw new Exception("FIle bad bounds");
                                }


                                osmData.bounds = new OsmBounds();


                                if (fileMaxLat <= minLat && fileMaxLon <= minLon && fileMinLat >= maxLat && fileMinLon >= maxLon)
                                {
                                    break;
                                }

                                if (fileMinLat >= minLat)
                                {
                                    osmData.bounds.MinLat = fileMinLat;
                                }
                                else
                                {
                                    osmData.bounds.MinLat = minLat;
                                }

                                if (fileMinLon >= minLon)
                                {
                                    osmData.bounds.MinLon = fileMinLon;
                                }
                                else
                                {
                                    osmData.bounds.MinLon = minLon;
                                }

                                if (fileMaxLat >= maxLat)
                                {
                                    osmData.bounds.MaxLat = maxLat;
                                }
                                else
                                {
                                    osmData.bounds.MaxLat = fileMaxLat;
                                }

                                if (fileMaxLon >= maxLon)
                                {
                                    osmData.bounds.MaxLon = maxLon;
                                }
                                else
                                {
                                    osmData.bounds.MaxLon = fileMaxLon;
                                }
                            }
                        }
                    }
                }
            }
            return(osmData);
        }
 public string Calculate(MapMakerSettings mapMakerSettings, OsmObjectBase osmObjectBase, Tag osmTag, OsmRelation parentRelation)
 {
     return(osmTag.Value.ToUpperInvariant());
 }
 public string Calculate(MapMakerSettings mapMakerSettings, OsmObjectBase osmObjectBase, Tag osmTag, OsmRelation parentRelation)
 {
     return(string.Format(
                CultureInfo.InvariantCulture,
                "~[0x{0:x}]",
                specialCode));
 }