Inheritance: Obstacle
    /// <summary>
    /// Generates all the rivers in the world.
    /// Generates <para name="count"></para> rivers in total
    /// </summary>
    /// <param name="count"></param>
    public void GenerateAllRivers(int count = 10)
    {
        //Create a RNG to use for generating rivers
        GenerationRandom genRan = new GenerationRandom(GameGenerator.Seed);

        Vec2i middle = new Vec2i(World.WorldSize / 2, World.WorldSize / 2);

        River[] rivers = new River[count];
        for (int i = 0; i < count; i++)
        {
            //Define the start point as one within a set distance of the middle of the map
            Vec2i startOff = genRan.RandomVec2i(-World.WorldSize / 5, World.WorldSize / 5);
            //Create null direction, define main direction heading away from land mass centre
            Vec2i dir = null;

            //Check directions travelling in negative x direction.
            if (startOff.x <= 0)
            {
                //If the z value is of greater magnitude, then the river travels in the z direction
                if (Mathf.Abs(startOff.z) > Mathf.Abs(startOff.x))
                {
                    dir = new Vec2i(0, (int)Mathf.Sign(startOff.z));
                }
                else
                {
                    dir = new Vec2i(-1, 0);
                }
            }
            else
            {
                //If the z value is of greater magnitude, then the river travels in the z direction
                if (Mathf.Abs(startOff.z) > Mathf.Abs(startOff.x))
                {
                    dir = new Vec2i(0, (int)Mathf.Sign(startOff.z));
                }
                else
                {
                    dir = new Vec2i(1, 0);
                }
            }
            //Generate and store river
            rivers[i] = GenerateRiver(middle + startOff, dir, genRan);
        }


        foreach (River riv in rivers)
        {
            foreach (KeyValuePair <Vec2i, RiverNode> kvp in riv.GenerateRiverNodes())
            {
                if (GameGenerator.TerrainGenerator.ChunkBases[kvp.Key.x, kvp.Key.z].RiverNode == null)
                {
                    GameGenerator.TerrainGenerator.ChunkBases[kvp.Key.x, kvp.Key.z].AddRiver(kvp.Value);
                }
                else
                {
                    GameGenerator.LakeGenerator.AddLake(new Lake(kvp.Key, 10));
                }
            }
        }
    }
示例#2
0
 private void SetRiverTile(River river)
 {
     SetRiverPath(river);
     TerrainData.HeightType  = HeightType.River;
     TerrainData.HeightValue = 0;
     TerrainData.Collidable  = false;
 }
        public async Task <IActionResult> Edit(int id, [Bind("RiverId,Name,TotalLength,NumAPs,MapPath")] River river)
        {
            if (id != river.RiverId)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(river);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!RiverExists(river.RiverId))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(river));
        }
    private River GenerateRiver(Vec2i start, Vec2i mainDirection, GenerationRandom genRan)
    {
        bool  shouldStop = false;
        River r          = new River();

        r.SetFirstChunk(start, 5);
        List <Vec2i> directions = new List <Vec2i>();

        directions.Add(mainDirection);
        directions.Add(mainDirection);
        directions.Add(mainDirection);
        directions.Add(mainDirection);
        directions.AddRange(PerpDir(mainDirection));
        Vec2i last = start;

        while (!shouldStop)
        {
            Vec2i next = last + genRan.RandomFromList <Vec2i>(directions);
            if (r.AddChunk(next, 5))
            {
                last = next;
                if (next.x < 0 || next.z < 0 || next.x >= World.WorldSize || next.z >= World.WorldSize)
                {
                    shouldStop = true;
                }
                else if (!GameGenerator.TerrainGenerator.ChunkBases[next.x, next.z].IsLand)
                {
                    shouldStop = true;
                }
            }
        }

        return(r);
    }
示例#5
0
 public ActionResult Post([FromBody] SampleRiver river)
 {
     try
     {
         List <Country> tempList = new List <Country>();
         foreach (var country in CountryManager.GetAll())
         {
             if (river.Countries.Contains(country.ID.ToString()))
             {
                 tempList.Add(country);
             }
         }
         if (tempList.Count == river.Countries.Count)
         {
             logger.LogInformation("RiverController : Get => " + DateTime.Now);
             River x = new River(river.Name, river.Lenght, tempList);
             RiverManager.Add(x);
             return(CreatedAtAction(nameof(Get), new { id = x.ID }, x));
         }
         else
         {
             return(NotFound("Country input not found"));
         }
     }catch (Exception e)
     {
         return(BadRequest(e.Message));
     }
 }
示例#6
0
        protected void btnEdit_Click(object sender, EventArgs e)
        {
            RiverTableAdapter RiverTableAdapter = new RiverTableAdapter();
            River             originalRiver     = RiverTableAdapter.GetRiverByID(Convert.ToInt32(Request["RiverID"]));

            River River = new River();

            if (IsValidData())
            {
                River.ID          = originalRiver.ID;
                River.RiverName   = txtRiverName.Text.Trim();
                River.RiverID     = Guid.NewGuid().ToString();
                River.Latitude    = txtLatitude.Text.Trim();
                River.Longitude   = txtLongitude.Text.Trim();
                River.Description = txtDescription.Text.Trim();
                River.Status      = "ACTIVE";


                if (RiverTableAdapter.Update(River) > 0)
                {
                    ltlMessage.Text = "<div class=\"alert alert-success alert-dismissible\"><button type = \"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">&times;</button> <h4><i class=\"icon fa fa-check\"></i> Alert!</h4> Sucessfully Updated <b>" + txtRiverName.Text.Trim() + "</b>.</div>";
                    Response.Redirect("~/Rivers/riverlist.aspx");
                }
            }
        }
示例#7
0
        public void IsLandOrWaterTest()
        {
            var h = new Hex();

            Assert.IsTrue(h.IsWater());
            Assert.IsFalse(h.IsLand());

            h = new Hex(Hex.HexType.Ocean);
            Assert.IsTrue(h.IsWater());
            Assert.IsFalse(h.IsLand());

            h = new Hex(Hex.HexType.Shore);
            Assert.IsTrue(h.IsWater());
            Assert.IsFalse(h.IsLand());

            h = new Hex(Hex.HexType.Land);
            Assert.IsFalse(h.IsWater());
            Assert.IsTrue(h.IsLand());

            var r  = new River();
            var rs = new RiverSegment(r);

            h.MainRiverSegment = rs;
            Assert.IsFalse(h.IsWater());
            Assert.IsTrue(h.IsLand());
        }
示例#8
0
        static void Main()
        {
            var context = new GeographyEntities();
            var xmlDoc  = XDocument.Load(@"..\..\rivers.xml");
            //Console.WriteLine(xmlDoc);
            var riverElements = xmlDoc.Root.Elements();

            foreach (var riverElement in riverElements)  //in xmlDoc.XPathSelectElements("/rivers/river")
            {
                var riverEntity = new River();
                riverEntity.RiverName = riverElement.Element("name").Value;
                //Console.WriteLine(riverElement.Element("name").Value);
                riverEntity.Length  = int.Parse(riverElement.Element("length").Value);
                riverEntity.Outflow = riverElement.Element("outflow").Value;
                if (riverElement.Element("drainage-area") != null)
                {
                    riverEntity.DrainageArea = int.Parse(riverElement.Element("drainage-area").Value);
                }
                if (riverElement.Element("average-discharge") != null)
                {
                    riverEntity.AverageDischarge = int.Parse(riverElement.Element("average-discharge").Value);
                }

                ParseAndAddCountriesToRiver(context, riverElement, riverEntity);

                context.Rivers.Add(riverEntity);
            }

            context.SaveChanges();
        }
示例#9
0
        public void RiverExtensions_DoesReturnDataArray()
        {
            var river = new River();
            var array = river.PopulateRiverData();

            Assert.NotNull(array);
        }
示例#10
0
        static int DoShowAll(ParsedOpts args)
        {
            var profileStore   = new UserProfileStore();
            var aggregateStore = new AggregateRiverStore();

            UserProfile profile = profileStore.GetProfileFor(args["user"].Value).Result;

            foreach (RiverDefinition rd in profile.Rivers)
            {
                Console.WriteLine("Loading {0} ({1})...", rd.Name, rd.Id);
                River river = aggregateStore.LoadAggregate(rd.Id).Result;
                if (river.UpdatedFeeds.Feeds.Count > 0)
                {
                    foreach (FeedSegment feed in river.UpdatedFeeds.Feeds)
                    {
                        DumpFeed(feed);
                    }
                }
                else
                {
                    Console.WriteLine("No data for {0}", rd.Name);
                }
            }

            return(0);
        }
示例#11
0
        private void button3_Click(object sender, EventArgs e)
        {
            int count = _Rivers.Count + 1;

            try
            {
                River myNewRiver = new River(count, textBox3.Text, int.Parse(textBox4.Text),
                                             int.Parse(textBox5.Text), int.Parse(textBox6.Text), double.Parse(textBox7.Text), textBox8.Text);
                _Rivers.Add(myNewRiver);
                dataGridView1.Rows.Add(myNewRiver.number, myNewRiver.title, myNewRiver.extent, myNewRiver.extentRussia, myNewRiver.poolArea, myNewRiver.waterFlow, myNewRiver.flowsInto);
            }
            catch
            {
                MessageBox.Show("Некорректный ввод данных!");
                textBox4.Text = "";
                textBox5.Text = "";
                textBox6.Text = "";
                textBox7.Text = "";
            }
            finally
            {
                textBox3.Text = "";
                textBox4.Text = "";
                textBox5.Text = "";
                textBox6.Text = "";
                textBox7.Text = "";
                textBox8.Text = "";
            }
        }
示例#12
0
    void Start()
    {
        river = FindObjectOfType <River>();

        var y = transform.position.y;
        var x = Random.Range(river.GetBank(y, true) + radius, river.GetBank(y, false) - radius);

        transform.position = new Vector3(x, y, transform.position.z);

        lines             = new LineRenderer[lineCount];
        lineTimeOffsets   = new float[lineCount];
        lineRadiusOffsets = new float[lineCount];

        for (int i = 0; i < lineCount; i++)
        {
            var lineObj = new GameObject();
            lineObj.transform.position = transform.position;
            lineObj.transform.SetParent(transform);
            lines[i]               = lineObj.AddComponent <LineRenderer>();
            lines[i].startWidth    = 1f / 16f;
            lines[i].endWidth      = 1f / 16f;
            lines[i].useWorldSpace = false;
            lines[i].material      = lineMaterial;
            lineTimeOffsets[i]     = Random.value;
            lineRadiusOffsets[i]   = Random.value;
        }
    }
示例#13
0
        internal void Initialize(River river)
        {
            AutoScrollSpeed          = Math.Abs(Settings.Default.AutoScrollSpeed);
            AutoScrollDirection      = Math.Sign(Settings.Default.AutoScrollDirection);
            IsProfanityFilterEnabled = Settings.Default.IsProfanityFilterEnabled;
            RetrievalOrder           = Settings.Default.RetrievalOrder;

            // Set up the FeedProcessor on a background thread.
            Thread thread = new Thread(() =>
            {
                ObservableCollection <string> flickrQuery = new ObservableCollection <string>(Split(Settings.Default.FlickrQuery.Trim()));
                Split(Settings.Default.FlickrBans.Trim()).ToList().ForEach(ban => flickrQuery.Add(Processor.NegativeQueryMarker + ban));

                ObservableCollection <string> newsQuery = new ObservableCollection <string>(Split(Settings.Default.NewsQuery.Trim()));
                Split(Settings.Default.NewsBans.Trim()).ToList().ForEach(ban => newsQuery.Add(Processor.NegativeQueryMarker + ban));

                ObservableCollection <string> twitterQuery = new ObservableCollection <string>(Split(Settings.Default.TwitterQuery.Trim()));
                Split(Settings.Default.TwitterBans.Trim()).ToList().ForEach(ban => twitterQuery.Add(Processor.NegativeQueryMarker + ban));

                ObservableCollection <string> facebookQuery = new ObservableCollection <string>(Split(Settings.Default.FacebookQuery.Trim()));
                Split(Settings.Default.FacebookBans.Trim()).ToList().ForEach(ban => facebookQuery.Add(Processor.NegativeQueryMarker + ban));

                FeedProcessor = new FeedProcessor.Processor(
                    Settings.Default.FlickrApiKey,
                    Settings.Default.FacebookClientId,
                    Settings.Default.FacebookClientSecret,
                    Settings.Default.DisplayFbContentFromOthers,
                    Settings.Default.FlickrPollInterval,
                    Settings.Default.TwitterPollInterval,
                    Settings.Default.NewsPollInterval,
                    Settings.Default.FacebookPollInterval,
                    Settings.Default.MinFeedItemDate)
                {
                    Profanity = new ObservableCollection <string>(File.Exists("Profanity.txt") ? File.ReadAllLines("Profanity.txt") : new string[0]),
                    DistributeContentEvenly  = Settings.Default.DistributeContentEvenly,
                    IsProfanityFilterEnabled = IsProfanityFilterEnabled,
                    RetrievalOrder           = RetrievalOrder,
                    FlickrQuery   = flickrQuery,
                    NewsQuery     = newsQuery,
                    TwitterQuery  = twitterQuery,
                    FacebookQuery = facebookQuery
                };

                IsContentLoaded            = FeedProcessor.FeedCount == 0;
                var uiDisp                 = Dispatcher.CurrentDispatcher;
                FeedProcessor.CachePurged += (sender, e) => uiDisp.Invoke(new Action(() => { river.PurgeHistory(e.ValidData); }));
                FeedProcessor.FeedUpdated += FeedProcessor_FeedUpdated;

                IsInitialized = true;
                IsPaused      = false;

                // Cache the tag client, otherwise the first instance takes a while to start up.
                using (MicrosoftTagService.MIBPContractClient tagClient = new MicrosoftTagService.MIBPContractClient())
                {
                }
            });

            thread.Priority = ThreadPriority.Lowest;
            thread.Start();
        }
示例#14
0
 private void SetRiverTile(River river)
 {
     SetRiverPath(river);
     heightType   = HeightType.River;
     heightValue  = 0;
     isCollidable = false;
 }
示例#15
0
    public static List <River> ConvertToRivers(List <RiverSdo> riverSdos)
    {
        if (riverSdos == null || riverSdos.Count < 1)
        {
            return(null);
        }

        var rivers = new List <River>();

        foreach (var sdo in riverSdos)
        {
            River river;
            if (WorldData.Instance.Rivers.ContainsKey(sdo.Id))
            {
                river = WorldData.Instance.Rivers[sdo.Id];
            }
            else
            {
                river        = new River(sdo.Id);
                river.Length = sdo.Length;

                foreach (var id in sdo.CellIds)
                {
                    river.Cells.Add(WorldData.Instance.MapDictionary[id]);
                }

                WorldData.Instance.Rivers.Add(sdo.Id, river);
            }
            rivers.Add(river);
        }

        return(rivers);
    }
        public ActionResult <RiverRestOutput> Get(int id)
        {
            log("Get");
            try
            {
                River           river           = riverRepos.GetRiver(id);
                List <string>   countryUrls     = new List <string>();
                RiverRestOutput riverRestOutput = new RiverRestOutput(id, river.Name, river.Length);

                if (river.RiverMappings != null)
                {
                    foreach (RiverMapping rm in river.RiverMappings)
                    {
                        string url = $"http://localhost:50055/api/continent/{id}/country/{rm.CountryId}";
                        countryUrls.Add(url);
                    }
                    riverRestOutput.CountryId = countryUrls;
                }
                return(riverRestOutput);
            }
            catch (GeoException ex)
            {
                return(NotFound(ex.Message));
            }
        }
        public void AddEdge(int v, int u, int owner = -1)
        {
            var river = new River(v, u, owner);

            Vertexes[v].Edges.Add(Edge.Forward(river));
            Vertexes[u].Edges.Add(Edge.Backward(river));
        }
示例#18
0
        /// <summary>
        /// Добавляет реку в базу данных.
        /// </summary>
        /// <param name="river">Объект, представляющий реку.</param>
        /// <returns>Была ли река добавлена?</returns>
        private bool addRiverToDB(River river)
        {
            bool riverAlreadyExists = false;

            foreach (DataGridViewRow row in riversDataGridView.Rows)
            {
                if (
                    (string)row.Cells[1].Value == river.name &&
                    ((double)row.Cells[2].Value).ToString() == river.length.ToString() &&
                    (string)row.Cells[3].Value == river.source &&
                    (string)row.Cells[4].Value == river.mouth
                    )
                {
                    riverAlreadyExists = true;
                    break;
                }
            }
            if (!riverAlreadyExists)
            {
                riversTableAdapter.Insert(
                    river.name,
                    river.length,
                    river.source,
                    river.mouth
                    );
            }
            return(!riverAlreadyExists);
        }
示例#19
0
        public static void Main(string[] args)  // Pass in <IP address> and <port> for RabbitMQ
        {
            var rapidsConnection = new RabbitMqRapids("monitor_all_csharp", args[0], args[1]);
            var river            = new River(rapidsConnection);

            river.Register(new Monitor());
        }
示例#20
0
        public int Update(River river)
        {
            UpdateCommand.Parameters["@ID"].Value          = river.ID;
            UpdateCommand.Parameters["@RiverID"].Value     = river.RiverID;
            UpdateCommand.Parameters["@RiverName"].Value   = river.RiverName;
            UpdateCommand.Parameters["@Latitude"].Value    = river.Latitude;
            UpdateCommand.Parameters["@Longitude"].Value   = river.Longitude;
            UpdateCommand.Parameters["@Description"].Value = river.Description;
            UpdateCommand.Parameters["@Status"].Value      = river.Status;

            int returnValue = -1;

            try
            {
                UpdateCommand.Connection.Open();
                returnValue = UpdateCommand.ExecuteNonQuery();
            }
            catch (SqlException ex)
            {
                Logger.Write(ex);
            }
            finally
            {
                UpdateCommand.Connection.Close();
            }
            return(returnValue);
        }
示例#21
0
        public int Insert(River river)
        {
            InsertCommand.Parameters["@RiverID"].Value     = river.RiverID;
            InsertCommand.Parameters["@RiverName"].Value   = river.RiverName;
            InsertCommand.Parameters["@Latitude"].Value    = river.Latitude;
            InsertCommand.Parameters["@Longitude"].Value   = river.Longitude;
            InsertCommand.Parameters["@Description"].Value = river.Description;
            InsertCommand.Parameters["@Status"].Value      = river.Status;


            int returnValue = -1;

            try
            {
                InsertCommand.Connection.Open();
                returnValue = (int)InsertCommand.ExecuteScalar();
            }
            catch (SqlException ex)
            {
                Logger.Write(ex);
            }
            finally
            {
                InsertCommand.Connection.Close();
            }
            return(returnValue);
        }
示例#22
0
        public RiverRenderer(Transform transform, Material mat, Island island, River river)
        {
            _transform = transform;
            _waterMat  = mat;
            _island    = island;

            _root = new RiverNode(river);

            Queue <RiverTuple> riverQueue = new Queue <RiverTuple>();

            riverQueue.Enqueue(new RiverTuple(river, _root));
            while (riverQueue.Count > 0)
            {
                var currNode = riverQueue.Dequeue();
                if (currNode._dataNode.left != null)
                {
                    var pos = new Vector3((float)currNode._dataNode.left.data.position[0],
                                          currNode._dataNode.left.data.elevation,
                                          (float)currNode._dataNode.left.data.position[1]);
                    currNode._renderNode.AddUpStream(pos, currNode._dataNode.left.discharge);
                    riverQueue.Enqueue(new RiverTuple(currNode._dataNode.left,
                                                      currNode._renderNode._upstream[currNode._renderNode._upstream.Count - 1]));
                }
                if (currNode._dataNode.right != null)
                {
                    var pos = new Vector3((float)currNode._dataNode.right.data.position[0],
                                          currNode._dataNode.right.data.elevation,
                                          (float)currNode._dataNode.right.data.position[1]);
                    currNode._renderNode.AddUpStream(pos, currNode._dataNode.right.discharge);
                    riverQueue.Enqueue(new RiverTuple(currNode._dataNode.right,
                                                      currNode._renderNode._upstream[currNode._renderNode._upstream.Count - 1]));
                }
            }
        }
示例#23
0
 public void AddRiver(River river)
 {
     if (!rivers.Contains(river))
     {
         rivers.Add(river);
     }
 }
示例#24
0
        /// <summary>
        /// Возвращает реку, распарсивая страницу с нею.
        /// </summary>
        /// <param name="document">HTML страница с информацией о реке</param>
        /// <returns>Объект River с заполненными полями.</returns>
        public River getRiver(IHtmlDocument document)
        {
            River returnRiver = new River();

            Regex rlength = new Regex(@"(\d+)");

            returnRiver.name = document.QuerySelector("table.infobox tbody tr th.infobox-above").TextContent;
            foreach (var item in document.QuerySelectorAll("table.infobox tbody tr"))
            {
                // Выбираем весь текст до первой '.' или 'переноса строки'.
                var text = item.QuerySelector("th")?.TextContent?.Split('.')[0]?.Split('\n')[0]?.Trim();

                if (text != null && text == "Длина")
                {
                    returnRiver.length = double.Parse(rlength.Match(item.QuerySelector("td").TextContent.Trim()).Groups[1].Value);
                }
                else if (text != null && text == "Исток")
                {
                    returnRiver.source = item.QuerySelector("td").TextContent.Trim();
                }
                else if (text != null && text == "Устье")
                {
                    returnRiver.mouth = item.QuerySelector("td").TextContent.Trim();
                }
            }

            return(returnRiver);
        }
示例#25
0
    private void FindRiverPath(River r)
    {
        Vector3 activePos = r.riverPoints[0];
        Vector3 lastPos;
        int     steps = 0;

        while (activePos.z > waterHeight - riverMaxWaterDepth)
        {
            lastPos = activePos;
            float actualDistance = 0;
            //Default search radius
            float searchRadius = 2;
            //Check previous moves to see if any significant progress has been made
            if (r.riverPoints.Count > 2)
            {
                for (int i = r.riverPoints.Count - 2; i > 0 && i > r.riverPoints.Count - 10; i--)
                {
                    float distanceBack = (r.riverPoints[r.riverPoints.Count - 1] - r.riverPoints[i]).magnitude;
                    if (distanceBack > 10)
                    {
                        break;
                    }
                    actualDistance = distanceBack;
                }
                // If progress has been mediocre, increase search distance
                if (actualDistance < 8)
                {
                    searchRadius = riverSearchDist;
                }
            }


            //Check where is forwards, radius increases based on previous movement
            Vector3 dir = GetFlowDirection(activePos, searchRadius, 12);

            if (steps == 0)
            {
                activePos += dir * riverStepSize;
            }
            //Mix between flowDir & previousDir
            //dir = ((activePos - lastPos).normalized + dir) / 2;
            dir = Vector3.Lerp((activePos - lastPos).normalized, dir, 0.85f);

            activePos += dir * riverStepSize;
            float h = HeightAt(new Vector2(activePos.x, activePos.y));
            //Make sure height is correct
            activePos.z = h;
            //Add point
            r.riverPoints.Add(activePos);
            //Count steps
            steps++;
            r.length += (lastPos - activePos).magnitude;
            if (steps > 2000)
            {
                break;
            }
        }
        //Debug.Log("Steps: " + steps);
    }
示例#26
0
        public ActionResult DeleteConfirmed(int id)
        {
            River river = db.Rivers.Find(id);

            db.Rivers.Remove(river);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
示例#27
0
 void OnCollisionEnter2D(Collision2D collision)
 {
     if (collision.gameObject.tag == "River")
     {
         //Debug.Log("River");
         river = collision.gameObject.GetComponent <River>();
     }
 }
示例#28
0
        public void TestRiverDistance4()
        {
            Line[] segments = { new Line(0, 0, 100, 0), new Line(100, 0, 100, 20) };
            River  r        = new River(segments);
            double dist     = r.Distance(new Point(90, 50));

            Assert.AreEqual(Math.Sqrt(1000), dist, 1e-5);
        }
示例#29
0
        public void TestRiverDistance1()
        {
            Line[] segments = { new Line(0, 0, 100, 0), new Line(100, 0, 100, 20) };
            River  r        = new River(segments);
            double dist     = r.Distance(new Point(30, 10));

            Assert.AreEqual(10, dist, 1e-5);
        }
示例#30
0
        static void Main()
        {
            var context = new GeographyEntities();
            // var rivers = context.Rivers.Count(); // check DB

            // Load the XML from file and test print
            var xmlDoc = XDocument.Load(@"..\..\rivers.xml");
            //System.Console.WriteLine(xmlDoc);

            var riverNodes = xmlDoc.XPathSelectElements("/rivers/river");

            foreach (var riverNode in riverNodes)
            {
                //extract the mandatory fields
                string riverName    = riverNode.Element("name").Value;
                int    riverLenght  = int.Parse(riverNode.Element("length").Value);
                string riverOutflow = riverNode.Element("outflow").Value;

                //extract the optional fields
                int?drainageArea = null;
                if (riverNode.Element("drainage-area") != null)
                {
                    drainageArea = int.Parse(riverNode.Element("drainage-area").Value);
                }

                int?averageDischarge = null;
                if (riverNode.Element("average-discharge") != null)
                {
                    averageDischarge = int.Parse(riverNode.Element("average-discharge").Value);
                }

                // Import the parsed rivers into the database
                var river = new River()
                {
                    RiverName        = riverName,
                    Length           = riverLenght,
                    Outflow          = riverOutflow,
                    DrainageArea     = drainageArea,
                    AverageDischarge = averageDischarge
                };


                // Load the countries for each river
                var countryNodes = riverNode.XPathSelectElements("countries/country");
                var countryNames = countryNodes.Select(c => c.Value);
                foreach (var countryName in countryNames)
                {
                    var country = context.Countries.FirstOrDefault(c => c.CountryName == countryName);
                    river.Countries.Add(country);
                }

                // Save the river in the database
                context.Rivers.Add(river);
                context.SaveChanges();
            }

            System.Console.WriteLine("Rivers imported from rivers.xml");
        }
示例#31
0
	public int GetRiverNeighborCount(River river)
	{
		int count = 0;
		if (Left.Rivers.Count > 0 && Left.Rivers.Contains (river))
			count++;
		if (Right.Rivers.Count > 0 && Right.Rivers.Contains (river))
			count++;
		if (Top.Rivers.Count > 0 && Top.Rivers.Contains (river))
			count++;
		if (Bottom.Rivers.Count > 0 && Bottom.Rivers.Contains (river))
			count++;
		return count;
	}
    static void Main()
    {
        var xmlDoc = XDocument.Load(@"..\..\rivers.xml");
        var riverNodes = xmlDoc.XPathSelectElements("/rivers/river");
        var context = new GeographyEntities();
        foreach (var riverNode in riverNodes)
        {
            // Parse the river properties
            var river = new River
            {
                RiverName = riverNode.Descendants("name").First().Value,
                Length = int.Parse(riverNode.Descendants("length").First().Value),
                Outflow = riverNode.Descendants("outflow").First().Value
            };
            var drainageArea = riverNode.Descendants("drainage-area").FirstOrDefault();
            if (drainageArea != null)
            {
                river.DrainageArea = int.Parse(drainageArea.Value);
            }
            var averageDischarge = riverNode.Descendants("average-discharge").FirstOrDefault();
            if (averageDischarge != null)
            {
                river.AverageDischarge = int.Parse(averageDischarge.Value);
            }

            // Load the countries for each river
            var countryNodes = riverNode.XPathSelectElements("countries/country");
            foreach (var countryNode in countryNodes)
            {
                var country = context.Countries.
                    FirstOrDefault(c => c.CountryName == countryNode.Value);
                if (country == null)
                {
                    throw new Exception("Can not find country: " + countryNode.Value);
                }
                river.Countries.Add(country);
            }

            // Save the river in the database
            context.Rivers.Add(river);
            context.SaveChanges();
        }

        Console.WriteLine("Rivers imported from rivers.xml");
    }
        public void Create(GameStartupSettings settings)
        {
            Random rnd = new Random();

            log.DebugFormat("Create( {0} )", settings);
            HeightMap heightmap = CreateHeightMap(settings);

            float seaLevel = heightmap.FindHeightLevel(settings.OceanRatio * 1.5f, 0.05f); // <-- Values from settings
            float shoreLevel = heightmap.FindHeightLevel(settings.OceanRatio, 0.05f); // <-- Values from settings
            float hillLevel = heightmap.FindHeightLevel(0.1f, 0.01f); // <-- Values from settings
            float mountainLevel = heightmap.FindHeightLevel(settings.PeakRatio, 0.01f); // <-- Values from settings

            OnProgress(new ProgressNotificationEventArgs(string.Format("Min: {0}, Sea: {1}, shoreLevel: {2}, mountain: {3}, max: {4}", heightmap.Minimum, seaLevel, shoreLevel, mountainLevel, heightmap.Maximum), 1f, 0.1f));

            Init(settings.Width, settings.Height);

            // assign coords
            for (int i = 0; i < settings.Width; ++i)
            {
                for (int j = 0; j < settings.Height; ++j)
                {
                    this[i, j].Height = heightmap[i, j];
                }
            }

            Terrain ocean = Provider.Instance.Terrains["Ocean"];
            Terrain shore = Provider.Instance.Terrains["Shore"]; // Shore
            Terrain coast = Provider.Instance.Terrains["Coast"];
            Terrain grassland = Provider.Instance.Terrains["Grassland"];

            Feature hills = Provider.Instance.Features["Hills"];
            Feature mountains = Provider.Instance.Features["Mountains"];

            // settle ground plains (ocean, grassland, mountain)
            RangeConversion<float, Terrain> conv = new RangeConversion<float, Terrain>(grassland);

            conv.AddMapping(heightmap.Minimum, seaLevel, ocean);
            conv.AddMapping(seaLevel, shoreLevel, shore);
            conv.AddMapping(shoreLevel, hillLevel, grassland);
            //conv.AddMapping(hillLevel, mountainLevel, hill);
            //conv.AddMapping(mountainLevel, heightmap.Maximum, mountain);

            for (int i = 0; i < settings.Width; ++i)
            {
                for (int j = 0; j < settings.Height; ++j)
                {
                    this[i, j].Terrain = conv.Find(heightmap[i, j]);

                    if(hillLevel <= heightmap[i,j] && heightmap[i,j] < mountainLevel)
                        this[i, j].Features.Add(hills);
                    else if(mountainLevel <= heightmap[i,j])
                        this[i, j].Features.Add(mountains);
                }
            }

            OnProgress(new ProgressNotificationEventArgs("Basic Terrain Assignment", 1f, 0.2f));

            // find coasts
            for (int i = 0; i < settings.Width; ++i)
            {
                for (int j = 0; j < settings.Height; ++j)
                {
                    if (this[i, j].IsOcean)
                    {
                        if (ShouldBeCoast(i, j))
                            this[i, j].Terrain = coast;
                    }
                }
            }

            OnProgress(new ProgressNotificationEventArgs("Find Coasts: " + GetArea(a => a.IsOcean).Count + " ocean tiles, " + GetArea(a => a.IsLand).Count + " land tiles", 1f, 0.3f));

            // find river tiles
            List<MapCell> hillsOrMountains = GetArea(a => a.IsSpring);

            int currentRiverId = 0;

            int numOfRivers = Math.Min(hillsOrMountains.Count, settings.NumOfRivers);
            Array corners = Enum.GetValues(typeof(HexCorner));
            while( currentRiverId < numOfRivers)
            {
                MapCell spring = hillsOrMountains.PickRandom();

                HexCorner randomCorner = (HexCorner)corners.GetValue(rnd.Next(corners.Length));

                HexPointCorner hxc = new HexPointCorner { Corner = randomCorner, Point = spring.Point };
                HexPointFlow[] flows = GetFlowByCorner(hxc);

                River currentriver = new River(string.Format("River{0}", currentRiverId));
                Rivers.Add(currentriver);
                DoRiver(flows[rnd.Next(3)], hxc, currentriver, 0);

                currentRiverId++;
            }

            OnProgress(new ProgressNotificationEventArgs("Add Rivers: " + GetArea(a => a.IsRiver).Count + " tiles", 1f, 0.3f));
        }
        private void DoRiver(HexPointFlow hexPointFlow, HexPointCorner hxc, River river, int iteration)
        {
            if (river.Points.Count > 50 || iteration > 100) // paranoia
                return;

            if (!IsValid(hxc.Point))
                return;

            if( !river.Points.Select( a => a.Point).Contains(hxc.Point) )
                river.Points.Add(new FlowPoint( hxc.Point, hexPointFlow.Flow));

            this[hxc.Point].SetRiver(hexPointFlow.Flow);

            if (this[hxc.Point].IsOcean)
                return;

            List<HexPointFlow> flows = new List<HexPointFlow>(GetFlowByCorner(hxc));

            // remove not valid and current flow (resp. reverse flow)
            for (int i = 2; i > -1; i-- )
            {
                if (!IsValid(flows[i].Corner.Point) || Reverse(flows[i].Flow) == hexPointFlow.Flow || flows[i].Flow == hexPointFlow.Flow)
                    flows.RemoveAt(i);
            }

            if (flows.Count == 0)
                return;

            if( flows.Count == 1) 
            {
                DoRiver( new HexPointFlow { Corner = flows[0].Corner, Flow = flows[0].Flow }, flows[0].Corner, river, iteration + 1);
                return;
            }

            float height1 = GetHeightAtCorner( flows[0].Corner.Point.X, flows[0].Corner.Point.Y, flows[0].Corner.Corner);
            float height2 = GetHeightAtCorner( flows[1].Corner.Point.X, flows[1].Corner.Point.Y, flows[1].Corner.Corner);

            if(height1 < height2)
                DoRiver(new HexPointFlow { Corner = flows[0].Corner, Flow = flows[0].Flow }, flows[0].Corner, river, iteration + 1);
            else
                DoRiver(new HexPointFlow { Corner = flows[1].Corner, Flow = flows[1].Flow }, flows[1].Corner, river, iteration + 1);
        }
示例#35
0
    public void ReadRivers()
    {
        //clear previous data
        rivers.Clear();

        string gml = controller.Geometry_GetGML(controller.CurrentGeomFile());

        //Parse xml from gml
        XmlDocument doc = new XmlDocument();
        doc.LoadXml(gml);

        IList<XmlNode> nlist = doc.GetElementsByTagName("River").Cast<XmlNode>().Where(n => n.ChildNodes.Count > 1).ToList();

        foreach (XmlNode n in nlist)
        {
            string riverId = n["River"].InnerText;
            string reachId = n["Reach"].InnerText;
            River r = null;

            if (rivers.ContainsKey(riverId))
            {
                r = rivers[riverId];
            }
            else
            {
                r = new River(riverId);
                rivers.Add(riverId, r);
            }

            if (!r.Reaches.ContainsKey(riverId))
            {
                List<XmlNode> crosssectionsOnReach = doc.GetElementsByTagName("XS").Cast<XmlNode>()
                    .Where(p => p["River"].InnerText == riverId && p["Reach"].InnerText == reachId).ToList();

                if (crosssectionsOnReach.Count > 0)
                {
                    Reach reach = new Reach(reachId);

                    List<Point> centerLinePoints = new List<Point>();

                    string centerLine = n["geometryProperty"]["gml:LineString"]["gml:coordinates"].InnerText;
                    string[] centerLineCoords = centerLine.Split(spaceDel, StringSplitOptions.RemoveEmptyEntries);

                    for (int j = 0; j < centerLineCoords.Length; j++)
                    {
                        string[] tCoords = centerLineCoords[j].Split(commaDel, StringSplitOptions.RemoveEmptyEntries);
                        centerLinePoints.Add(new Point(double.Parse(tCoords[0]), double.Parse(tCoords[1]), 0.0));
                    }

                    reach.CenterLine = centerLinePoints;

                    for (int i = 0; i < crosssectionsOnReach.Count; i++)
                    {
                        XmlNode xs = crosssectionsOnReach[i];

                        string cutLineCoordsText = xs["geometryProperty"]["gml:LineString"]["gml:coordinates"].InnerText;
                        string[] cutLineCoords = cutLineCoordsText.Split(spaceDel, StringSplitOptions.RemoveEmptyEntries);

                        XSection section = new XSection(xs["RiverStation"].InnerText);

                        for (int j = 0; j < cutLineCoords.Length; j++)
                        {
                            string[] tCoords = cutLineCoords[j].Split(commaDel, StringSplitOptions.RemoveEmptyEntries);
                            section.XSCutLine.Add(new Point(double.Parse(tCoords[0]), double.Parse(tCoords[1]), 0.0));
                        }
                        reach.XSections.Add(section.StationName.Trim(), section);
                    }

                    r.Reaches.Add(reachId, reach);
                }
            }
        }

        foreach (River r in rivers.Values)
        {
            foreach (Reach re in r.Reaches.Values)
            {
                re.CreateGISFeatures();
                re.CreateTriangulationForWaterSurface();
            }
        }
    }
示例#36
0
	public void SetRiverPath(River river)
	{
		if (!Collidable)
			return;
		
		if (!Rivers.Contains (river)) {
			Rivers.Add (river);
		}
	}
示例#37
0
	private void FindPathToWater(Tile tile, Direction direction, ref River river)
	{
		if (tile.Rivers.Contains (river))
			return;

		// check if there is already a river on this tile
		if (tile.Rivers.Count > 0)
			river.Intersections++;

		river.AddTile (tile);

		// get neighbors
		Tile left = GetLeft (tile);
		Tile right = GetRight (tile);
		Tile top = GetTop (tile);
		Tile bottom = GetBottom (tile);
		
		float leftValue = int.MaxValue;
		float rightValue = int.MaxValue;
		float topValue = int.MaxValue;
		float bottomValue = int.MaxValue;
		
		// query height values of neighbors
		if (left != null && left.GetRiverNeighborCount(river) < 2 && !river.Tiles.Contains(left)) 
			leftValue = left.HeightValue;
		if (right != null && right.GetRiverNeighborCount(river) < 2 && !river.Tiles.Contains(right)) 
			rightValue = right.HeightValue;
		if (top != null && top.GetRiverNeighborCount(river) < 2 && !river.Tiles.Contains(top)) 
			topValue = top.HeightValue;
		if (bottom != null && bottom.GetRiverNeighborCount(river) < 2 && !river.Tiles.Contains(bottom)) 
			bottomValue = bottom.HeightValue;
		
		// if neighbor is existing river that is not this one, flow into it
		if (bottom != null && bottom.Rivers.Count == 0 && !bottom.Collidable)
			bottomValue = 0;
		if (top != null && top.Rivers.Count == 0 && !top.Collidable)
			topValue = 0;
		if (left != null && left.Rivers.Count == 0 && !left.Collidable)
			leftValue = 0;
		if (right != null && right.Rivers.Count == 0 && !right.Collidable)
			rightValue = 0;
		
		// override flow direction if a tile is significantly lower
		if (direction == Direction.Left)
			if (Mathf.Abs (rightValue - leftValue) < 0.1f)
				rightValue = int.MaxValue;
		if (direction == Direction.Right)
			if (Mathf.Abs (rightValue - leftValue) < 0.1f)
				leftValue = int.MaxValue;
		if (direction == Direction.Top)
			if (Mathf.Abs (topValue - bottomValue) < 0.1f)
				bottomValue = int.MaxValue;
		if (direction == Direction.Bottom)
			if (Mathf.Abs (topValue - bottomValue) < 0.1f)
				topValue = int.MaxValue;
		
		// find mininum
		float min = Mathf.Min (Mathf.Min (Mathf.Min (leftValue, rightValue), topValue), bottomValue);
		
		// if no minimum found - exit
		if (min == int.MaxValue)
			return;
		
		//Move to next neighbor
		if (min == leftValue) {
			if (left != null && left.Collidable)
			{
				if (river.CurrentDirection != Direction.Left){
					river.TurnCount++;
					river.CurrentDirection = Direction.Left;
				}
				FindPathToWater (left, direction, ref river);
			}
		} else if (min == rightValue) {
			if (right != null && right.Collidable)
			{
				if (river.CurrentDirection != Direction.Right){
					river.TurnCount++;
					river.CurrentDirection = Direction.Right;
				}
				FindPathToWater (right, direction, ref river);
			}
		} else if (min == bottomValue) {
			if (bottom != null && bottom.Collidable)
			{
				if (river.CurrentDirection != Direction.Bottom){
					river.TurnCount++;
					river.CurrentDirection = Direction.Bottom;
				}
				FindPathToWater (bottom, direction, ref river);
			}
		} else if (min == topValue) {
			if (top != null && top.Collidable)
			{
				if (river.CurrentDirection != Direction.Top){
					river.TurnCount++;
					river.CurrentDirection = Direction.Top;
				}
				FindPathToWater (top, direction, ref river);
			}
		}
	}
示例#38
0
        public void SaveToDb(string name)
        {
            Console.WriteLine ("Saving to db");

            Map map = new Map () {
                Height = this.h,
                Width = this.w
            };

            GameState game = new GameState () {
                Name = name,
                Map = map,
            };

            string[] deleteTables = new string[] {
                "gamestate",
                "map",
                "hex",
                "hexresource",
                "map_cities",
                "map_rivers",
                "map_hexes",
                "hex_edges",
                "hex_effects",
                "kingdom"
            };

            foreach (string deleteTable in deleteTables)
                MySqlProvider.Provider.ExecuteNonQuery ("truncate " + deleteTable + ";");

            map.Game = game;
            map.Save ();
            game.Save ();

            RecordList<Hex> hexes = new RecordList<Hex> ();
            for (int x = 0; x < w; x++) {
                for (int y = 0; y < h; y++) {
                    Hex hex = new Hex ();
                    hex.EnsureId ();
                    hex.X = x;
                    hex.Y = y;
                    Color c = b.GetPixel (x, y);
                    if (c == blue)
                        hex.Terrain = TerrainType.Sea;
                    else if (c == white)
                        hex.Terrain = TerrainType.Mountains;
                    else if (c == darkGreen)
                        hex.Terrain = TerrainType.Forest;
                    else if (c == town)
                    {
                        hex.Terrain = TerrainType.Plains;
                    }
                    else
                        hex.Terrain = TerrainType.Plains;
                    hexes.Add (hex);
                    hexMap[x,y] = hex;
                }
            }

            //cities have to be done in a separate pass to account for growth.
            map.Hexes = hexes;
            map.EnsureMapIsBuilt (true);

            //check coastals
            foreach (Hex h in hexes)
                if (h.Terrain == TerrainType.Sea)
                    CheckCoastal (h);

            hexes.Save ();

            foreach (var kvp in riverPaths)
            {
                River r = new River();
                int z = 0;
                foreach(Point p in kvp.Value)
                {
                    r.Path.Add (new Triple<int> () {
                        X = p.X,
                        Y = p.Y,
                        Z = z++
                    });
                }
                r.Save ();
                r.Path.Save ();
                r.SaveRelations("Path");
                map.Rivers.Add (r);
            }

            map.SaveRelations ("Rivers");
            map.SaveRelations ("Hexes");
        }
示例#39
0
	// Dig river
	private void DigRiver(River river)
	{
		int counter = 0;
		
		// How wide are we digging this river?
		int size = UnityEngine.Random.Range(1,5);
		river.Length = river.Tiles.Count;  

		// randomize size change
		int two = river.Length / 2;
		int three = two / 2;
		int four = three / 2;
		int five = four / 2;
		
		int twomin = two / 3;
		int threemin = three / 3;
		int fourmin = four / 3;
		int fivemin = five / 3;

		// randomize lenght of each size
		int count1 = UnityEngine.Random.Range (fivemin, five);             
		if (size < 4) {
			count1 = 0;
		}
		int count2 = count1 + UnityEngine.Random.Range(fourmin, four); 
		if (size < 3) {
			count2 = 0;
			count1 = 0;
		}
		int count3 = count2 + UnityEngine.Random.Range(threemin, three); 
		if (size < 2) {
			count3 = 0;
			count2 = 0;
			count1 = 0;
		}
		int count4 = count3 + UnityEngine.Random.Range (twomin, two);  
		
		// Make sure we are not digging past the river path
		if (count4 > river.Length) {
			int extra = count4 - river.Length;
			while (extra > 0)
			{
				if (count1 > 0) { count1--; count2--; count3--; count4--; extra--; }
				else if (count2 > 0) { count2--; count3--; count4--; extra--; }
				else if (count3 > 0) { count3--; count4--; extra--; }
				else if (count4 > 0) { count4--; extra--; }
			}
		}

		// Dig it out
		for (int i = river.Tiles.Count - 1; i >= 0 ; i--)
		{
			Tile t = river.Tiles[i];

			if (counter < count1) {
				t.DigRiver (river, 4);				
			}
			else if (counter < count2) {
				t.DigRiver (river, 3);				
			} 
			else if (counter < count3) {
				t.DigRiver (river, 2);				
			} 
			else if ( counter < count4) {
				t.DigRiver (river, 1);
			}
			else {
				t.DigRiver(river, 0);
			}			
			counter++;			
		}
	}
示例#40
0
	// Dig river based on a parent river vein
	private void DigRiver(River river, River parent)
	{
		int intersectionID = 0;
		int intersectionSize = 0;

		// determine point of intersection
		for (int i = 0; i < river.Tiles.Count; i++) {
			Tile t1 = river.Tiles[i];
			for (int j = 0; j < parent.Tiles.Count; j++) {
				Tile t2 = parent.Tiles[j];
				if (t1 == t2)
				{
					intersectionID = i;
					intersectionSize = t2.RiverSize;
				}
			}
		}

		int counter = 0;
		int intersectionCount = river.Tiles.Count - intersectionID;
		int size = UnityEngine.Random.Range(intersectionSize, 5);
		river.Length = river.Tiles.Count;  

		// randomize size change
		int two = river.Length / 2;
		int three = two / 2;
		int four = three / 2;
		int five = four / 2;
		
		int twomin = two / 3;
		int threemin = three / 3;
		int fourmin = four / 3;
		int fivemin = five / 3;
		
		// randomize length of each size
		int count1 = UnityEngine.Random.Range (fivemin, five);  
		if (size < 4) {
			count1 = 0;
		}
		int count2 = count1 + UnityEngine.Random.Range(fourmin, four);  
		if (size < 3) {
			count2 = 0;
			count1 = 0;
		}
		int count3 = count2 + UnityEngine.Random.Range(threemin, three); 
		if (size < 2) {
			count3 = 0;
			count2 = 0;
			count1 = 0;
		}
		int count4 = count3 + UnityEngine.Random.Range (twomin, two); 

		// Make sure we are not digging past the river path
		if (count4 > river.Length) {
			int extra = count4 - river.Length;
			while (extra > 0)
			{
				if (count1 > 0) { count1--; count2--; count3--; count4--; extra--; }
				else if (count2 > 0) { count2--; count3--; count4--; extra--; }
				else if (count3 > 0) { count3--; count4--; extra--; }
				else if (count4 > 0) { count4--; extra--; }
			}
		}
				
		// adjust size of river at intersection point
		if (intersectionSize == 1) {
			count4 = intersectionCount;
			count1 = 0;
			count2 = 0;
			count3 = 0;
		} else if (intersectionSize == 2) {
			count3 = intersectionCount;		
			count1 = 0;
			count2 = 0;
		} else if (intersectionSize == 3) {
			count2 = intersectionCount;
			count1 = 0;
		} else if (intersectionSize == 4) {
			count1 = intersectionCount;
		} else {
			count1 = 0;
			count2 = 0;
			count3 = 0;
			count4 = 0;
		}

		// dig out the river
		for (int i = river.Tiles.Count - 1; i >= 0; i--) {

			Tile t = river.Tiles [i];

			if (counter < count1) {
				t.DigRiver (river, 4);				
			} else if (counter < count2) {
				t.DigRiver (river, 3);				
			} else if (counter < count3) {
				t.DigRiver (river, 2);				
			} 
			else if ( counter < count4) {
				t.DigRiver (river, 1);
			}
			else {
				t.DigRiver (river, 0);
			}			
			counter++;			
		}
	}
示例#41
0
	private void GenerateRivers()
	{
		int attempts = 0;
		int rivercount = RiverCount;
		Rivers = new List<River> ();

		// Generate some rivers
		while (rivercount > 0 && attempts < MaxRiverAttempts) {

			// Get a random tile
			int x = UnityEngine.Random.Range (0, Width);
			int y = UnityEngine.Random.Range (0, Height);			
			Tile tile = Tiles[x,y];

			// validate the tile
			if (!tile.Collidable) continue;
			if (tile.Rivers.Count > 0) continue;

			if (tile.HeightValue > MinRiverHeight)
			{				
				// Tile is good to start river from
				River river = new River(rivercount);

				// Figure out the direction this river will try to flow
				river.CurrentDirection = tile.GetLowestNeighbor (this);

				// Recursively find a path to water
				FindPathToWater(tile, river.CurrentDirection, ref river);

				// Validate the generated river 
				if (river.TurnCount < MinRiverTurns || river.Tiles.Count < MinRiverLength || river.Intersections > MaxRiverIntersections)
				{
					//Validation failed - remove this river
					for (int i = 0; i < river.Tiles.Count; i++)
					{
						Tile t = river.Tiles[i];
						t.Rivers.Remove (river);
					}
				}
				else if (river.Tiles.Count >= MinRiverLength)
				{
					//Validation passed - Add river to list
					Rivers.Add (river);
					tile.Rivers.Add (river);
					rivercount--;	
				}
			}		
			attempts++;
		}
	}
示例#42
0
	private void SetRiverTile(River river)
	{
		SetRiverPath (river);
		HeightType = HeightType.River;
		HeightValue = 0;
		Collidable = false;
	}
示例#43
0
    // This function got messy.  Sorry.
	public void DigRiver(River river, int size)
	{
		SetRiverTile (river);
		RiverSize = size;

		if (size == 1) {
			if (Bottom != null) 
			{ 
				Bottom.SetRiverTile (river);
				if (Bottom.Right != null) Bottom.Right.SetRiverTile (river);		
			}
			if (Right != null) Right.SetRiverTile (river);					
		}

		if (size == 2) {
			if (Bottom != null) { 
				Bottom.SetRiverTile (river);
				if (Bottom.Right != null) Bottom.Right.SetRiverTile (river);		
			}
			if (Right != null) {
				Right.SetRiverTile (river);
			}
			if (Top != null) {
				Top.SetRiverTile (river);
				if (Top.Left != null) Top.Left.SetRiverTile (river);
				if (Top.Right != null)Top.Right.SetRiverTile (river);
			}
			if (Left != null) {
				Left.SetRiverTile (river);
				if (Left.Bottom != null) Left.Bottom.SetRiverTile (river);
			}
		}

		if (size == 3) {
			if (Bottom != null) { 
				Bottom.SetRiverTile (river);
				if (Bottom.Right != null) Bottom.Right.SetRiverTile (river);	
				if (Bottom.Bottom != null)
				{
					Bottom.Bottom.SetRiverTile (river);
					if (Bottom.Bottom.Right != null) Bottom.Bottom.Right.SetRiverTile (river);
				}
			}
			if (Right != null) {
				Right.SetRiverTile (river);
				if (Right.Right != null) 
				{
					Right.Right.SetRiverTile (river);
					if (Right.Right.Bottom != null) Right.Right.Bottom.SetRiverTile (river);
				}
			}
			if (Top != null) {
				Top.SetRiverTile (river);
				if (Top.Left != null) Top.Left.SetRiverTile (river);
				if (Top.Right != null)Top.Right.SetRiverTile (river);
			}
			if (Left != null) {
				Left.SetRiverTile (river);
				if (Left.Bottom != null) Left.Bottom.SetRiverTile (river);
			}
		}

		if (size == 4) {

			if (Bottom != null) { 
				Bottom.SetRiverTile (river);
				if (Bottom.Right != null) Bottom.Right.SetRiverTile (river);	
				if (Bottom.Bottom != null)
				{
					Bottom.Bottom.SetRiverTile (river);
					if (Bottom.Bottom.Right != null) Bottom.Bottom.Right.SetRiverTile (river);
				}
			}
			if (Right != null) {
				Right.SetRiverTile (river);
				if (Right.Right != null) 
				{
					Right.Right.SetRiverTile (river);
					if (Right.Right.Bottom != null) Right.Right.Bottom.SetRiverTile (river);
				}
			}
			if (Top != null) {
				Top.SetRiverTile (river);
				if (Top.Right != null) { 
					Top.Right.SetRiverTile (river);
					if (Top.Right.Right != null) Top.Right.Right.SetRiverTile (river);
				}
				if (Top.Top != null)
				{
					Top.Top.SetRiverTile (river);
					if (Top.Top.Right != null) Top.Top.Right.SetRiverTile (river);
				}
			}
			if (Left != null) {
				Left.SetRiverTile (river);
				if (Left.Bottom != null) {
					Left.Bottom.SetRiverTile (river);
					if (Left.Bottom.Bottom != null) Left.Bottom.Bottom.SetRiverTile (river);
				}

				if (Left.Left != null) {
					Left.Left.SetRiverTile (river);
					if (Left.Left.Bottom != null) Left.Left.Bottom.SetRiverTile (river);
					if (Left.Left.Top != null) Left.Left.Top.SetRiverTile (river);
				}

				if (Left.Top != null)
				{
					Left.Top.SetRiverTile (river);
					if (Left.Top.Top != null) Left.Top.Top.SetRiverTile (river);
				}
			}
		}	
	}
        private bool FindRiversToJoin(List<River> rivers, out River r1, out River r2)
        {
            r1 = null;
            r2 = null;

            foreach (River r in rivers)
            {
                foreach (River rInner in rivers)
                {
                    if (ReferenceEquals(r, rInner))
                        continue;

                    if (r.IsConnected(rInner))
                    {
                        r1 = r;
                        r2 = rInner;
                        return true;
                    }
                }
            }

            return false;
        }
	private void generateRivers(){
		River river = new River ();
		river.pathShader = pathShader;
		river.riverTexture = riverTexture;
		river.terrainSize = m_terrainSize;
		river.heightMapSize = m_heightMapSize;
		river.waterlimit = waterLimit;
		river.drawRivers (rivercorners, corners.Count);
		
	}
        private void PatchRivers()
        {
            // fill base data
            List<FlowPoint> riverParts = new List<FlowPoint>();
         
            for (int x = 0; x < Width; x++)
            {
                for (int y = 0; y < Height; y++)
                {
                    MapCell.FlowDirectionType fd = this[x, y].WOfRiver;

                    if (fd != MapCell.FlowDirectionType.NoFlowdirection)
                        riverParts.Add(new FlowPoint(new HexPoint(x, y), fd));

                    fd = this[x, y].NEOfRiver;

                    if (fd != MapCell.FlowDirectionType.NoFlowdirection)
                        riverParts.Add(new FlowPoint(new HexPoint(x, y), fd));

                    fd = this[x, y].NWOfRiver;

                    if (fd != MapCell.FlowDirectionType.NoFlowdirection)
                        riverParts.Add(new FlowPoint(new HexPoint(x, y), fd));
                }
            }

            // create river graphs
            List<River> rivers = new List<River>();
            int riverNum = 0;

            foreach (FlowPoint fp in riverParts)
            {
                River r = rivers.FirstOrDefault(a => a.IsConnected(fp));

                if (r == null)
                {
                    River newRiver = new River("River " + (riverNum++));
                    newRiver.Points.Add(fp);
                    rivers.Add(newRiver);
                }
                else 
                {
                    r.Points.Add(fp);
                }
            }

            // join rivers
            bool riversNeedJoin = true;
            while (riversNeedJoin)
            {
                River r1, r2;
                riversNeedJoin = FindRiversToJoin(rivers, out r1, out r2 );

                if (riversNeedJoin)
                {
                    r1.Join(r2);
                    rivers.Remove(r2);
                }
            }

            // remove strange flows
            foreach (River r in rivers)
                r.Clean();

            //XmlWriterSettings settings = new XmlWriterSettings();
            //settings.Indent = true;

            //using (XmlWriter writer = XmlWriter.Create("river.xml", settings))
            //{
            //    IntermediateSerializer.Serialize(writer, rivers, null);
            //}

            for (int x = 0; x < Width; x++)
                for (int y = 0; y < Height; y++)
                    this[x, y].River = 0;

            foreach (River r in rivers)
            {
                if (r.Length > 1)
                {
                    foreach (FlowPoint fp in r.Points)
                        this[fp.Point].SetRiver(fp.Flow);
                }
            }
        }
示例#47
0
	public void DigRiver(River river, int size)
	{
		SetRiverTile (river);
		RiverSize = size;

		if (size == 1) {
			Bottom.SetRiverTile (river);
			Right.SetRiverTile (river);
			Bottom.Right.SetRiverTile (river);				
		}

		if (size == 2) {
			Bottom.SetRiverTile (river);
			Right.SetRiverTile (river);
			Bottom.Right.SetRiverTile (river);
			Top.SetRiverTile (river);
			Top.Left.SetRiverTile (river);
			Top.Right.SetRiverTile (river);
			Left.SetRiverTile (river);
			Left.Bottom.SetRiverTile (river);
		}

		if (size == 3) {
			Bottom.SetRiverTile (river);
			Right.SetRiverTile (river);
			Bottom.Right.SetRiverTile (river);
			Top.SetRiverTile (river);
			Top.Left.SetRiverTile (river);
			Top.Right.SetRiverTile (river);
			Left.SetRiverTile (river);
			Left.Bottom.SetRiverTile (river);
			Right.Right.SetRiverTile (river);
			Right.Right.Bottom.SetRiverTile (river);
			Bottom.Bottom.SetRiverTile (river);
			Bottom.Bottom.Right.SetRiverTile (river);
		}

		if (size == 4) {
			Bottom.SetRiverTile (river);
			Right.SetRiverTile (river);
			Bottom.Right.SetRiverTile (river);
			Top.SetRiverTile (river);
			Top.Right.SetRiverTile (river);
			Left.SetRiverTile (river);
			Left.Bottom.SetRiverTile (river);
			Right.Right.SetRiverTile (river);
			Right.Right.Bottom.SetRiverTile (river);
			Bottom.Bottom.SetRiverTile (river);
			Bottom.Bottom.Right.SetRiverTile (river);
			Left.Bottom.Bottom.SetRiverTile (river);
			Left.Left.Bottom.SetRiverTile (river);
			Left.Left.SetRiverTile (river);
			Left.Left.Top.SetRiverTile (river);
			Left.Top.SetRiverTile (river);
			Left.Top.Top.SetRiverTile (river);
			Top.Top.SetRiverTile (river);
			Top.Top.Right.SetRiverTile (river);
			Top.Right.Right.SetRiverTile (river);
		}	
	}