Inheritance: UnrealBuildTool.ModuleRules
 public LandscapePresenter(Landscape landscape)
 {
     this.original = landscape;
     if (landscape != null)
         Figures = landscape.Figures.Select(x => new FigurePresenter(x, landscape)).ToList();
     Update();
 }
Example #2
0
    // Use this for initialization
    void Start()
    {
        startY = transform.position.y;

        GameObject landscapeObj = GameObject.Find( "Landscape" );
        landscape = landscapeObj.GetComponent<Landscape>();
    }
		//---------------------------------------------------------------------

		internal void SetAll(Landscape landscape,
		                     Location  location,
		                     bool      isActive,
		                     uint      dataIndex)
		{
			this.Landscape = landscape;
			this.LocationAndIndex.Location = location;
			this.LocationAndIndex.Index    = dataIndex;
			this.isActive = isActive;
		}
Example #4
0
    // Use this for initialization
    void Start()
    {
        GameObject landscapeObj = GameObject.Find( "Landscape" );
        landscape = landscapeObj.GetComponent<Landscape>();

        megaTree = landscape.GetMegaTree();

        player = GameObject.Find( "Player" );

        cameraBlender = Camera.main.gameObject.GetComponent<CameraBlender>();
        cutawayCam = new CameraBlend();
    }
        public void Init()
        {
            species = Data.Species[0];
            expectedSender = null;
            deadCohorts = new List<ICohort>();

            bool[,] grid = new bool[,]{ {true} };
            DataGrid<bool> dataGrid = new DataGrid<bool>(grid);
            ILandscape landscape = new Landscape(dataGrid);
            activeSite = landscape[1,1];

            Cohort.DeathEvent += MySenescenceDeathMethod;
        }
Example #6
0
        private static World CreateWorld()
        {
            Random random = new Random();
              var content = new List<ActorWithLocationAndBehaviour>();

              var islandInAscii = @"
            WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW
            WWWWWWWWWPPPPPPPPPPPPPPPWWWWWWWWWW
            WWWWPPPPPPPPPPPPPPPPPPPPPPPPWWWWWW
            WWWPPPPPPPPPPPPPPPPPPPPPPPPPPPPWWW
            WWWPPPPPPPPPPPPPPPPPPPPPPPPPPPPWWW
            WWWPPPPPPPPPPPPPPPPPPPPPPPPPPPPWWW
            WWWPPPPPPPPPPPPPPPPPPPPPPPPPPPPWWW
            WWWPPPPPPPPPPPPPPPPPPPPPPPPPPPPWWW
            WWWWPPPPPPPPPPPPPPPPPPPPPPPPWWWWWW
            WWWWWWWWWPPPPPPPPPPPPPPPWWWWWWWWWW
            WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW";

              var landscapeArray = islandInAscii.Split('\n').Skip(1).Select(
            row => row.Trim().ToCharArray()).ToArray();

              Landscape[,] landscape = new Landscape[landscapeArray[0].Length, landscapeArray.Length];

              for (int i = 0; i < landscapeArray.Length; i++)
              {
            for (int j = 0; j < landscapeArray[0].Length; j++)
            {
              var location = new Location(j, i);

              switch (landscapeArray[i][j])
              {
            case 'W':
              landscape[j, i] = new Water();
              break;

            case 'P':
              landscape[j, i] = new Plain();
              break;
              }
            }
              }

              var person = new Person();
              var personLocation = new Location(landscape.GetLength(0)/2, landscape.GetLength(1)/2);
              content.Add(new ActorWithLocationAndBehaviour(
            person,
            personLocation,
            new Behaviour(new PersonScript(person, personLocation).CollectWood)));

              return new World(landscape, content);
        }
        public void Init()
        {
            abiebals = Data.Species["abiebals"];
            betualle = Data.Species["betualle"];

            bool[,] grid = new bool[,]{ {true} };
            DataGrid<bool> dataGrid = new DataGrid<bool>(grid);
            ILandscape landscape = new Landscape(dataGrid);
            activeSite = landscape[1,1];

            disturbance = new MockSpeciesCohortsDisturbance();
            disturbance.CurrentSite = activeSite;
            deadCohorts = new Dictionary<ISpecies, List<ushort>>();

            Cohort.DeathEvent += MyCohortDiedMethod;
        }
        }         // GenerateUTextureCoordinates()

        #endregion

        #region GenerateTunnelsAndLandscapeObjects
        private void GenerateTunnelsAndLandscapeObjects(
            List <TrackData.RoadHelper> roadHelpers,
            List <TrackData.NeutralObject> neutralObjects,
            Landscape landscape)
        {
            #region Find out where the tunnels are
            // Go through all tunnel helpers along the road,
            // everything close enough (<25) is interessting for us.
            int helperStartedNum = -1;
            TrackData.RoadHelper.HelperType remType =
                TrackData.RoadHelper.HelperType.Reset;
            for (int num = 0; num < points.Count; num++)
            {
                Vector3 pos = points[num].pos;
                foreach (TrackData.RoadHelper roadHelper in roadHelpers)
                {
                    float dist = Vector3.Distance(roadHelper.pos, pos);
                    if (dist < 25.0f)
                    {
                        if (helperStartedNum >= 0)
                        {
                            helperPositions.Add(new RoadHelperPosition(
                                                    remType, helperStartedNum, num));
                            // Reset?
                            if (roadHelper.type == TrackData.RoadHelper.HelperType.Reset)
                            {
                                helperStartedNum = -1;
                            }
                            else
                            {
                                // Start new part
                                helperStartedNum = num;
                                remType          = roadHelper.type;
                            }                     // else
                        }                         // if (helperStartedNum)
                        else
                        {
                            helperStartedNum = num;
                            remType          = roadHelper.type;
                        }                         // else

                        // Remove this roadHelper (don't use it again)!
                        roadHelpers.Remove(roadHelper);
                        break;
                    }     // if (dist)
                }         // foreach (roadHelper)
            }             // for (num)

            // Still a helper open? Then close it close before the end!
            if (helperStartedNum > 0)
            {
                helperPositions.Add(new RoadHelperPosition(
                                        remType, helperStartedNum, points.Count - 3));
            }
            #endregion

            #region Copy over neutral objects for landscape rendering
            if (landscape != null)
            {
                for (int num = 0; num < neutralObjects.Count; num++)
                {
                    TrackData.NeutralObject obj = neutralObjects[num];
                    landscape.AddObjectToRender(obj.modelName, obj.matrix, false);
                } // for (num)
            }     // if (landscape)
            #endregion
        }         // GenerateTunnelsAndLandscapeObjects()
Example #9
0
 /// <summary>
 /// Метод изменяет текущую скорость и область видимости Юнита в зависимости от текущего местоположения, переданного в метод.
 /// </summary>
 /// <param name="land">Местоположение (Местность)</param>
 internal void SetCurrent(Landscape land)
 {
     Properties.CurSpeed = Properties.Speed * land.Passability();
     Properties.CurVisible = Properties.Visible * land.Visibility();
 }
Example #10
0
        /*now done in track class!
         * /// <summary>
         * /// Matrix list for each of the holder pile objects we have to render.
         * /// </summary>
         * List<Matrix> holderPileMatrices = new List<Matrix>();
         */
        #endregion

        #region Constructor
        /// <summary>
        /// Create guard rail
        /// </summary>
        /// <param name="points">Points of the road itself</param>
        /// <param name="mode">Mode, left or right</param>
        /// <param name="landscape">Landscape</param>
        public GuardRail(List <TrackVertex> points, Modes mode,
                         Landscape landscape)
        {
            #region Generate guardrail points
            // First generate a list of points at the side of the road where
            // we are going to generate all the guard rail vertices.
            // Note: We use only half as much points as points provides!
            railPoints = new TrackVertex[points.Count / 2 + 1];
            for (int num = 0; num < railPoints.Length; num++)
            {
                // Make sure we have a closed line, we might have to skip the
                // last points entry because we devided through 2.
                int pointNum = num * 2;
                if (pointNum >= points.Count - 1)
                {
                    pointNum = points.Count - 1;
                }

                // Just copy the points over and manipulate the position and the
                // right vector depending on which side of the guard rail we are
                // going to generate here.
                if (mode == Modes.Left)
                {
                    railPoints[num] = points[pointNum].LeftTrackVertex;
                    // Invert the direction and right vector for the left side
                    // This makes everything point in the other road direction!
                    railPoints[num].right = -railPoints[num].right;
                    railPoints[num].dir   = -railPoints[num].dir;
                    // Move it a little inside the road
                    railPoints[num].pos -=
                        railPoints[num].right * InsideRoadDistance;
                }
                else
                {
                    railPoints[num] = points[pointNum].RightTrackVertex;
                    // Move it a little inside the road
                    railPoints[num].pos -=
                        railPoints[num].right * InsideRoadDistance;
                }
            }
            #endregion

            #region Generate vertex buffer
            railVertices =
                new TangentVertex[railPoints.Length * GuardRailVertices.Length];

            // Current texture coordinate for the guardrail in our current direction.
            float uTexValue     = 0.5f;
            float lastHolderGap = 0;//HolderGap;
            for (int num = 0; num < railPoints.Length; num++)
            {
                // The unit vectors for our local point space
                Vector3 right = railPoints[num].right;
                Vector3 dir   = railPoints[num].dir;
                Vector3 up    = railPoints[num].up;

                // Create the coordinate system for the current point by the 3 unit
                // vectors.
                Matrix pointSpace = Matrix.Identity;
                pointSpace.M11 = right.X;
                pointSpace.M12 = right.Y;
                pointSpace.M13 = right.Z;
                pointSpace.M21 = dir.X;
                pointSpace.M22 = dir.Y;
                pointSpace.M23 = dir.Z;
                pointSpace.M31 = up.X;
                pointSpace.M32 = up.Y;
                pointSpace.M33 = up.Z;

                Vector3 localPos = railPoints[num].pos;
                // Adjust the position for the guardrail, put it up a little.
                localPos += up * GuardRailHeight;

                // Set the beginning- or ending point for the guardrail around the
                // current spline position
                for (int i = 0; i < GuardRailVertices.Length; i++)
                {
                    // Transform each of our guardrail points by our local point space
                    // and translate it to our current position.
                    Vector3 pos = Vector3.Transform(
                        GuardRailVertices[i].pos * CorrectionScale,
                        pointSpace * Matrix.CreateTranslation(localPos));
                    // Also transform our normal and tangent data
                    Vector3 normal = Vector3.TransformNormal(
                        // Left side needs inverted normals (side is inverted)
                        (mode == Modes.Left ? -1 : 1) *
                        GuardRailVertices[i].normal,
                        pointSpace);
                    Vector3 tangent = Vector3.TransformNormal(
                        -GuardRailVertices[i].tangent,
                        //GuardRailVertices[i].normal,
                        //new Vector3(0, 0, -1),
                        pointSpace);

                    // Store vertex
                    railVertices[num * GuardRailVertices.Length + i] =
                        new TangentVertex(pos,
                                          uTexValue, GuardRailVertices[i].V,
                                          normal, tangent);
                }

                // Distance of the current position to the next position
                float distance = Vector3.Distance(
                    railPoints[(num + 1) % railPoints.Length].pos, railPoints[num].pos);

                // Uniform calculation of the texture coordinates for the guardrail,
                // so it doesn't matter if there is a gap of 2 or 200 m
                // -> through "1 / HolderGap" we guarantee that the drilling
                //        (from the texture) is always set in the front of the pile,
                //        no matter which holder gap is set
                // Note: Only display a holder for every 3 texture loops.
                uTexValue += (1 / HolderGap) * distance * 2.0f;

                // Have we reach or go over the holder gap ?
                if (lastHolderGap - distance <= 0)
                {
                    // Catmull interpolation, instead the linear interpolation, for a
                    // better position calculation, especially in curves
                    Vector3 p1 =
                        railPoints[num - 1 < 0 ? railPoints.Length - 1 : num - 1].pos;
                    Vector3 p2 = railPoints[num].pos;
                    Vector3 p3 = railPoints[(num + 1) % railPoints.Length].pos;
                    Vector3 p4 = railPoints[(num + 2) % railPoints.Length].pos;

                    Vector3 holderPoint = Vector3.CatmullRom(p1, p2, p3, p4,
                                                             lastHolderGap / distance);

                    // Store the calculated render matrix for this holder pile object
                    if (landscape != null &&
                        // Completely ignore all guard rails for low detail
                        // to save performance (few thousand objects per track less)
                        BaseGame.HighDetail)
                    {
                        landscape.AddObjectToRender(
                            "GuardRailHolder",
                            // Fix scaling a little
                            //Matrix.CreateScale(0.9f) *
                            Matrix.CreateScale(1.125f) *
                            // First the translation to get the pile to the back of the
                            // guardrail and not in the middle
                            Matrix.CreateTranslation(HolderPileCorrectionVector) *
                            // the ordinary transformation to the current point space
                            pointSpace *
                            // at least we calculate to correct position where the pile
                            // reaches exactly the holder gap
                            Matrix.CreateTranslation(holderPoint),
                            // Optimize performance: Set this to false,
                            // but then we won't have shadows for the holder piles.
                            false);//true);
                    }
                    // We have just set a pile, the next pile will be set after
                    // reaching the next holder gap.
                    lastHolderGap += HolderGap;
                }

                // The distance we have to cover until the next position.
                // We subtract our current distance from the remaining gap distance,
                // which will then be checked in the next loop.
                lastHolderGap -= distance;
            }

            // Create the vertex buffer from our vertices.
            //railVb = new VertexBuffer(
            //    BaseGame.Device,
            //    typeof(TangentVertex),
            //    railVertices.Length,
            //    ResourceUsage.WriteOnly,
            //    ResourceManagementMode.Automatic);
            railVb = new VertexBuffer(
                BaseGame.Device,
                typeof(TangentVertex),
                railVertices.Length,
                BufferUsage.WriteOnly);
            railVb.SetData(railVertices);
            #endregion

            #region GenerateIndexBuffer
            // Count of quads (polygons) which creates the current guardrail segment
            int   quadPolysPerStrip = GuardRailVertices.Length - 1;
            int[] indices           =
                new int[(2 * 3 * quadPolysPerStrip) * (railPoints.Length - 1)];
            // Current vertex index
            int vertexIndex = 0;
            // Helper variable, current index of the indices list
            int indicesIndex = 0;
            for (int num = 0; num < railPoints.Length - 1; num++)
            {
                // Set all quads of the guardrail
                for (int j = 0; j < quadPolysPerStrip; j++)
                {
                    indicesIndex = 3 * 2 * (num * quadPolysPerStrip + j);

                    // 1. Polygon
                    indices[indicesIndex]     = vertexIndex + j;
                    indices[indicesIndex + 1] = vertexIndex + 1 + j;
                    indices[indicesIndex + 2] =
                        vertexIndex + 1 + GuardRailVertices.Length + j;

                    // 2. Polygon
                    indices[indicesIndex + 3] = indices[indicesIndex + 2];
                    indices[indicesIndex + 4] =
                        vertexIndex + GuardRailVertices.Length + j;
                    indices[indicesIndex + 5] = indices[indicesIndex];
                }

                vertexIndex += GuardRailVertices.Length;
            }

            // Create the index buffer from our indices.
            //railIb = new IndexBuffer(
            //    BaseGame.Device,
            //    typeof(int),
            //    indices.Length,
            //    ResourceUsage.WriteOnly,
            //    ResourceManagementMode.Automatic);
            railIb = new IndexBuffer(
                BaseGame.Device,
                typeof(int),
                indices.Length,
                BufferUsage.WriteOnly);
            railIb.SetData(indices);
            #endregion
        }
Example #11
0
 /// <summary>
 /// Mark a landscape to be destroyed
 /// </summary>
 /// <param name="land"></param>
 public static void Destroy(Landscape land)
 {
     land.gameObject.SetActive(false);
     landscapeToDestroy.Enqueue(land);
 }
Example #12
0
 /// <summary>
 /// Возвращает время заданного пути по конкретной области.
 /// </summary>
 /// <param name="land">Местоположение (Местность)</param>
 /// <param name="WayBegin">Начальная точка</param>
 /// <param name="WayEnd">Конечная точка</param>
 /// <returns>Время</returns>
 public double GetPathTime(Landscape land, Point WayBegin, Point WayEnd)
 {
     //SetCurrent(land);
     //return WalkTime(WayBegin, WayEnd);
     double leng = Point.Length(WayBegin, WayEnd);
     return leng / (Properties.Speed * land.Passability());
 }
Example #13
0
        }         // TrackLine(inputPointsFromColladaTrack)

        #endregion

        #region Load
        /// <summary>
        /// Load
        /// </summary>
        /// <param name="inputPoints">Input points</param>
        /// <param name="widthHelpers">Width helpers</param>
        /// <param name="roadHelpers">Road helpers</param>
        /// <param name="neutralObjects">Neutral objects</param>
        /// <param name="landscape">Landscape</param>
        protected void Load(Vector3[] inputPoints,
                            List <TrackData.WidthHelper> widthHelpers,
                            List <TrackData.RoadHelper> roadHelpers,
                            List <TrackData.NeutralObject> neutralObjects,
                            Landscape landscape)
        {
            #region Kill all previously loaded data
            points.Clear();
            helperPositions.Clear();

            // Kill all loaded objects
            if (landscape != null)
            {
                landscape.KillAllLoadedObjects();
            }
            #endregion

            #region Make sure we got valid data
            if (inputPoints == null ||
                inputPoints.Length < 3)
            {
                throw new ArgumentException("inputPoints is invalid, we need at " +
                                            "least 3 valid input points to generate a TrackLine.");
            }
            #endregion

            #region Check if all points are ABOVE the landscape
            if (landscape != null)
            {
                // Go through all spline points
                for (int num = 0; num < inputPoints.Length; num++)
                {
                    // Get landscape height here
                    float landscapeHeight = landscape.GetMapHeight(
                        inputPoints[num].X, inputPoints[num].Y) +
                                            // add little to fix ground errors
                                            MinimumLandscapeDistance * 2.25f;

                    // And make sure we are always above it!
                    if (inputPoints[num].Z < landscapeHeight)
                    {
                        inputPoints[num].Z = landscapeHeight;
                    }
                }                 // for (num)

                // Second pass, check 24 interpolation points between all inputPoints
                for (int num = 0; num < inputPoints.Length; num++)
                {
                    for (int iter = 1; iter < 25; iter++)
                    {
                        float iterPercent = iter / 25.0f;

                        float iterHeight = inputPoints[num].Z * (1 - iterPercent) +
                                           inputPoints[(num + 1) % inputPoints.Length].Z * iterPercent;

                        // Check 2x2 points (in all directions) to make sure
                        // we don't go through the landscape at the sides
                        for (int x = 0; x < 2; x++)
                        {
                            for (int y = 0; y < 2; y++)
                            {
                                // Also get height at middle to next pos
                                float landscapeHeight = landscape.GetMapHeight(
                                    -5.0f + 10.0f * x +
                                    inputPoints[num].X * (1 - iterPercent) +
                                    inputPoints[(num + 1) % inputPoints.Length].X * iterPercent,
                                    -5.0f + 10.0f * y +
                                    inputPoints[num].Y * (1 - iterPercent) +
                                    inputPoints[(num + 1) % inputPoints.Length].Y * iterPercent) +
                                                                                         // add little to fix ground errors
                                                        MinimumLandscapeDistance * 1.6f; // 1.5f;//1.25f;

                                // Increase both positions if this point is under the landscape
                                if (iterHeight < landscapeHeight)
                                {
                                    float increaseHeight = landscapeHeight - iterHeight;
                                    inputPoints[num].Z += increaseHeight;
                                    inputPoints[(num + 1) % inputPoints.Length].Z +=
                                        increaseHeight;
                                }                         // if (iterHeight)
                            }                             // for
                        }
                    } // for for (iter)
                }
            }             // if (landscape)
            //Log.Write("Input points: " + StringHelper.WriteArrayData(inputPoints));
            #endregion

            #region Search for any loopings indicated by 2 points above each other
            // Go through all spline points (ignore first and last 3, this
            // makes it easier to remove points and add new ones).
            for (int num = 1; num < inputPoints.Length - 3; num++)
            {
                // X/Y distance has to be 4 times smaller than Z distance
                Vector3 distVec = inputPoints[num + 1] - inputPoints[num];
                float   xyDist  = (float)Math.Sqrt(
                    distVec.X * distVec.X + distVec.Y * distVec.Y);
                float zDist = Math.Abs(distVec.Z);
                // Also check if next point is down again.
                Vector3 distVec2 = inputPoints[num + 2] - inputPoints[num + 1];
                if (zDist / 2 > xyDist &&
                    Math.Abs(distVec.Z + distVec2.Z) < zDist / 2)
                {
                    // Find out which direction we are going
                    Vector3 dir = inputPoints[num] - inputPoints[num - 1];
                    dir.Normalize();
                    Vector3 upVec    = new Vector3(0, 0, 1);
                    Vector3 rightVec = Vector3.Cross(dir, upVec);
                    // Matrix build helper matrix to rotate our looping points
                    Matrix rotMatrix = new Matrix(
                        rightVec.X, rightVec.Y, rightVec.Z, 0,
                        dir.X, dir.Y, dir.Z, 0,
                        upVec.X, upVec.Y, upVec.Z, 0,
                        0, 0, 0, 1);

                    // Ok do a looping with zDist as height.
                    // Start with the current point, loop around and end with the
                    // point after the looping. We will remove the current and the
                    // next 2 points, but add 9 new points instead for our smooth loop.
                    // See LoopingPoints for the looping itself.
                    Vector3 startLoopPos = inputPoints[num];
                    Vector3 endLoopPos   = inputPoints[num + 2];

                    // Insert 7 new points (9 new points, but we reuse
                    // start, middle and end points which are num, num+1 and num+2,
                    // plus an additional point after the looping to keep the road
                    // straight!)
                    Vector3[] remInputPoints = (Vector3[])inputPoints.Clone();
                    inputPoints = new Vector3[inputPoints.Length + 7];
                    // Copy everything over
                    for (int copyNum = 0; copyNum < remInputPoints.Length; copyNum++)
                    {
                        if (copyNum < num)
                        {
                            inputPoints[copyNum] = remInputPoints[copyNum];
                        }
                        else
                        {
                            inputPoints[copyNum + 7] = remInputPoints[copyNum];
                        }
                    }

                    // Ok, now we can add our loop
                    for (int loopNum = 0; loopNum < LoopingPoints.Length; loopNum++)
                    {
                        // Interpolate between start and end pos to land at the end pos!
                        float loopPercent = loopNum / (float)(LoopingPoints.Length - 1);
                        inputPoints[num + loopNum] =
                            startLoopPos * (1 - loopPercent) +
                            endLoopPos * loopPercent +
                            zDist * Vector3.Transform(LoopingPoints[loopNum], rotMatrix);
                    }                     // for (loopNum)

                    // Add extra point to keep the road straight
                    Vector3 newRoadDir =
                        inputPoints[num + 10] - inputPoints[num + 8];
                    // Don't go more than zDist * 2 units away!
                    if (newRoadDir.Length() > zDist * 2)
                    {
                        newRoadDir.Normalize();
                        newRoadDir           = newRoadDir * zDist;
                        inputPoints[num + 9] = inputPoints[num + 8] + newRoadDir;
                    }                     // if (newRoadDir.Length)
                    else
                    {
                        // Just add an interpolation point
                        inputPoints[num + 9] =
                            (inputPoints[num + 8] + inputPoints[num + 10]) / 2.0f;
                    }

                    // Advance 10 points until we check for the next loop
                    num += 10;

                    // That's it, good work everyone ^^
                }         // if (zDist)
            }             // for (num)
            #endregion

            #region Generate all points with help of catmull rom splines
            // Generate all points with help of catmull rom splines
            for (int num = 0; num < inputPoints.Length; num++)
            {
                // Get the 4 required points for the catmull rom spline
                Vector3 p1 = inputPoints[num - 1 < 0 ? inputPoints.Length - 1 : num - 1];
                Vector3 p2 = inputPoints[num];
                Vector3 p3 = inputPoints[(num + 1) % inputPoints.Length];
                Vector3 p4 = inputPoints[(num + 2) % inputPoints.Length];

                // Calculate number of iterations we use here based
                // on the distance of the 2 points we generate new points from.
                float distance           = Vector3.Distance(p2, p3);
                int   numberOfIterations =
                    (int)(NumberOfIterationsPer100Meters * (distance / 100.0f));
                if (numberOfIterations <= 0)
                {
                    numberOfIterations = 1;
                }

                Vector3 lastPos = p1;
                for (int iter = 0; iter < numberOfIterations; iter++)
                {
                    TrackVertex newVertex = new TrackVertex(
                        Vector3.CatmullRom(p1, p2, p3, p4,
                                           iter / (float)numberOfIterations));

                    lastPos = newVertex.pos;

                    points.Add(newVertex);
                }         // for (iter)
            }             // for (num)
            #endregion

            #region Generate up vectors, very important for our road building
            // Pre up vectors are used to first generate all optimal up vectors
            // for the track, but this is not useful for driving because we need
            // the road to point up always except for loopings.
            List <Vector3> preUpVectors = new List <Vector3>();

            // Now generate all up vectors, first pass does optimal up vectors.
            Vector3 defaultUpVec = new Vector3(0, 0, 1);
            Vector3 lastUpVec    = defaultUpVec;
            for (int num = 0; num < points.Count; num++)
            {
                // Get direction we are driving in at this point,
                // interpolate with help of last and next points.
                Vector3 dir = points[(num + 1) % points.Count].pos -
                              points[num - 1 < 0 ? points.Count - 1 : num - 1].pos;
                dir.Normalize();

                // Now calculate the optimal up vector for this point
                Vector3 middlePoint = (points[(num + 1) % points.Count].pos +
                                       points[num - 1 < 0 ? points.Count - 1 : num - 1].pos) / 2.0f;
                Vector3 optimalUpVector = middlePoint - points[num].pos;
                if (optimalUpVector.Length() < 0.0001f)
                {
                    optimalUpVector = lastUpVec;
                }
                optimalUpVector.Normalize();

                // Store the optimalUpVectors in the preUpVectors list
                preUpVectors.Add(optimalUpVector);

                // Also save dir vector
                points[num].dir = dir;

                // And remember the last upVec in case the road is going straight ahead
                lastUpVec = optimalUpVector;
            }             // for (num)

            // Interpolate the first up vector for a smoother road at the start pos
            preUpVectors[0] = preUpVectors[preUpVectors.Count - 1] + preUpVectors[1];
            preUpVectors[0].Normalize();
            #endregion

            #region Interpolate the up vectors and also add the dir and right vectors
            // Second pass, interpolated precalced values and apply our logic :)
            //preUpVectors[0] =
            lastUpVec = Vector3.Lerp(defaultUpVec, preUpVectors[0],
                                     1.5f * CurveFactor * UpFactorCorrector);
            //lastUpVec = preUpVectors[0];
            Vector3 lastUpVecUnmodified = lastUpVec;            // defaultUpVec;
            Vector3 lastRightVec        = Vector3.Zero;
            for (int num = 0; num < points.Count; num++)
            {
                // Grab dir vector (could be calculated here too)
                Vector3 dir = points[num].dir;

                // First of all interpolate the preUpVectors
                Vector3 upVec =
                    //single input: preUpVectors[num];
                    Vector3.Zero;
                for (int smoothNum = -NumberOfUpSmoothValues / 2;
                     smoothNum <= NumberOfUpSmoothValues / 2; smoothNum++)
                {
                    upVec +=
                        preUpVectors[(num + points.Count + smoothNum) % points.Count];
                }
                upVec.Normalize();

                // Find out if this road piece is upside down and if we are
                // moving up or down. This is VERY important for catching loopings.
                bool upsideDown = upVec.Z < -0.25f &&
                                  lastUpVecUnmodified.Z < -0.05f;
                bool movingUp   = dir.Z > 0.75f;
                bool movingDown = dir.Z < -0.75f;

                //float changeAngle2 =
                //  GetAngleBetweenVectors(lastUpVec, upVec);
                //if (num < 100)
                //  Log.Write("changeAngel2=" + changeAngle2);

                // Mix in the last vector to make curves weaker
                upVec = Vector3.Lerp(lastUpVec, upVec, CurveFactor);
                upVec.Normalize();
                // Store the last value to check for loopings.
                lastUpVecUnmodified = upVec;

                // Don't mix in default up if we head up or are upside down!
                // Its very useful to know if we move up or down to fix the
                // problematic areas at loopings by pointing stuff correct right away.
                if (movingUp)
                {
                    lastUpVec = Vector3.Lerp(upVec, -defaultUpVec, UpFactorCorrector);
                }
                else if (movingDown)
                {
                    lastUpVec = Vector3.Lerp(upVec, defaultUpVec, UpFactorCorrector);
                }
                else if (upsideDown)
                {
                    lastUpVec = Vector3.Lerp(upVec, -defaultUpVec, UpFactorCorrector);
                }
                else
                {
                    lastUpVec = Vector3.Lerp(upVec, defaultUpVec, UpFactorCorrector);
                }

                // If we are very close to the ground, make the road point up more!
                if (                //upsideDown == false &&
                    landscape != null)
                {
                    // Get landscape height here
                    float landscapeHeight = landscape.GetMapHeight(
                        points[num].pos.X, points[num].pos.Y);

                    // If point is close to the landscape, let everything point up more
                    if (points[num].pos.Z - landscapeHeight <
                        MinimumLandscapeDistance * 4)
                    {
                        lastUpVec = Vector3.Lerp(upVec, defaultUpVec,
                                                 1.75f * UpFactorCorrector);
                    }
                }                 // if (upsideDown == false &&)

                // And finally calculate rightVectors with just a cross product.
                // Used to render the track later.
                Vector3 rightVec = Vector3.Cross(dir, upVec);
                rightVec.Normalize();
                points[num].right = rightVec;

                //*tst
                // Recalculate up vector with help of right and dir.
                // This makes the up vector to always point up 90 degrees.
                upVec = Vector3.Cross(rightVec, dir);
                upVec.Normalize();
                points[num].up = upVec;
                //*/

                //// Make sure we never rotate the road more than a few degrees
                //if (lastRightVec.Length() > 0)
                //{
                //  float changeAngle =
                //    GetAngleBetweenVectors(lastRightVec, rightVec);
                //  if (num < 100)
                //    Log.Write("changeAngel=" + changeAngle);
                //} // if (lastRightVec.Length)

                //// Remember right vec for comparison in the next frame.
                //lastRightVec = rightVec;
            }             // for (num)
            #endregion

            #region Smooth up vectors!
            lastUpVec = points[0].up;
            for (int num = 0; num < points.Count; num++)
            {
                preUpVectors[num] = points[num].up;
            }
            for (int num = 0; num < points.Count; num++)
            {
                // Interpolate up vectors again
                Vector3 upVec = Vector3.Zero;
                for (int smoothNum = -NumberOfUpSmoothValues;
                     smoothNum <= NumberOfUpSmoothValues; smoothNum++)
                {
                    upVec +=
                        preUpVectors[(num + points.Count + smoothNum) % points.Count];
                }                 // for (smoothNum)
                upVec.Normalize();
                points[num].up = upVec;

                // Also rebuild right vector
                Vector3 dir = points[num].dir;
                points[num].right = Vector3.Cross(dir, upVec);

                /*suxx
                 * // Grab dir and up vector
                 * Vector3 dir = points[num].dir;
                 * Vector3 upVec = points[num].up;
                 * /*suxx
                 * // Compare with previous up vector
                 * float changeAngle =
                 *      GetAngleBetweenVectors(lastUpVec, upVec);
                 * /*tst
                 * bool upsideDown = upVec.Z < -0.25f &&
                 *      lastUpVecUnmodified.Z < -0.05f;
                 * bool movingUp = dir.Z > 0.75f;
                 * bool movingDown = dir.Z < -0.75f;
                 * lastUpVecUnmodified = upVec;
                 * if (Math.Abs(changeAngle) > 0.02f &&
                 *      upsideDown == false &&
                 *      movingUp == false &&
                 *      movingDown == false)
                 * {
                 *      points[num].up = Vector3.SmoothStep(lastUpVec, upVec, 0.33f);//.25f);
                 *      // Also rebuild right vector
                 *      points[num].right = Vector3.Cross(dir, points[num].up);
                 * } // if (Math.Abs)
                 */
                /*suxx
                 * //if (Math.Abs(changeAngle) > 0.02f)
                 * {
                 *      points[num].up = Vector3.SmoothStep(lastUpVec, upVec, 0.05f);//.25f);
                 *      // Also rebuild right vector
                 *      points[num].right = Vector3.Cross(dir, points[num].up);
                 * } // if (Math.Abs)
                 * lastUpVec = upVec;
                 */
                //if (num < 100)
                //  Log.Write("changeAngel=" + changeAngle);
            }             // for (num)
            #endregion

            AdjustRoadWidths(widthHelpers);

            GenerateUTextureCoordinates();

            GenerateTunnelsAndLandscapeObjects(
                roadHelpers, neutralObjects, landscape);
        }         // Load(inputPoints, widthHelpers, roadHelpers)
Example #14
0
 public AllTreesEnumerator(Landscape landscape)
 {
     this.landscape = landscape;
     this.Reset();
 }
Example #15
0
 /// <summary>
 /// Dispose
 /// </summary>
 /// <param name="someObject">Some object</param>
 public static void Dispose(ref Landscape someObject)
 {
     if (someObject != null)
         someObject.Dispose();
     someObject = null;
 }
 public void SetChunkData(ChunkData chunkData)
 {
     _landscape = new Landscape(chunkData);
 }
        /// <summary>
        /// Create track columns
        /// </summary>
        /// <param name="points">Points</param>
        /// <param name="landscape">Landscape for getting the ground height</param>
        public TrackColumns(List <TrackVertex> points, Landscape landscape)
        {
            if (landscape == null)
            {
                return;
            }

            #region Find out column positions
            float         lastColumnsDistance     = ColumnsDistance;
            List <Matrix> columnPointSpacesTop    = new List <Matrix>();
            List <Matrix> columnPointSpacesBottom = new List <Matrix>();
            for (int num = 0; num < points.Count; num++)
            {
                // Distance of the current position to the next position
                float distance = Vector3.Distance(
                    points[(num + 1) % points.Count].pos, points[num].pos);

                // Uniform calculation of the distance for the columns,
                // so it doesn't matter if there is a gap of 2 or 200 m
                // Have we reach or go over the ColumnsDistance?
                if (lastColumnsDistance - distance <= 0)
                {
                    // Catmull interpolation, instead the linear interpolation, for a
                    // better position calculation, especially in curves
                    Vector3 p1 = points[num - 1 < 0 ? points.Count - 1 : num - 1].pos;
                    Vector3 p2 = points[num].pos;
                    Vector3 p3 = points[(num + 1) % points.Count].pos;
                    Vector3 p4 = points[(num + 2) % points.Count].pos;

                    Vector3 holderPoint = Vector3.CatmullRom(p1, p2, p3, p4,
                                                             lastColumnsDistance / distance);

                    // Just find out how much this point is pointing up
                    float draft = Vector3.Dot(points[num].up, new Vector3(0, 0, 1));
                    // And don't add if height is too small!
                    float columnHeight = holderPoint.Z -
                                         landscape.GetMapHeight(holderPoint.X, holderPoint.Y);

                    // Store the position for this holder
                    if (draft > 0.3f &&//< 0 MaxColumnGenerationAngel &&
                        columnHeight > MinimumColumnHeight)
                    {
                        columnPositions.Add(holderPoint);

                        // The unit vectors for our local point space
                        Vector3 right = points[num].right;
                        Vector3 dir   = points[num].dir;
                        Vector3 up    = points[num].up;

                        // Create the coordinate system for the current point by the 3
                        // unit vectors.
                        Matrix pointSpace = Matrix.Identity;
                        pointSpace.M11 = right.X;
                        pointSpace.M12 = right.Y;
                        pointSpace.M13 = right.Z;
                        pointSpace.M21 = dir.X;
                        pointSpace.M22 = dir.Y;
                        pointSpace.M23 = dir.Z;
                        pointSpace.M31 = up.X;
                        pointSpace.M32 = up.Y;
                        pointSpace.M33 = up.Z;

                        // Remember point space
                        columnPointSpacesTop.Add(pointSpace);

                        // Same for bottom, but don't use up vector (let it stay default)
                        pointSpace = Matrix.Identity;
                        Vector3 upVector = new Vector3(0, 0, 1);
                        // Rebuild right vector (to make it 90 degree to our up vector)
                        Vector3 rightVector = Vector3.Cross(dir, upVector);
                        pointSpace.M11 = rightVector.X;
                        pointSpace.M12 = rightVector.Y;
                        pointSpace.M13 = rightVector.Z;
                        pointSpace.M21 = dir.X;
                        pointSpace.M22 = dir.Y;
                        pointSpace.M23 = dir.Z;
                        columnPointSpacesBottom.Add(pointSpace);
                    }

                    // We have just set a pile, the next pile will be set after
                    // reaching the next holder gap.
                    lastColumnsDistance += ColumnsDistance;
                }

                // The distance we have to cover until the next position.
                // We subtract our current distance from the remaining gap distance,
                // which will then be checked in the next loop.
                lastColumnsDistance -= distance;
            }
            #endregion

            #region Generate vertex buffer
            columnVertices = new TangentVertex[
                columnPositions.Count * BaseColumnVertices.Length * 2];

            // Go through all columns
            for (int num = 0; num < columnPositions.Count; num++)
            {
                Vector3 pos = columnPositions[num];

                // Find out the current landscape height here
                Vector3 bottomPos = new Vector3(pos.X, pos.Y,
                                                landscape.GetMapHeight(pos.X, pos.Y) +
                                                ColumnGroundHeight);
                Vector3 topPos = new Vector3(pos.X, pos.Y,
                                             pos.Z - TopColumnSubHeight);
                // Calculate top v tex coord for this column
                float topTexV =
                    Vector3.Distance(topPos, bottomPos) / (MathHelper.Pi * 2);

                // Use the BaseColumnVertices twice, once for the bottom and then for the
                // top part of our generated column.
                for (int topBottom = 0; topBottom < 2; topBottom++)
                {
                    // Go to all BaseColumnVertices
                    for (int i = 0; i < BaseColumnVertices.Length; i++)
                    {
                        int vertIndex = num * BaseColumnVertices.Length * 2 +
                                        topBottom * BaseColumnVertices.Length + i;

                        // For the top positions, modify them them to fit directly
                        // on the bottom side of our road. Same for bottom, but don't
                        // modify the z value
                        Matrix transformMatrix = topBottom == 0 ?
                                                 columnPointSpacesBottom[num] : columnPointSpacesTop[num];

                        // We don't have to transform the vertices much, just adjust
                        // the z value and the v tex coord.
                        columnVertices[vertIndex] =
                            new TangentVertex(
                                (topBottom == 0 ? bottomPos : topPos) +
                                Vector3.Transform(BaseColumnVertices[i].pos,
                                                  transformMatrix),
                                BaseColumnVertices[i].U, topBottom == 0 ? 0 : topTexV,
                                Vector3.Transform(BaseColumnVertices[i].normal,
                                                  transformMatrix),
                                Vector3.Transform(-BaseColumnVertices[i].tangent,
                                                  transformMatrix));
                    }
                }

                // Also add the bottom position to the list of holders we want
                // to render later.
                if (landscape != null &&
                    // This is not really required, we can easily optimize this out.
                    BaseGame.HighDetail)
                {
                    landscape.AddObjectToRender(
                        "RoadColumnSegment",
                        new Vector3(bottomPos.X, bottomPos.Y,
                                    bottomPos.Z - ColumnGroundHeight));
                }
            }

            // Create the vertex buffer from our vertices.
            // fix
            //columnVb = new VertexBuffer(
            //    BaseGame.Device,
            //    typeof(TangentVertex),
            //    columnVertices.Length,
            //    ResourceUsage.WriteOnly,
            //    ResourceManagementMode.Automatic);
            columnVb = new VertexBuffer(
                BaseGame.Device,
                typeof(TangentVertex),
                columnVertices.Length,
                BufferUsage.WriteOnly);
            columnVb.SetData(columnVertices);
            #endregion

            #region GenerateIndexBuffer
            // Count of quads (polygons) we have for each column
            int   quadPolysPerColumn = BaseColumnVertices.Length - 1;
            int[] indices            =
                new int[(2 * 3 * quadPolysPerColumn) * columnPositions.Count];
            // Current vertex index
            int vertexIndex = 0;
            // Helper variable, current index of the indices list
            int indicesIndex = 0;
            for (int num = 0; num < columnPositions.Count; num++)
            {
                // Set all quads of the column
                for (int j = 0; j < quadPolysPerColumn; j++)
                {
                    indicesIndex = 3 * 2 * (num * quadPolysPerColumn + j);

                    // 1. Polygon
                    indices[indicesIndex]     = vertexIndex + j;
                    indices[indicesIndex + 1] =
                        vertexIndex + 1 + BaseColumnVertices.Length + j;
                    indices[indicesIndex + 2] = vertexIndex + 1 + j;

                    // 2. Polygon
                    indices[indicesIndex + 3] = indices[indicesIndex + 1];
                    indices[indicesIndex + 4] = indices[indicesIndex];
                    indices[indicesIndex + 5] =
                        vertexIndex + BaseColumnVertices.Length + j;
                }

                // Go to next column
                vertexIndex += BaseColumnVertices.Length * 2;
            }

            // Create the index buffer from our indices.
            // fix
            //columnIb = new IndexBuffer(
            //    BaseGame.Device,
            //    typeof(int),
            //    indices.Length,
            //    ResourceUsage.WriteOnly,
            //    ResourceManagementMode.Automatic);
            columnIb = new IndexBuffer(
                BaseGame.Device,
                typeof(int),
                indices.Length,
                BufferUsage.WriteOnly);
            columnIb.SetData(indices);
            #endregion
        }
Example #18
0
 /// <summary>
 /// Метод изменяет текущую скорость и область видимости Юнита в зависимости от текущего местоположения, переданного в метод.
 /// </summary>
 /// <param name="land">Местоположение (Местность)</param>
 internal void SetCurrent(Landscape land)
 {
     Properties.CurSpeed   = Properties.Speed * land.Passability();
     Properties.CurVisible = Properties.Visible * land.Visibility();
 }
Example #19
0
        public void renderEntities(DirectionalLight sun, BaseCamera camera, Matrix4 projectionMatrix, float time, Landscape terrain = null,
                                   Vector4 clipPlane = new Vector4())
        {
            if (this._bufferAssembled)
            {
                postConstructor(terrain);

                timeElapsed += time * windSpeed;
                timeElapsed  = timeElapsed > 360 ? timeElapsed - 360 : timeElapsed;

                _shader.startProgram();
                _texture[0].BindTexture(TextureUnit.Texture0);      //Биндим текстуру
                if (_texture.Count > 1)
                {
                    _texture[1].BindTexture(TextureUnit.Texture1);      //Биндим текстуру
                    if (_texture.Count == 3)
                    {
                        _texture[2].BindTexture(TextureUnit.Texture2);      //Биндим текстуру
                    }
                }

                _shader.setTextureSampler(0);
                _shader.setMaterial(_grassMaterial);
                _shader.setViewMatrix(camera.GetViewMatrix());
                _shader.setProjectionMatrix(ref projectionMatrix);
                _shader.setSun(sun);
                _shader.setWind(_wind);
                _shader.setTime(timeElapsed);
                _shader.setClipPlane(ref clipPlane);
                _shader.setMist(_mist);

                //VAOManager.renderInstanced(_buffer, PrimitiveType.Triangles, _plants.Count);
                _shader.stopProgram();
            }
        }
Example #20
0
 public Transformer(Landscape landscape)
 {
     LandscapeAround = landscape;
 }
Example #21
0
 public new static LandCell Get(uint cellID)
 {
     return(Landscape.get_landcell(cellID));
 }
Example #22
0
    /// <summary>
    ///
    /// </summary>
    /// <param name="heightMap">height map</param>
    /// <param name="size">size in world unit</param>
    /// <param name="baseHeight"></param>
    /// <param name="totalHeight"></param>
    private static Landscape Create(Texture2D heightMap, Vector2 size, float baseHeight,
                                    float totalHeight)
    {
        if (heightMap == null)
        {
            throw new System.ArgumentNullException(nameof(heightMap));
        }

        Landscape landscape  = new Landscape();
        var       resolution = new Vector2Int(heightMap.width, heightMap.height);

        if (resolution.x > 4097 || resolution.y > 4097 || resolution.x < 33 || resolution.y < 33)
        {
            throw new System.ArgumentException(
                      "resolution must be in range 33x33 to 4097x4097", nameof(resolution));
        }

        if (!Mathf.IsPowerOfTwo(resolution.x - 1) || !Mathf.IsPowerOfTwo(resolution.y - 1))
        {
            throw new System.ArgumentException(
                      "resolution value must be (power of 2) + 1", nameof(resolution));
        }

        var       quadNumber      = resolution - Vector2Int.one;
        const int blockQuadNumber = 16;
        int       LOD             = 0;

        while (quadNumber.x > 16 && quadNumber.y > 16)
        {
            var blockNumber    = quadNumber / blockQuadNumber;
            var blockMeshes    = new List <Mesh>(blockNumber.x * blockNumber.y);
            var blockPixelSize =
                new Vector2Int(resolution.x / blockNumber.x, resolution.y / blockNumber.y);
            var quadSize       = size / resolution;
            var blockPixelStep = new Vector2Int(
                (resolution.x - 1) / quadNumber.x,
                (resolution.y - 1) / quadNumber.y);
            for (int blockY = 0; blockY < blockNumber.y; blockY++)
            {
                for (int blockX = 0; blockX < blockNumber.x; blockX++)
                {
                    var blockPixelMin = new Vector2Int(blockX, blockY) * blockPixelSize;
                    var blockPixelMax = blockPixelMin + Vector2Int.one * blockPixelSize;

                    Debug.Log($"LOD{LOD} Block<{blockX},{blockY}>:" +
                              $" from {blockPixelMin} to {blockPixelMax} step {blockPixelStep}" +
                              " on the height map");

                    var mesh = CreateBlockMesh(
                        blockPixelMin, blockPixelMax, blockPixelStep,
                        baseHeight, totalHeight, quadSize, heightMap);
                    mesh.name = $"Block<{blockX},{blockY}>";
                    blockMeshes.Add(mesh);
                }
            }

            landscape.LODMeshList.Add(blockMeshes);
            LOD++;
#if ONLY_LOD0
            break;
#endif
            quadNumber /= 2;
        }

        return(landscape);
    }
Example #23
0
        //---------------------------------------------------------------------

        /// <summary>
        /// Runs a model scenario.
        /// </summary>
        public void Run(string scenarioPath)
        {
            siteVarRegistry.Clear();

            Scenario scenario = LoadScenario(scenarioPath);

            startTime      = scenario.StartTime;
            endTime        = scenario.EndTime;
            timeSinceStart = 0;
            currentTime    = startTime;
            InitializeRandomNumGenerator(scenario.RandomNumberSeed);

            LoadSpecies(scenario.Species);
            LoadEcoregions(scenario.Ecoregions);

            UI.WriteLine("Initializing landscape from ecoregions map \"{0}\" ...", scenario.EcoregionsMap);
            Ecoregions.Map ecoregionsMap = new Ecoregions.Map(scenario.EcoregionsMap,
                                                              ecoregions,
                                                              rasterDriverMgr);
            ProcessMetadata(ecoregionsMap.Metadata, scenario);
            using (IInputGrid <bool> grid = ecoregionsMap.OpenAsInputGrid()) {
                UI.WriteLine("Map dimensions: {0} = {1:#,##0} cell{2}", grid.Dimensions,
                             grid.Count, (grid.Count == 1 ? "" : "s"));
                landscape = new Landscape(grid);
            }
            UI.WriteLine("Sites: {0:#,##0} active ({1:p1}), {2:#,##0} inactive ({3:p1})",
                         landscape.ActiveSiteCount, (landscape.Count > 0 ? ((double)landscape.ActiveSiteCount) / landscape.Count : 0),
                         landscape.InactiveSiteCount, (landscape.Count > 0 ? ((double)landscape.InactiveSiteCount) / landscape.Count : 0));

            ecoregionSiteVar = ecoregionsMap.CreateSiteVar(landscape);

            plugInsWith2PhaseInit = new List <PlugIns.I2PhaseInitialization>();
            plugInsWithCleanUp    = new List <PlugIns.ICleanUp>();

            try {
                UI.WriteLine("Loading {0} plug-in ...", scenario.Succession.Info.Name);
                succession = Loader.Load <SuccessionPlugIn>(scenario.Succession.Info);
                succession.Initialize(scenario.Succession.InitFile, this);
                succession.InitializeSites(scenario.InitialCommunities,
                                           scenario.InitialCommunitiesMap);

                PlugIn[] disturbancePlugIns = LoadAndInitPlugIns(scenario.Disturbances);
                PlugIn[] otherPlugIns       = LoadAndInitPlugIns(scenario.OtherPlugIns);

                //    Perform 2nd phase of initialization for those plug-ins
                //    that have it.
                foreach (PlugIns.I2PhaseInitialization plugIn in plugInsWith2PhaseInit)
                {
                    plugIn.InitializePhase2();
                }

                //  Run output plug-ins for TimeSinceStart = 0 (time step 0)
                foreach (PlugIn plugIn in otherPlugIns)
                {
                    if (plugIn.PlugInType.IsMemberOf("output"))
                    {
                        Run(plugIn);
                    }
                }

                //******************// for Rob
                //  Main time loop  //
                //******************//

                for (currentTime++, timeSinceStart++;
                     currentTime <= endTime;
                     currentTime++, timeSinceStart++)
                {
                    bool isSuccTimestep = IsPlugInTimestep(succession);

                    List <PlugIn> distPlugInsToRun;
                    distPlugInsToRun = GetPlugInsToRun(disturbancePlugIns);
                    bool isDistTimestep = distPlugInsToRun.Count > 0;

                    List <PlugIn> otherPlugInsToRun;
                    otherPlugInsToRun = GetPlugInsToRun(otherPlugIns);

                    if (!isSuccTimestep && !isDistTimestep &&
                        otherPlugInsToRun.Count == 0)
                    {
                        continue;
                    }

                    UI.WriteLine("Current time: {0}", currentTime);

                    if (isDistTimestep)
                    {
                        if (scenario.DisturbancesRandomOrder)
                        {
                            Util.Random.Shuffle(distPlugInsToRun);
                        }
                        foreach (PlugIn distPlugIn in distPlugInsToRun)
                        {
                            Run(distPlugIn);
                        }
                    }

                    if (isSuccTimestep || isDistTimestep)
                    {
                        Run(succession);
                    }

                    foreach (PlugIn otherPlugIn in otherPlugInsToRun)
                    {
                        Run(otherPlugIn);
                    }
                }  // main time loop
            }
            finally {
                foreach (PlugIns.ICleanUp plugIn in plugInsWithCleanUp)
                {
                    plugIn.CleanUp();
                }
            }
        }
        /// <summary>
        /// Load graphics content for the game.
        /// </summary>
        public override void Activate(InputState input)
        {
            grid = new DrawableGrid(3);
            landscape = new Landscape();
            effectSprites = new List<EffectSprite>();
            //for (int i = 0; i < Main.backgroundLoops.Count; i++)
            //Main.backgroundLoops[i].Play();

            scoreText = new IconText("", Main.sprites["points"], new Vector2(Main.windowSize.X / 10.0f, Main.windowSize.X / 10.0f), new Vector2(Main.windowSize.X / 6.0f, Main.windowSize.X / 12.0f), 0.5f, Color.Goldenrod, TextAlignment.Right);

            snake = new Snake(grid, Main.windowSize * 0.5f,  this.snakeSpeed, this.startSnakeLength);
            landscape.AddComponent(snake);

            List<Type> snakeConditions = new List<Type>();
            snakeConditions.Add(typeof(Mouse));
            snakeConditions.Add(typeof(Rabbit));

            snake.ScheduleCollisionHandling(snakeConditions);
            animals = new List<IDrawableGridAsset>();
            for (int i = 0; i < 5; i++)
                this.PlaceAnimal();
            ScreenManager.Game.ResetElapsedTime();
            base.Activate(input);
        }
Example #25
0
        private static IEnumerable <TestCaseData> IntersectingTestCases()
        {
            IPhysObject GetObjectWithSize(Vector cords, Size size)
            {
                var obj = Substitute.For <IPhysObject>();

                obj.Cords.Returns(cords);
                obj.Size.Returns(size);

                return(obj);
            }

            var landscape = Landscape.CreateFromText(new List <string>
            {
                "........................................",
                "........................................",
                "........................................",
                "........................................",
                "........................................",
                "...........................*************",
                "........................****************",
                "..................................******",
                ".................................*******",
                ".**............................*********",
                "*****.............******....************",
                "******.........******************...****",
                "*********************************...****"
            }, chr => chr == '*' ? LandscapeCell.Ground : LandscapeCell.Empty);

            yield return(new TestCaseData(landscape, GetObjectWithSize(Vector.Create(0, 0), Size.Create(5, 5)), false)
                         .SetName("int 1"));

            yield return(new TestCaseData(landscape, GetObjectWithSize(Vector.Create(2, 2), Size.Create(5, 5)), false)
                         .SetName("int 2"));

            yield return(new TestCaseData(landscape, GetObjectWithSize(Vector.Create(5, 5), Size.Create(5, 5)), false)
                         .SetName("int 3"));

            yield return(new TestCaseData(landscape, GetObjectWithSize(Vector.Create(30, 1), Size.Create(15, 15)), true)
                         .SetName("int 4"));

            yield return(new TestCaseData(landscape, GetObjectWithSize(Vector.Create(26, 7), Size.Create(2, 2)), false)
                         .SetName("int 5"));

            yield return(new TestCaseData(landscape, GetObjectWithSize(Vector.Create(35, 9), Size.Create(5, 5)), true)
                         .SetName("int 6"));

            yield return(new TestCaseData(landscape, GetObjectWithSize(Vector.Create(26, 5), Size.Create(1, 1)), false)
                         .SetName("int 7"));

            yield return(new TestCaseData(landscape, GetObjectWithSize(Vector.Create(-10, 20), Size.Create(100, 100)),
                                          false).SetName("int 8"));

            yield return(new TestCaseData(landscape, GetObjectWithSize(Vector.Create(-10, 10), Size.Create(100, 100)),
                                          true).SetName("int 9"));

            yield return(new TestCaseData(landscape, GetObjectWithSize(Vector.Create(35, 4), Size.Create(1, 1)), false)
                         .SetName("int 10"));

            yield return(new TestCaseData(landscape, GetObjectWithSize(Vector.Create(34, 12), Size.Create(1, 1)), false)
                         .SetName("int 11"));

            yield return(new TestCaseData(landscape, GetObjectWithSize(Vector.Create(32, 12), Size.Create(1, 1)), true)
                         .SetName("int 12"));

            yield return(new TestCaseData(landscape, GetObjectWithSize(Vector.Create(26.1, 5), Size.Create(1, 1)), true)
                         .SetName("double 1"));

            yield return(new TestCaseData(landscape, GetObjectWithSize(Vector.Create(-1, 5), Size.Create(10, 10)), true)
                         .SetName("double 2"));

            yield return(new TestCaseData(landscape, GetObjectWithSize(Vector.Create(26.7, 7), Size.Create(1, 1)),
                                          false).SetName("double 3"));

            yield return(new TestCaseData(landscape, GetObjectWithSize(Vector.Create(26, 7.1), Size.Create(1, 1)),
                                          false).SetName("double 4"));

            yield return(new TestCaseData(landscape, GetObjectWithSize(Vector.Create(34.9, 12), Size.Create(1, 1)),
                                          false).SetName("double 5"));

            yield return(new TestCaseData(landscape, GetObjectWithSize(Vector.Create(32.1, 12), Size.Create(1, 1)),
                                          true).SetName("double 6"));
        }
Example #26
0
 // Use this for initialization
 void Start()
 {
     GameObject landscapeObj = GameObject.Find( "Landscape" );
     landscape = landscapeObj.GetComponent<Landscape>();
 }
Example #27
0
 // Use this for initialization
 void Awake()
 {
     landscape = FindObjectOfType <Landscape>();
     mapGen    = FindObjectOfType <MapGenerator>();
 }
Example #28
0
        public void Save(XElement e)
        {
            XElement elemGameSetting = new XElement("GameSetting");

            e.Add(elemGameSetting);

            XElement   elem  = new XElement("OurTeamOffensive");
            XAttribute attri = new XAttribute("Value", OurTeamOffensive.ToString());

            elem.Add(attri);
            elemGameSetting.Add(elem);

            elem  = new XElement("Scaling");
            attri = new XAttribute("Value", Scaling.ToString());
            elem.Add(attri);
            elemGameSetting.Add(elem);

            // 11-09-2010 Scott
            elem  = new XElement("ScalingAnimation");
            attri = new XAttribute("Value", ScalingAnimation.ToString());
            elem.Add(attri);
            elemGameSetting.Add(elem);

            // 10-08-2010 Scott
            elem  = new XElement("OffensiveMainField");
            attri = new XAttribute("Value", OffensiveMainField.ToString());
            elem.Add(attri);
            elemGameSetting.Add(elem);

            elem  = new XElement("OffensiveSubField");
            attri = new XAttribute("Value", OffensiveSubField.ToString());
            elem.Add(attri);
            elemGameSetting.Add(elem);

            elem  = new XElement("DefensiveMainField");
            attri = new XAttribute("Value", DefensiveMainField.ToString());
            elem.Add(attri);
            elemGameSetting.Add(elem);

            elem  = new XElement("DefensiveSubField");
            attri = new XAttribute("Value", DefensiveSubField.ToString());
            elem.Add(attri);
            elemGameSetting.Add(elem);

            // 10-26-2011 Scott
            elem  = new XElement("KickMainField");
            attri = new XAttribute("Value", KickMainField.ToString());
            elem.Add(attri);
            elemGameSetting.Add(elem);

            elem  = new XElement("KickSubField");
            attri = new XAttribute("Value", KickSubField.ToString());
            elem.Add(attri);
            elemGameSetting.Add(elem);
            // end

            elem  = new XElement("UserFolder");
            attri = new XAttribute("Value", UserFolder);
            elem.Add(attri);
            elemGameSetting.Add(elem);

            elem  = new XElement("UserType");
            attri = new XAttribute("Value", UserType.ToString());
            elem.Add(attri);
            elemGameSetting.Add(elem);

            elem  = new XElement("ProductType");
            attri = new XAttribute("Value", ProductType.ToString());
            elem.Add(attri);
            elemGameSetting.Add(elem);

            elem  = new XElement("PlaygroundType");
            attri = new XAttribute("Value", PlaygroundType.ToString());
            elem.Add(attri);
            elemGameSetting.Add(elem);

            elem  = new XElement("CurrentTheme");
            attri = new XAttribute("Value", CurrentTheme);
            elem.Add(attri);
            elemGameSetting.Add(elem);

            elem  = new XElement("GridLine");
            attri = new XAttribute("Value", GridLine.ToString());
            elem.Add(attri);
            elemGameSetting.Add(elem);

            elem  = new XElement("SnapValue");
            attri = new XAttribute("Value", SnapValue.ToString());
            elem.Add(attri);
            elemGameSetting.Add(elem);

            elem  = new XElement("SnapToGrid");
            attri = new XAttribute("Value", SnapToGrid.ToString());
            elem.Add(attri);
            elemGameSetting.Add(elem);

            elem  = new XElement("ShowBall");
            attri = new XAttribute("Value", ShowBall.ToString());
            elem.Add(attri);
            elemGameSetting.Add(elem);

            elem  = new XElement("BallSize");
            attri = new XAttribute("Value", BallSize.ToString());
            elem.Add(attri);
            elemGameSetting.Add(elem);

            elem  = new XElement("Landscape");
            attri = new XAttribute("Value", Landscape.ToString());
            elem.Add(attri);
            elemGameSetting.Add(elem);

            elem  = new XElement("ShowPlayground");
            attri = new XAttribute("Value", ShowPlayground.ToString());
            elem.Add(attri);
            elemGameSetting.Add(elem);

            elem  = new XElement("EnableColor");
            attri = new XAttribute("Value", EnableColor.ToString());
            elem.Add(attri);
            elemGameSetting.Add(elem);

            elem  = new XElement("EnableSymbolColor");
            attri = new XAttribute("Value", EnableSymbolColor.ToString());
            elem.Add(attri);
            elemGameSetting.Add(elem);

            elem  = new XElement("EnableTitle");
            attri = new XAttribute("Value", EnableTitle.ToString());
            elem.Add(attri);
            elemGameSetting.Add(elem);

            elem  = new XElement("PlayerAngle");
            attri = new XAttribute("Value", PlayerAngle.ToString());
            elem.Add(attri);
            elemGameSetting.Add(elem);

            elem  = new XElement("PlayerAppearance");
            attri = new XAttribute("Value", PlayerAppearance.ToString());
            elem.Add(attri);
            elemGameSetting.Add(elem);

            elem  = new XElement("PlayerDash");
            attri = new XAttribute("Value", PlayerDash.ToString());
            elem.Add(attri);
            elemGameSetting.Add(elem);

            elem  = new XElement("PlayerSzie");
            attri = new XAttribute("Value", PlayerSize.ToString());
            elem.Add(attri);
            elemGameSetting.Add(elem);

            elem  = new XElement("PlayerTextVisibility");
            attri = new XAttribute("Value", PlayerTextVisibility.ToString());
            elem.Add(attri);
            elemGameSetting.Add(elem);

            elem  = new XElement("PlayerThickness");
            attri = new XAttribute("Value", PlayerThickness.ToString());
            elem.Add(attri);
            elemGameSetting.Add(elem);

            elem  = new XElement("ImageShowPlayground");
            attri = new XAttribute("Value", ImageShowPlayground.ToString());
            elem.Add(attri);
            elemGameSetting.Add(elem);

            elem  = new XElement("ImageEnableColor");
            attri = new XAttribute("Value", ImageEnableColor.ToString());
            elem.Add(attri);
            elemGameSetting.Add(elem);

            elem  = new XElement("ImageEnableSymbolColor");
            attri = new XAttribute("Value", ImageEnableSymbolColor.ToString());
            elem.Add(attri);
            elemGameSetting.Add(elem);
        }
        /// <summary>
        /// Load graphics content for the game.
        /// </summary>
        /// 
        public override void Activate(InputState input)
        {
            grid = new DrawableGrid(3);
            landscape = new Landscape();
            effectSprites = new List<EffectSprite>();
            //for (int i = 0; i < Main.backgroundLoops.Count; i++)
            //Main.backgroundLoops[i].Play();
            scoreText = new IconText("", Main.sprites["points"], new Vector2(Main.windowSize.X / 15.0f, Main.windowSize.X / 15.0f), new Vector2(Main.windowSize.X / 6.0f, 100.0f), 0.5f, Color.Goldenrod, TextAlignment.Right);

            quadrantTarget = Main.numGenerator.Next() % 4 + 1;
            if (currentExcercise == QuadrantExcercises.PolarityOne || currentExcercise == QuadrantExcercises.PolarityTwo)
                quadrantCommand = new IconText(Utilities.QuadrantToPolarity(quadrantTarget), Main.sprites["quadrant"], new Vector2(Main.windowSize.X / 10.0f, Main.windowSize.X / 10.0f), new Vector2(Main.windowSize.X / 3.0f, 100), 1.0f, Color.Azure, TextAlignment.Right, TextEffect.Bubble);

            else
                quadrantCommand = new IconText(quadrantTarget.ToString(), Main.sprites["quadrant"], new Vector2(Main.windowSize.X / 10.0f, Main.windowSize.X / 10.0f), new Vector2(Main.windowSize.X / 3.0f, 100), 1.0f, Color.Azure, TextAlignment.Right, TextEffect.Bubble);
            resultText = new Text("", new Vector2(Main.windowSize.X / 2.0f, Main.windowSize.X / 10.0f), Main.windowSize.X / 1920.0f, Color.Red, TextEffect.Fade);

            this.lives = 5;
            lifeSprites = new List<DrawableAsset<Texture2D>>();
            Vector2 lifeSpriteSize = new Vector2(Main.windowSize.X / 15.0f, Main.windowSize.X / 15.0f);
            for (int i = 0; i < lives; i++)
                lifeSprites.Add(new DrawableAsset<Texture2D>(new Vector2(Main.windowSize.X - (i + 1) * lifeSpriteSize.X, lifeSpriteSize.Y), new Vector2(0, -1), lifeSpriteSize, Main.sprites["snakeBody"]));

            landscape.AddStain(new CoordinateSystem(coordinateType));
            snake = new Snake(grid, Main.windowSize * 0.5f,  this.snakeSpeed, this.startSnakeLength);
            landscape.AddComponent(snake);

            animals = new List<IDrawableGridAsset>();
            for (int i = 0; i < 4; i++)
                this.PlaceAnimal(i + 1);

            List<Type> snakeConditions = new List<Type>();
            snakeConditions.Add(typeof(Mouse));
            snakeConditions.Add(typeof(Rabbit));

            snake.ScheduleCollisionHandling(snakeConditions);
            //ScreenManager.Game.ResetElapsedTime();

            base.Activate(input);
        }
Example #30
0
        private static readonly int SIZE = 9;        //128;

        //512;

        private static void Main()
        {
            /*Vec3 v1 = new Vec3(1);
             * Console.WriteLine("v1 is: " + v1);
             * Vec3 v2 = new Vec3(1, 2, 4);
             * Console.WriteLine("v2 is: " + v2);
             * Console.WriteLine("Dot(v1, v2): " + Vec3.Dot(v1, v2));
             * Console.WriteLine("Cross(v1, v2): " + Vec3.Cross(v1, v2));
             * Console.WriteLine("Cross(v2, v1): " + Vec3.Cross(v2, v1));
             * Console.WriteLine("v1 + v2: " + ( v1 + v2 ));1
             * Console.WriteLine("v2 + v1: " + ( v2 + v1 ));
             * Console.WriteLine("v1 - v2: " + ( v1 - v2 ));
             * Console.WriteLine("v2 - v1: " + ( v2 - v1 ));
             * Console.WriteLine("v1 * v2: " + ( v1 * v2 ));
             * Console.WriteLine("v1 * 5: " + ( v1 * 5 ));
             * Console.WriteLine("v1 / 5: " + ( v1 / 5 ));
             * Console.WriteLine("v1 is: " + v1);
             * Console.WriteLine("v2 is: " + v2);
             *
             * Console.WriteLine("90 degrees: " + Angle.RightAngle.Vec2);
             *
             * Console.WriteLine("180 degrees: " + Angle.StraightAngle.AngleRaw);
             * Console.WriteLine("180 degrees: " + Angle.StraightAngle.GetAngle(AngleFormat.Unit));
             * Console.WriteLine("180 degrees: " + Angle.StraightAngle.GetAngle(AngleFormat.Degrees));
             * Console.WriteLine("180 degrees: " + Angle.StraightAngle.GetAngle(AngleFormat.Radians));
             * Console.WriteLine("180 degrees: " + Angle.StraightAngle.Vec2);
             *
             * Console.WriteLine("Cross(v1, X): " + Vec3.Cross(v1, new Vec3(1, 0, 0)));
             * Console.WriteLine("Cross(v1, Y): " + Vec3.Cross(v1, new Vec3(0, 1, 0)));
             * Console.WriteLine("Cross(v1, Z): " + Vec3.Cross(v1, new Vec3(0, 0, 1)));
             * Console.WriteLine("v1.CrossX: " + v1.CrossX);
             * Console.WriteLine("v1.CrossY: " + v1.CrossY);
             * Console.WriteLine("v1.CrossZ: " + v1.CrossZ);
             *
             * Sector<float> sectorFloat = new Sector<float>(new Coordinate(0, 0), 1, 1);
             * sectorFloat[0, 0] = 0;
             * sectorFloat[1, 0] = 50;
             *
             * Console.WriteLine("should be 12.5: " + sectorFloat.ValueAt(0.5f, 0.5f));
             */
            Stopwatch sw = new Stopwatch();

            Console.WriteLine("Stopwatch Started");
            Console.WriteLine("Building...");
            sw.Start();

            LandscapeBuilder landscapeBuilder = new LandscapeBuilder();

            landscapeBuilder["random"] = new RandomBuilder()
            {
                Seed = 6
            };
            landscapeBuilder["vec2"] = new Vec2FieldBuilder()
            {
                SourceID = "random", Magnitude = Constants.SQRT_2_OVER_2_FLOAT
            };
            landscapeBuilder["mem1"] = new MemoryBuilder <Vec2>()
            {
                SourceID = "vec2"
            };
            landscapeBuilder["perlin"] = new ParlinGroupBuiler()
            {
                Vec2FieldID = "mem1", UpperTargetScale = SCALE, MaxPerlinScale = SCALE / 4, DeltaFactor = 0.625f, ScaleStep = 1.5f, RetFactor = 1f, BottomUp = false, OffsetGlobal = new Coordinate(64, 64), LowerTargetScale = 2
            };
            //landscapeBuilder["mem2"] = new MemoryBuilder<float>() { SourceID = "perlin" };
            //0.5325f
            landscapeBuilder["mem2"] = new MemoryBuilder <float>()
            {
                SourceID = "perlin"
            };
            landscapeBuilder["HE"] = new HydraulicErosionBuilder()
            {
                SourceID               = "mem2",
                LayeringPower          = 7,
                CoverageFactor         = 1 / 4f,
                BrushRadius            = 4,
                StepLength             = 2f,
                Gravity                = 4,
                OutputFactor           = 0.2f,
                Friction               = 0.5f,
                SedimentCapacityFactor = 1.125f,
                MinModification        = 0.01f,
                ErodeSpeed             = 0.5f,
                DepositSpeed           = 0.125f,
                SedimentFactor         = 2,
            };
            landscapeBuilder["HEmem"] = new MemoryStrictSectoringBuilder <float>()
            {
                SourceID = "HE", SectorSize = 32
            };
            landscapeBuilder["HEmblur"] = new BlurBuilder {
                SourceID = "HEmem"
            };
            landscapeBuilder["finalInterpol"] = new InterpolatorBuilder {
                SourceID = "HEmblur", Scale = 2
            };
            landscapeBuilder["finalblur"] = new BlurBuilder {
                SourceID = "finalInterpol"
            };
            landscapeBuilder["fianlMem"] = new MemoryBuilder <float>()
            {
                SourceID = "HEmblur"
            };
            landscapeBuilder["HEinv"] = new FloatAdderBuilder()
            {
                Sources = new string[] { "fianlMem" }, RetFactor = -1
            };
            landscapeBuilder["HEdiff"] = new FloatAdderBuilder()
            {
                Sources = new string[] { "HEinv", "mem2" }, RetFactor = 2
            };
            landscapeBuilder["output"] = new HeightMapImageOutputterBuilder()
            {
                SourceID = "mem2", Layers = 3, Size = 100, Min = -1, Max = 1
            };

            //landscapeBuilder["blur1"] = new BlurBuilder() { SourceID = "mem2" };
            //landscapeBuilder["brush"] = new BrushTestBuilder();

            Landscape landscape = landscapeBuilder.Build();

            //string xml = landscapeBuilder.XML;
            //Console.WriteLine(xml);
            //landscapeBuilder.XML = xml;
            //Console.WriteLine(landscapeBuilder.XML);
            Console.WriteLine("Elapsed={0}", sw.Elapsed);
            Console.WriteLine("Computing...");

            sw.Restart();
            Algorithm <float>  outputPerlin    = landscape.GetAlgorithm <float>("mem2");
            Algorithm <float>  outputHE        = landscape.GetAlgorithm <float>("fianlMem");
            Algorithm <float>  outputdiff      = landscape.GetAlgorithm <float>("HEdiff");
            Outputter <Bitmap> bitmapOutputter = landscape.GetOutputter <Bitmap>("output");

            RequstSector request = new RequstSector(new Coordinate(0, 0), SIZE, SIZE);

            //Sector<float> sectordiff = outputdiff.GetSector(request);
            //Sector<float> sectorHE = outputHE.GetSector(request);
            //Sector<float> sectorPerlin = outputPerlin.GetSector(request);

            sw.Stop();
            Console.WriteLine("Elapsed={0}", sw.Elapsed);
            //Console.WriteLine("Press \"Enter\" to save", sw.Elapsed);
            //Console.ReadKey();

            int width  = request.Width_units * 3;
            int height = request.Height_units;

            Bitmap bmp = bitmapOutputter.GetObject(new Coordinate());

            Console.WriteLine("Saving...");
            bmp.Save("D:\\output.png", ImageFormat.Png);

            //Console.WriteLine("min: " + min + " max: " + max + " avg: " + (double) total / (width * height) + " errors: " + errors);
            Console.WriteLine("Saved");
            GC.Collect();
            Console.ReadKey();
        }
        public void Test1()
        {
            AbstractChromosomeFactory factory = new SolutionFactory();

            int[] routeWeights = new int[]
            {
                20000, 50000, 120000, 200000, 350000
            };
            int distanceWeight = 1;

            string[] customerTypes = new string[] { "C1", "C2", "R1", "R2", "RC1", "RC2" };
            Dictionary <string, int> customerNumbers = new Dictionary <string, int>()
            {
                { "2", 20000 }, { "4", 50000 }, { "6", 120000 }, { "8", 200000 }, { "10", 350000 }
            };

            string[] customerInstances = new string[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };

            CrossoverOperator[] crossoverOps = new CrossoverOperator[]
            {
                new OrderCrossover(), new PartiallyMatchedCrossover(), new CycleCrossover(), new UniformBasedOrderCrossover()
            };

            MutationOperator[] mutationOps = new MutationOperator[]
            {
                new SwapOperator(), new InsertionOperator(), new InversionOperator(), new DisplacementOperator()
            };

            int randomWalkNumber = 2000, randomWalkSteps = 5000;

            string floatPattern = "0.000", separator = ",";
            float  epsilon = 0.05f;

            foreach (var type in customerTypes)
            {
                foreach (var number in customerNumbers)
                {
                    foreach (var instance in customerInstances)
                    {
                        string          instanceId = type + '_' + number.Key + '_' + instance;
                        VrptwProblem    problem    = reader.ReadFromFile(FILE_PATH + @"\" + instanceId + ".txt");
                        FitnessFunction ff         = new FitnessFunction(number.Value, distanceWeight);
                        Landscape       landscape  = new Landscape(problem, factory, ff);
                        foreach (var op in crossoverOps)
                        {
                            string path = RESULT_PATH + @"\" + instanceId + "_" + op.GetId() + ".csv";
                            if (!File.Exists(path))
                            {
                                File.Create(path).Close();
                                File.ReadAllText(path);
                                using (TextWriter tw = new StreamWriter(path))
                                {
                                    tw.WriteLine("AC, IC, PIC, DBI");
                                    for (int i = 0; i < randomWalkNumber; ++i)
                                    {
                                        var    rwResult = landscape.RandomWalk(randomWalkSteps, op);
                                        float  ac       = Autocorrelation.Run(rwResult);
                                        float  ic       = InformationContent.Run(rwResult, epsilon);
                                        float  pic      = PartialInformationContent.Run(rwResult, epsilon);
                                        float  dbi      = DensityBasinInformation.Run(rwResult, epsilon);
                                        string line     =
                                            ac.ToString(floatPattern) + separator +
                                            ic.ToString(floatPattern) + separator +
                                            pic.ToString(floatPattern) + separator +
                                            dbi.ToString(floatPattern);
                                        tw.WriteLine(line);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }