Exemplo n.º 1
0
        public IChunk[] GenerateChunk(IPlanet planet, Index2 index)
        {
            IChunk[] result = new IChunk[planet.Size.Z];

            for (int layer = 0; layer < planet.Size.Z; layer++)
                result[layer] = new Chunk(new Index3(index.X, index.Y, layer), planet.Id);

            int part = (planet.Size.Z * Chunk.CHUNKSIZE_Z) / 4;

            for (int y = 0; y < Chunk.CHUNKSIZE_Y; y++)
            {
                float heightY = (float)Math.Sin((float)(y * Math.PI) / 15f);
                for (int x = 0; x < Chunk.CHUNKSIZE_X; x++)
                {
                    float heightX = (float)Math.Sin((float)(x * Math.PI) / 18f);

                    float height = ((heightX + heightY + 2) / 4) * (2 * part);
                    for (int z = 0; z < planet.Size.Z * Chunk.CHUNKSIZE_Z; z++)
                    {
                        if (z < (int)(height + part))
                        {
                            int block = z % (Chunk.CHUNKSIZE_Z);
                            int layer = (int)(z / Chunk.CHUNKSIZE_Z);
                            result[layer].SetBlock(x, y, block, new SandBlock());
                        }
                    }
                }
            }

            return result;
        }
Exemplo n.º 2
0
 public Index2 getIndexForVec(Vector3 vec)
 {
     Index2 returnIndex = new Index2();
     returnIndex.X = Mathf.RoundToInt(vec.x / (cellSize * prodMesh.xSize));
     returnIndex.Y= Mathf.RoundToInt(vec.z / (cellSize * prodMesh.xSize));
     return returnIndex;
 }
Exemplo n.º 3
0
        public IChunk[] GenerateChunk(IEnumerable<IBlockDefinition> blockDefinitions, IPlanet planet, Index2 index)
        {
            IBlockDefinition sandDefinition = blockDefinitions.FirstOrDefault(d => typeof(SandBlockDefinition) == d.GetType());
            ushort sandIndex = (ushort)(Array.IndexOf(blockDefinitions.ToArray(), sandDefinition) + 1);

            IChunk[] result = new IChunk[planet.Size.Z];

            for (int layer = 0; layer < planet.Size.Z; layer++)
                result[layer] = new Chunk(new Index3(index.X, index.Y, layer), planet.Id);

            int part = (planet.Size.Z * Chunk.CHUNKSIZE_Z) / 4;

            for (int y = 0; y < Chunk.CHUNKSIZE_Y; y++)
            {
                float heightY = (float)Math.Sin((float)(y * Math.PI) / 15f);
                for (int x = 0; x < Chunk.CHUNKSIZE_X; x++)
                {
                    float heightX = (float)Math.Sin((float)(x * Math.PI) / 18f);

                    float height = ((heightX + heightY + 2) / 4) * (2 * part);
                    for (int z = 0; z < planet.Size.Z * Chunk.CHUNKSIZE_Z; z++)
                    {
                        if (z < (int)(height + part))
                        {
                            int block = z % (Chunk.CHUNKSIZE_Z);
                            int layer = (int)(z / Chunk.CHUNKSIZE_Z);
                            result[layer].SetBlock(x, y, block, sandIndex);
                        }
                    }
                }
            }

            return result;
        }
Exemplo n.º 4
0
 public static Index2 operator /(Index2 a, int b)
 {
     Index2 retIndex = new Index2();
     retIndex.X = a.X / b;
     retIndex.Y = a.Y / b;
     return retIndex;
 }
        /// <summary>
        /// Lädt eine <see cref="IChunkColumn"/>.
        /// </summary>
        /// <param name="universeGuid">GUID des Universums.</param>
        /// <param name="planet">Index des Planeten.</param>
        /// <param name="columnIndex">Zu serialisierende ChunkColumn.</param>
        /// <returns>Die neu geladene ChunkColumn.</returns>
        public IChunkColumn LoadColumn(Guid universeGuid, IPlanet planet, Index2 columnIndex)
        {
            string file = Path.Combine(GetRoot(), universeGuid.ToString(), planet.Id.ToString(), string.Format(ColumnFilename, columnIndex.X, columnIndex.Y));
            if (!File.Exists(file))
                return null;

            try {
            using (Stream stream = File.Open(file, FileMode.Open, FileAccess.Read))
            {
                using (GZipStream zip = new GZipStream(stream, CompressionMode.Decompress))
                {
                    return planet.Generator.GenerateColumn(zip, DefinitionManager.Instance, planet.Id, columnIndex);
                }
                }
            }
            catch (IOException)
            {
                try
                {
                    File.Delete(file);
                }
                catch (IOException) { }
                return null;
            }
        }
        public override float[,] GetHeightmap(Index2 chunkIndex)
        {
            float[,] values = new float[Chunk.CHUNKSIZE_X, Chunk.CHUNKSIZE_Y];
            
            Index2 blockIndex = new Index2(chunkIndex.X * Chunk.CHUNKSIZE_X, chunkIndex.Y * Chunk.CHUNKSIZE_Y);

            float[,] regions = BiomeNoiseGenerator.GetTileableNoiseMap2D(blockIndex.X, blockIndex.Y, Chunk.CHUNKSIZE_X, Chunk.CHUNKSIZE_Y, Planet.Size.X * Chunk.CHUNKSIZE_X, Planet.Size.Y * Chunk.CHUNKSIZE_Y);

            float[][,] biomeValues = new float[SubBiomes.Count][,];

            for (int i = 0; i < SubBiomes.Count; i++)
                biomeValues[i] = SubBiomes[i].GetHeightmap(chunkIndex);

            for (int x = 0; x < Chunk.CHUNKSIZE_X; x++)
            {
                for (int y = 0; y < Chunk.CHUNKSIZE_Y; y++)
                {
                    float region = regions[x, y] / 2 + 0.5f;

                    int biome2;
                    int biome1 = ChooseBiome(region, out biome2);

                    float interpolationValue = 0f;
                    if (biome2 != -1)
                    {
                        interpolationValue = CalculateInterpolationValue(region, SubBiomes[biome1], SubBiomes[biome2]);
                        values[x, y] = (biomeValues[biome2][x, y] * interpolationValue) + (biomeValues[biome1][x, y] * (1 - interpolationValue));
                    }
                    else
                        values[x, y] = biomeValues[biome1][x, y];

                }
            }
            return values;
        }
Exemplo n.º 7
0
 public static Index2 operator -(Index2 a, Index2 b)
 {
     Index2 retIndex = new Index2();
     retIndex.X = a.X - b.X;
     retIndex.Y = a.Y - b.Y;
     return retIndex;
 }
Exemplo n.º 8
0
        public void GenerateOutput(List<Index2> outputCull, out List<Vector3> vertices, out List<int> indices)
        {
            var newVertices = new List<Vector3>((int)mesh.PointCount);
            var newIndices = new List<int>((int)mesh.PointCount*3);
            var vertexArrayPositions = new int[heightMap.Width, heightMap.Height];
            vertexArrayPositions.Fill(-1);

            mesh.OverFaces((tri, obj) =>
            {
                var triVertices = new[]
                {
                    tri.Point1,
                    tri.Point2,
                    tri.Point3
                };

                foreach (var holeMarker in outputCull)
                {
                    var count = 0;
                    foreach (var vertex in triVertices)
                    {
                        var idx = new Index2
                        {
                            X = (int)vertex.X,
                            Y = (int)vertex.Y
                        };

                        // The triangle abuts one of the hole markers
                        if (holeMarker == idx) return;

                        // The triangle is within the hole markers neighborhood
                        if (Index2.Abs(idx - holeMarker) <= Index2.One) count++;
                    }
                    if (count > 2) return;
                }

                if (GeometryHelpers.IsCounterClockwise(triVertices[0], triVertices[1], triVertices[2]))
                {
                    var temp = triVertices[1];
                    triVertices[1] = triVertices[2];
                    triVertices[2] = temp;
                }

                foreach (var vertex in triVertices)
                {
                    if (vertexArrayPositions[(int) vertex.X, (int) vertex.Y] == -1)
                    {
                        vertexArrayPositions[(int) vertex.X, (int) vertex.Y] = newVertices.Count;
                        newVertices.Add(new Vector3(vertex, heightMap.Eval(vertex.X, vertex.Y)));
                    }

                    newIndices.Add(vertexArrayPositions[(int) vertex.X, (int) vertex.Y]);
                }

            });

            vertices = newVertices;
            indices = newIndices;
        }
Exemplo n.º 9
0
        public void Index2DivisionTest()
        {
            Index2 i1 = new Index2(20, 15); // Startwert
            Index2 i2 = new Index2(6, 5); // Multiplikation mit 3
            Index2 i3 = new Index2(-10, -7); // Multi mit -2

            Assert.AreEqual(i2, i1 / 3);
            Assert.AreEqual(i3, i1 / -2);
        }
Exemplo n.º 10
0
        protected override void OnDrawContent(SpriteBatch batch, Rectangle contentArea, GameTime gameTime, float alpha)
        {
            batch.Draw(Skin.Pix, new Rectangle(contentArea.X - 2, contentArea.Y - 2, contentArea.Width + 4, contentArea.Height + 4), Color.Black);
            batch.Draw(Scene.MiniMapTexture, new Rectangle(contentArea.X, contentArea.Y, contentArea.Width, contentArea.Height), Color.White);

            Index2 center = new Index2((contentArea.Width / 2) + contentArea.X, (contentArea.Height / 2) + contentArea.Y);

            batch.Draw(Skin.Pix, new Rectangle(center.X - 1, center.Y - 1, 2, 2), Color.White);
        }
Exemplo n.º 11
0
        public void Index2AdditionTest()
        {
            Index2 i1 = new Index2(20, 15);     // Startwert
            Index2 i2 = new Index2(-100, -130); // Negativ Addition
            Index2 i3 = new Index2(-80, -115);  // Ergebnis i1 + i2
            Index2 i4 = new Index2(77, 44); // positive Addition
            Index2 i5 = new Index2(97, 59);  // Ergebnis i1 + i4

            // Addition
            Assert.AreEqual(i3, i1 + i2);
            Assert.AreEqual(i5, i1 + i4);
        }
Exemplo n.º 12
0
        public Color[] DoSomething(Light[] lights, Color ambient, bool[,] obstacles, Rectangle renderArea, Rectangle influenceArea, int downscale)
        {
            scale      = 1f / downscale;
            lightArray = new LightArray(renderArea.Width * renderArea.Height, ambient);
            Light[]   smallerLights        = new Light[lights.Length];
            Rectangle smallerRenderArea    = new Rectangle((int)(renderArea.X * scale), (int)(renderArea.Y * scale), (int)(renderArea.Width * scale), (int)(renderArea.Height * scale));
            Rectangle smallerInfluenceArea = new Rectangle((int)(influenceArea.X * scale), (int)(influenceArea.Y * scale), (int)(influenceArea.Width * scale), (int)(influenceArea.Height * scale));

            for (int i = 0; i < smallerLights.Length; i++)
            {
                smallerLights[i] = new Light(lights[i].Position * scale, (short)(lights[i].Radius * scale), lights[i].Brightness, lights[i].Color);
                DebugRenderer.AddDebugObjectWorldSingleCall(new DebugLight(lights[i], Color.AliceBlue));
            }
            Index2[][] pointsToCheck = new Index2[lights.Length][];
            for (int i = 0; i < smallerLights.Length; i++)
            {
                pointsToCheck[i] = Circle.CalculateEdge(smallerLights[i].Position, smallerLights[i].Radius);
                foreach (var currentPoint in pointsToCheck[i])
                {
                    if (smallerRenderArea.Contains(currentPoint) || smallerRenderArea.Contains(smallerLights[i].Position))
                    {
                        foreach (var raycast in new LightRaycast(smallerLights[i], smallerLights[i].Position, currentPoint))
                        {
                            if (!smallerInfluenceArea.Contains(raycast))                             //TODO: Use binarysearch
                            {
                                continue;
                            }
                            int x = raycast.X - smallerRenderArea.X;
                            int y = raycast.Y - smallerRenderArea.Y;
                            if (obstacles[x, y])
                            {
                                break;
                            }
                            if (!smallerRenderArea.Contains(raycast))
                            {
                                continue;
                            }
                            for (int xOff = 0; xOff < downscale; xOff++)
                            {
                                for (int yOff = 0; yOff < downscale; yOff++)
                                {
                                    lightArray.Set((downscale * y + yOff) * renderArea.Width + (downscale * x + xOff), smallerLights[i].Color);
                                }
                            }
                        }
                    }
                }
            }

            return(lightArray.ToColorArray());
        }
        private static void GPUMult(Index2 index, ArrayView2D <double> aView, ArrayView2D <double> bView,
                                    ArrayView2D <double> resView)
        {
            int x = index.X; //matrix one row
            int y = index.Y; //matrix two column

            double sum = 0;

            for (int i = 0; i < aView.Height; i++)
            {
                sum += aView[x, i] * bView[i, y];
            }
            resView[index] = sum;
        }
            /// <summary>
            ///
            /// </summary>
            /// <param name="i"></param>
            /// <param name="j"></param>
            /// <param name="current"></param>
            /// <returns></returns>
            public int NextAt(Index2 index, int[,] current)
            {
                int sum   = GetNeighborSum(index, current);
                int state = current[index.I, index.J];

                if (state == 0)
                {
                    return((sum == 3) ? 1 : 0);
                }
                else
                {
                    return((sum < 2 || sum > 3) ? 0 : 1);
                }
            }
Exemplo n.º 15
0
        public Index2[] FloodFill(Index2 point, List <Index2> result)
        {
            if (result.Contains(point) || IsEdge(point))
            {
                return(result.ToArray());
            }
            result.Add(point);
            foreach (var p in GetNeighbours(point))
            {
                FloodFill(p, result);
            }

            return(result.ToArray());
        }
Exemplo n.º 16
0
 void DisableEnemySpawningInSector(Index2 sector, bool destroyEnemies = true)
 {
     if (destroyEnemies)
     {
         foreach (Enemy e in Actor.FindObjectsInSector <Enemy>(Sector))
         {
             Destroy(e.gameObject);
         }
     }
     foreach (EnemySpawnPoint sp in Actor.FindObjectsInSector <EnemySpawnPoint>(sector))
     {
         sp.SpawningEnabled = false;
     }
 }
Exemplo n.º 17
0
        public void TestPerf()
        {
            // Specifie l'ordre des clefs trie
            Index2 <Model> tree = new Index2 <Model>(null,
                                                     c => c.Ope5,
                                                     c => c.Car2,
                                                     c => c.Qs3,
                                                     c => c.Pu1,
                                                     c => c.Pre4
                                                     );

            tree.Sort(Datas.Matrix);  // on construit

            var filter = tree.GetEvaluator <Model1>(
                c => c.Dgh5,
                c => c.Re2,
                c => c.Df3,
                c => c.az1,
                c => c.Klm4
                );

            Stopwatch st = new Stopwatch();

            var m = new Model1()
            {
                Dgh5 = 2, Re2 = null, Df3 = null, az1 = 23
            };

            st.Start();
            Assert.AreEqual(filter(m), true);
            st.Stop();
            Debug.WriteLine(st.Elapsed.TotalMilliseconds);

            var count = 1000;

            st.Restart();
            for (int i = 0; i < count; i++)
            {
                filter(m);
            }

            st.Stop();
            Debug.WriteLine(st.Elapsed.TotalMilliseconds / count);


            /*
             * 6,5106
             * 0,0009812
             */
        }
Exemplo n.º 18
0
        public static void Execute(Index2 index, ArrayView3D <byte> destBuffer, Index2 offset, byte[] color)
        {
            if (color == null)
            {
                throw new ArgumentNullException(nameof(color));
            }

            using (MemoryBuffer <byte> c = HardwareAcceleratorManager.GPUAccelerator.Allocate <byte>(color.Length))
            {
                c.CopyFrom(color, 0, 0, color.Length);
                kernel(index, destBuffer, offset, c);
                HardwareAcceleratorManager.GPUAccelerator.Synchronize();
            }
        }
        private static void strategy(Index2 index, ArrayView2D <byte> indexedBitmapBuffer,
                                     ArrayView2D <int> bitmapTile, ArrayView <int> colors)
        {
            int c = bitmapTile[index];

            for (int i = 0; i < colors.Length; i++)
            {
                if (colors[i] == c)
                {
                    indexedBitmapBuffer[index] = (byte)i;
                    break;
                }
            }
        }
Exemplo n.º 20
0
 public static void CopyGroupedTo <T>(this ArrayView2D <T> sourceView, ArrayView2D <T> targetView, Index threadIdx)
     where T : struct
 {
     Debug.Assert(sourceView.Extent <= targetView.Extent, "Target view out of range");
     Debug.Assert(threadIdx.X >= Index.Zero && threadIdx.X < Group.Dimension.X, "X thread-index out of range");
     for (Index i = threadIdx.X; i < sourceView.Extent.X; i += Group.Dimension.X)
     {
         for (Index j = 0; j < sourceView.Extent.Y; ++j)
         {
             var idx = new Index2(i, j);
             targetView[idx] = sourceView[idx];
         }
     }
 }
Exemplo n.º 21
0
        protected override void OnDrawContent(SpriteBatch batch, Rectangle contentArea, GameTime gameTime, float alpha)
        {
            if (Scene == null || Scene.MiniMapTexture == null)
            {
                return;
            }

            batch.Draw(Skin.Pix, new Rectangle(contentArea.X - 2, contentArea.Y - 2, contentArea.Width + 4, contentArea.Height + 4), Color.Black);
            batch.Draw(Scene.MiniMapTexture, new Rectangle(contentArea.X, contentArea.Y, contentArea.Width, contentArea.Height), Color.White);

            Index2 center = new Index2((contentArea.Width / 2) + contentArea.X, (contentArea.Height / 2) + contentArea.Y);

            batch.Draw(Skin.Pix, new Rectangle(center.X - 1, center.Y - 1, 2, 2), Color.White);
        }
Exemplo n.º 22
0
        public void CopyFrom(
            AcceleratorStream stream,
            T[][] source,
            Index2 sourceOffset,
            Index2 targetOffset,
            Index2 extent)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }

            if (extent.X < 0 || extent.Y < 0 ||
                extent.X > source.Length)
            {
                throw new ArgumentOutOfRangeException(nameof(extent));
            }

            if (sourceOffset.X < 0 || sourceOffset.Y < 0 ||
                sourceOffset.X >= extent.X || sourceOffset.Y >= extent.Y)
            {
                throw new ArgumentOutOfRangeException(nameof(sourceOffset));
            }

            var tempBuffer = new T[extent.Size];

            for (int i = 0; i < extent.X; ++i)
            {
                var subData = source[i + sourceOffset.X];
                if (subData == null)
                {
                    continue;
                }

                // Skip entries that are out of bounds
                for (int j = 0, e = IntrinsicMath.Min(subData.Length, extent.Y); j < e; ++j)
                {
                    var targetIdx = new Index2(i, j).ComputeLinearIndex(extent);
                    tempBuffer[targetIdx] = subData[j + sourceOffset.Y];
                }
            }

            buffer.CopyFrom(
                stream,
                tempBuffer,
                0,
                targetOffset,
                extent.Size);
        }
Exemplo n.º 23
0
        public void CopyTo(
            AcceleratorStream stream,
            T[,] target,
            Index2 sourceOffset,
            Index2 targetOffset,
            Index2 extent)
        {
            if (target == null)
            {
                throw new ArgumentNullException(nameof(target));
            }

            if (sourceOffset.X < 0 || sourceOffset.Y < 0 ||
                sourceOffset.X >= Extent.X ||
                sourceOffset.Y >= Extent.Y)
            {
                throw new ArgumentOutOfRangeException(nameof(sourceOffset));
            }

            if (targetOffset.X < 0 || targetOffset.Y < 0 ||
                targetOffset.X >= target.GetLength(0) ||
                targetOffset.Y >= target.GetLength(1))
            {
                throw new ArgumentOutOfRangeException(nameof(targetOffset));
            }

            if (extent.X < 0 || extent.Y < 0 ||
                sourceOffset.X + extent.X > Extent.X ||
                sourceOffset.Y + extent.Y > Extent.Y ||
                targetOffset.X + extent.X > target.GetLength(0) ||
                targetOffset.Y + extent.Y > target.GetLength(1))
            {
                throw new ArgumentOutOfRangeException(nameof(extent));
            }

            var tempBuffer = new T[extent.Size];

            buffer.CopyTo(stream, tempBuffer, sourceOffset, 0, extent);

            for (int i = 0; i < extent.X; ++i)
            {
                for (int j = 0; j < extent.Y; ++j)
                {
                    var sourceIdx = new Index2(i, j).ComputeLinearIndex(extent);
                    target[i + targetOffset.X, j + targetOffset.Y] =
                        tempBuffer[sourceIdx];
                }
            }
        }
Exemplo n.º 24
0
        public static Area ToArea(this Rectangle rectangle)
        {
            Index2[] area = new Index2[rectangle.Width * rectangle.Height];
            int      i    = 0;

            for (int x = 0; x < rectangle.Width; x++)
            {
                for (int y = 0; y < rectangle.Height; y++)
                {
                    area[i] = new Index2(x, y);
                    i++;
                }
            }
            return(new Area(area));
        }
Exemplo n.º 25
0
        public void InstanceMethodIndex2EntryPoint(int length)
        {
            var instanceHost = new InstaceHost();
            Action <Index2, ArrayView <int>, Index2> kernel = instanceHost.InstanceKernel;

            var extent = new Index2(length, length);

            using var buffer = Accelerator.Allocate <int>(extent.Size);
            Execute(kernel.Method, extent, buffer.View, extent);

            var expected =
                Enumerable.Range(instanceHost.InstanceOffset(), extent.Size).ToArray();

            Verify(buffer, expected);
        }
Exemplo n.º 26
0
        public void StaticFieldCapturingLambdaIndex2EntryPoint(int length)
        {
            Action <Index2, ArrayView <int>, Index2> kernel =
                (index, output, extent) =>
            {
                var linearIndex = index.ComputeLinearIndex(extent);
                output[linearIndex] = linearIndex + CaptureHost.CaptureField;
            };

            var extent = new Index2(length, length);

            using var buffer = Accelerator.Allocate <int>(extent.Size);
            Assert.Throws <NotSupportedException>(() =>
                                                  Execute(kernel.Method, extent, buffer.View, extent));
        }
Exemplo n.º 27
0
        public float[,] GetHeightmap(Index2 chunkIndex)
        {
            float[,] values = new float[Chunk.CHUNKSIZE_X, Chunk.CHUNKSIZE_Y];

            chunkIndex = new Index2(chunkIndex.X * Chunk.CHUNKSIZE_X, chunkIndex.Y * Chunk.CHUNKSIZE_Y);

            for (int x = 0; x < Chunk.CHUNKSIZE_X; x++)
            {
                for (int y = 0; y < Chunk.CHUNKSIZE_Y; y++)
                {
                    values[x, y] = 0f;
                }
            }
            return(values);
        }
Exemplo n.º 28
0
        public AnimatedTileLighting(BasicTile tile)
        {
            Position = tile.Position;
            Index    = tile.Index;
            var array = tile.Animations.GetAnimations().Where(a => a.Name.EndsWith("shadow")).ToArray();

            animations = new AnimationCollection(tile.Animations.StartAnimation + "shadow");
            if (array.Length <= 0)
            {
                GameConsole.Warning("Warning: No shadow animations found.");
                return;
            }
            animations.AddAnimations(array);
            tile.Animations.AnimationChanged += AnimationChanged;
        }
Exemplo n.º 29
0
        internal static void FullyConnectedLayer2D(Index2 currentInput, ArrayView3D <float> weights, ArrayView2D <float> error, ArrayView2D <float> activatedPreviousLayer, ArrayView2D <float> bias, ArrayView <float> variables)
        {
            var fac = error[currentInput] * variables[new Index1(0)];

            bias[currentInput] -= fac;
            for (int x = 0; x < activatedPreviousLayer.Width; x++)
            {
                for (int y = 0; y < activatedPreviousLayer.Height; y++)
                {
                    Index2 asosIndex  = new Index2(x, y);
                    var    adjustment = fac * activatedPreviousLayer[asosIndex];
                    weights[new Index3(currentInput, x * y + x)] -= adjustment;
                }
            }
        }
Exemplo n.º 30
0
        public float[,] GetHeightmap(Index2 chunkIndex)
        {
            float[,] values = new float[Chunk.CHUNKSIZE_X , Chunk.CHUNKSIZE_Y ];

            chunkIndex = new Index2(chunkIndex.X * Chunk.CHUNKSIZE_X , chunkIndex.Y * Chunk.CHUNKSIZE_Y );

            for (int x = 0; x < Chunk.CHUNKSIZE_X ; x++)
            {
                for (int y = 0; y < Chunk.CHUNKSIZE_Y ; y++)
                {
                    values[x, y] = 0f;
                }
            }
            return values;
        }
Exemplo n.º 31
0
        private static void GPUMult(Index2 index, ArrayView2D <T> aView, ArrayView2D <T> bView,
                                    ArrayView2D <T> resView)
        {
            int x = index.X; //matrix one row
            int y = index.Y; //matrix two column

            //this needs to be done explicitly so we know where to start
            T sum = aView[x, 0].Multiply(bView[0, y]);

            for (int i = 1; i < aView.Height; i++)
            {
                sum = sum.Add(aView[x, i].Multiply(bView[i, y]));
            }
            resView[index] = sum;
        }
Exemplo n.º 32
0
            /// <summary>
            ///
            /// </summary>
            /// <param name="i"></param>
            /// <param name="j"></param>
            /// <param name="current"></param>
            /// <returns></returns>
            public int NextState(Index2 index, int[,] current)
            {
                int sum = GetNeighborSum(index, current);

                int state = current[index.I, index.J];
                //the state that will be output based on rules
                int output = 0;

                //if current state is "alive"
                if (state == 1)
                {
                    //loneliness
                    if (sum < 2)
                    {
                        output = 0;
                    }

                    //balance
                    if (sum >= 2 && sum <= 3)
                    {
                        output = 1;
                    }

                    //overcrowding
                    if (sum > 3)
                    {
                        output = 0;
                    }
                }

                //if current state is "dead"
                if (state == 0)
                {
                    //procreation
                    if (sum == 3)
                    {
                        output = 1;
                    }

                    //no procreation
                    else
                    {
                        output = 0;
                    }
                }

                return(output);
            }
Exemplo n.º 33
0
        protected override void RequestDraw()
        {
            MainState _currentState = _state;

            if (_currentState != null)
            {
                Index2 cells = _currentState.Map.GetCellCount();
                DrawPlayground(cells, _currentState.Map.Tiles);

                foreach (var item in _currentState.Items)
                {
                    if (item is AnthillState)
                    {
                        AnthillState anthillState = item as AnthillState;
                        DrawItem(item.Id, item.Position, anthillState.Radius, null, null, Color.Brown, null, null, null, null, null, null);
                    }

                    if (item is AntState)
                    {
                        AntState antState = item as AntState;
                        // DrawItem(item.Id, item.Position, antState.Radius, Color.Black);
                    }

                    if (item is SugarState)
                    {
                        SugarState sugarState = item as SugarState;
                        // DrawItem(item.Id, item.Position, sugarState.Radius, Color.White);
                    }

                    if (item is AppleState)
                    {
                        AppleState appleState = item as AppleState;
                        // DrawItem(item.Id, item.Position, 5, Color.LightGreen);
                    }

                    if (item is MarkerState)
                    {
                        MarkerState markerState = item as MarkerState;
                        // DrawItem(item.Id, item.Position, 10, Color.Yellow);
                    }

                    if (item is BugState)
                    {
                        // DrawItem(item.Id, item.Position, 10, Color.Blue);
                    }
                }
            }
        }
Exemplo n.º 34
0
        private void InitFlat(bool blockBorder, TileSpeed speed)
        {
            Map = Map.CreateMap(MapPreset.Small, true);
            Index2 cells = Map.GetCellCount();

            for (int x = 0; x < cells.X; x++)
            {
                for (int y = 0; y < cells.Y; y++)
                {
                    Map.Tiles[x, y].Speed = speed;
                }
            }
            Engine.Init(Map);

            Engine.InsertItem(Item);
        }
Exemplo n.º 35
0
        internal static void SoftmaxLayer2D(Index2 currentInput, ArrayView2D <float> error, ArrayView2D <float> errorNextLayer, ArrayView3D <float> weightNextLayer, ArrayView2D <float> derived, ArrayView2D <float> should, ArrayView <float> variable)
        {
            int   xBounds = (int)errorNextLayer.Extent.X;
            int   yBounds = (int)errorNextLayer.Extent.Y;
            float sum     = 0.0f;

            for (int x = 0; x < xBounds; x++)
            {
                for (int y = 0; y < yBounds; y++)
                {
                    Index2 varIndex = new Index2(x, y);
                    sum += errorNextLayer[varIndex] * weightNextLayer[new Index3(varIndex, currentInput.X * currentInput.Y + currentInput.X)];
                }
            }
            error[currentInput] = sum * derived[currentInput];
        }
            public OceanSeismicMultithreaded(int n, int m)
            {
                // Create new output cube
                SeismicCube       outputCube = SeismicCube.NullObject;
                SeismicCollection coll       = SeismicCollection.NullObject;
                SeismicRoot       seisRoot;

                seisRoot = SeismicRoot.Get(PetrelProject.PrimaryProject);
                if (!seisRoot.HasSeismicProject)
                {
                    using (ITransaction tr = DataManager.NewTransaction())
                    {
                        tr.Lock(seisRoot);
                        seisRoot.CreateSeismicProject();
                        tr.Commit();
                    }
                }
                SeismicProject proj = seisRoot.SeismicProject;

                using (ITransaction tr = DataManager.NewTransaction())
                {
                    tr.Lock(proj);
                    coll = proj.CreateSeismicCollection("Test Survey Async " + n.ToString() + "x" + m.ToString());
                    tr.Lock(coll);
                    Index3  size             = new Index3(n, n, m);
                    Point3  origin           = new Point3(13579.75, 24680.08, 0.0);
                    Vector3 iSpacing         = new Vector3(100.0, 0.0, 0.000);
                    Vector3 jSpacing         = new Vector3(0.0, 100.0, 0.000);
                    Vector3 kSpacing         = new Vector3(0.0, 0.0, -100.0);
                    Index2  annotationOrigin = new Index2(0, 0);
                    Index2  annotationInc    = new Index2(1, 1);
                    if (coll.CanCreateSeismicCube(size, origin, iSpacing, jSpacing, kSpacing))
                    {
                        Type     dataType = typeof(float);
                        Domain   vDomain  = Domain.ELEVATION_DEPTH;
                        Template tmpl     = PetrelProject.WellKnownTemplates
                                            .SeismicColorGroup.SeismicDefault;
                        Range1 <double> r = new Range1 <double>(0.0, 140.0);
                        _cube = coll.CreateSeismicCube(size, origin, iSpacing, jSpacing, kSpacing, annotationOrigin, annotationInc, dataType, vDomain, tmpl, r);
                    }
                    if (_cube.IsWritable)
                    {
                        MakeCube(_cube);
                    }
                    tr.Commit();
                }
            }
Exemplo n.º 37
0
        public static void CalculateSignatureLengthDerivative(Index2 index, ArrayView3D <float> output, ArrayView3D <short> input, short maxValue)
        {
            var x = index.X;
            var y = index.Y;

            if (x == 0)
            {
                x = 1;
            }
            if (x == input.Width - 1)
            {
                x = input.Width - 2;
            }
            if (y == 0)
            {
                y = 1;
            }
            if (y == input.Height - 1)
            {
                y = input.Height - 2;
            }

            var depth = input.Depth;

            float xDiffComponentSum = 0;
            float yDiffComponentSum = 0;

            for (int i = 0; i < depth; i++)
            {
                var val1  = XMath.Clamp(input[x - 1, y, i], (short)0, maxValue);
                var val2  = XMath.Clamp(input[x + 1, y, i], (short)0, maxValue);
                var xDiff = val2 - val1;
                xDiffComponentSum += xDiff * xDiff;

                val1 = XMath.Clamp(input[x, y - 1, i], (short)0, maxValue);
                val2 = XMath.Clamp(input[x, y + 1, i], (short)0, maxValue);
                var yDiff = val2 - val1;
                yDiffComponentSum += yDiff * yDiff;
            }

            var xDiffLength = XMath.Sqrt(xDiffComponentSum);
            var yDiffLength = XMath.Sqrt(yDiffComponentSum);

            output[index.X, index.Y, 0] = xDiffLength;
            output[index.X, index.Y, 1] = yDiffLength;
            output[index.X, index.Y, 2] = XMath.Max(xDiffLength, yDiffLength);
        }
Exemplo n.º 38
0
        public void Index2ComparerTest()
        {
            Index2 i1 = new Index2(12, 13);
            Index2 i2 = new Index2(12, 15);
            Index2 i3 = new Index2(22, 13);
            Index2 i4 = new Index2(12, 13);

            Assert.AreEqual(i1, i1);
            Assert.AreEqual(i1, i4);
            Assert.AreNotEqual(i1, i2);
            Assert.AreNotEqual(i1, i3);

            Assert.IsTrue(i1 == i1);
            Assert.IsTrue(i1 == i4);
            Assert.IsTrue(i1 != i2);
            Assert.IsTrue(i1 != i3);
        }
Exemplo n.º 39
0
        private void Update(EvaluationContext context)
        {
            var overwrites = context.VariationOverwrites;

            // var id = new Variator.VariationId(Guid.Empty, Guid.Empty);
            if (!overwrites.TryGetValue(Variator.VariationId.EmptySet, out var entry))
            {
                entry = new VariationSelector();
                overwrites.Add(Variator.VariationId.EmptySet, entry);
            }

            entry.Index1 = Index1.GetValue(context);
            entry.Index2 = Index2.GetValue(context);
            entry.Weight = Weight.GetValue(context);
            Result.Value = Input.GetValue(context);
            overwrites.Remove(Variator.VariationId.EmptySet);
        }
Exemplo n.º 40
0
        public void Index2ComparerTest()
        {
            Index2 i1 = new Index2(12, 13);
            Index2 i2 = new Index2(12, 15);
            Index2 i3 = new Index2(22, 13);
            Index2 i4 = new Index2(12, 13);

            Assert.Equals(i1, i1);
            Assert.Equals(i1, i4);
            Assert.AreNotEqual(i1, i2);
            Assert.AreNotEqual(i1, i3);

            // Assert.True(i1 == i1);
            Assert.True(i1 == i4);
            Assert.True(i1 != i2);
            Assert.True(i1 != i3);
        }
Exemplo n.º 41
0
        public void CalculateLightmap(Renderer2D renderer, Matrix cam, Index2 mapSize, Color ambient)
        {
            var tempRender = CalculateRenderView(mapSize);

            if (!tempRender.HasValue)
            {
                return;
            }
            renderSize    = tempRender.Value;
            influenceArea = CalculateInfluenceArea();
            obstacles     = GrabObstacles(renderer, cam);
            texture?.Dispose();
            texture     = new Texture2D(graphicsDevice, renderSize.Width, renderSize.Height);
            textureData = new FieldOfView().DoSomething(lights.ToArray(), ambient, obstacles, renderSize, influenceArea, 2);
            texture.SetData(textureData);
            //texture = texture.GaussianBlur(3);
        }
Exemplo n.º 42
0
        public float[,] GetHeightmap(Index2 chunkIndex)
        {
            float[,] values = new float[Chunk.CHUNKSIZE_X , Chunk.CHUNKSIZE_Y];

            chunkIndex = new Index2(chunkIndex.X * Chunk.CHUNKSIZE_X, chunkIndex.Y * Chunk.CHUNKSIZE_Y);

            float[,] heights = BiomeNoiseGenerator.GetTileableNoiseMap2D(chunkIndex.X, chunkIndex.Y, Chunk.CHUNKSIZE_X , Chunk.CHUNKSIZE_Y, Planet.Size.X * Chunk.CHUNKSIZE_X , Planet.Size.Y * Chunk.CHUNKSIZE_Y );

            for (int x = 0; x < Chunk.CHUNKSIZE_X ; x++)
            {
                for (int y = 0; y < Chunk.CHUNKSIZE_Y ; y++)
                {
                    values[x, y] = (heights[x, y] / 2 + 0.5f) * ValueRange + ValueRangeOffset;
                }
            }
            return values;
        }
Exemplo n.º 43
0
        public float[,] GetHeightmap(Index2 chunkIndex)
        {
            float[,] values = new float[Chunk.CHUNKSIZE_X, Chunk.CHUNKSIZE_Y];

            chunkIndex = new Index2(chunkIndex.X * Chunk.CHUNKSIZE_X, chunkIndex.Y * Chunk.CHUNKSIZE_Y);

            float[,] heights = BiomeNoiseGenerator.GetTileableNoiseMap2D(chunkIndex.X, chunkIndex.Y, Chunk.CHUNKSIZE_X, Chunk.CHUNKSIZE_Y, Planet.Size.X * Chunk.CHUNKSIZE_X, Planet.Size.Y * Chunk.CHUNKSIZE_Y);

            for (int x = 0; x < Chunk.CHUNKSIZE_X; x++)
            {
                for (int y = 0; y < Chunk.CHUNKSIZE_Y; y++)
                {
                    values[x, y] = (heights[x, y] / 2 + 0.5f) * ValueRange + ValueRangeOffset;
                }
            }
            return(values);
        }
Exemplo n.º 44
0
    void OverrideSectorWithThisSectorsVoxels(Index2 sector, bool doOverride)
    {
        OverworldTerrainEngine eng = OverworldTerrainEngine.Instance;

        OverworldChunk ch = eng.GetChunkForSector(sector) as OverworldChunk;

        if (ch != null)
        {
            OverrideChunkWithThisSectorsVoxels(ch, doOverride);

            OverworldChunk ch_down = ch.GetChunkDirectlyBelowThisChunk() as OverworldChunk;        // TODO: Better methods for getting neighbors
            if (ch_down != null)
            {
                OverrideChunkWithThisSectorsVoxels(ch_down, doOverride);
            }
        }
    }
Exemplo n.º 45
0
        public void LoadChunkTest()
        {
            int planet = 2;
            Index2 index = new Index2(6, 7);
            IChunkColumn result = null;
            int loadCallCounter = 0;
            int saveCallCounter = 0;

            GlobalChunkCache cache = new GlobalChunkCache(
                (p, i) =>
                {
                    Assert.AreEqual(i, index);
                    loadCallCounter++;
                    return result = new TestChunkColumn(planet, index);
                },
                (p, i, c) =>
                {
                    Assert.AreEqual(p, planet);
                    Assert.AreEqual(i, index);
                    Assert.AreEqual(c, result);
                    saveCallCounter++;
                });

            Assert.AreEqual(0, cache.LoadedChunkColumns);
            Assert.AreEqual(0, loadCallCounter);
            Assert.AreEqual(0, saveCallCounter);

            // Chunk laden
            IChunkColumn x = cache.Subscribe(planet, index);
            Assert.AreEqual(x, result);
            Assert.AreEqual(x.Planet, planet);
            Assert.AreEqual(x.Index, index);
            Assert.AreEqual(1, loadCallCounter);
            Assert.AreEqual(0, saveCallCounter);

            Assert.AreEqual(1, cache.LoadedChunkColumns);

            // Chunk unload
            cache.Release(planet, index);

            Assert.AreEqual(0, cache.LoadedChunkColumns);
            Assert.AreEqual(1, loadCallCounter);
            Assert.AreEqual(1, saveCallCounter);
        }
Exemplo n.º 46
0
        public void Index3AdditionTest()
        {
            Index3 i1 = new Index3(20, 15, 17);     // Startwert
            Index2 in2 = new Index2(-100, -130); // Negativ Addition (2D)
            Index3 in3 = new Index3(-100, -130, -33); // Negativ Addition (3D)
            Index3 in2r = new Index3(-80, -115, 17);  // Ergebnis i1 + in2
            Index3 in3r = new Index3(-80, -115, -16);  // Ergebnis i1 + in3

            Index2 ip2 = new Index2(77, 44); // positive Addition (2D)
            Index3 ip3 = new Index3(77, 44, 54); // positive Addition (3D)
            Index3 ip2r = new Index3(97, 59, 17);  // Ergebnis i1 + ip2
            Index3 ip3r = new Index3(97, 59, 71);  // Ergebnis i1 + ip3

            // Addition
            Assert.AreEqual(in2r, i1 + in2);
            Assert.AreEqual(in3r, i1 + in3);
            Assert.AreEqual(ip2r, i1 + ip2);
            Assert.AreEqual(ip3r, i1 + ip3);
        }
Exemplo n.º 47
0
        public void Update()
        {
            MouseState state = Mouse.GetState();
            mousePointer = new Index2(state.X, state.Y);

            if (state.LeftButton == ButtonState.Pressed)
            {
                if (!mouseDown)
                {
                    mouseDown = true;
                }
            }
            else
            {
                if (mouseDown)
                {
                    mouseDown = false;
                    if (OnLeftMouseUp != null)
                        OnLeftMouseUp(mousePointer);
                }
            }
        }
Exemplo n.º 48
0
        public void Index2ConstructorTest()
        {
            // Parameterlos
            Index2 i1 = new Index2();
            Assert.AreEqual(0, i1.X);
            Assert.AreEqual(0, i1.Y);

            // Simpler Parameter
            Index2 i2 = new Index2(21, 32);
            Assert.AreEqual(21, i2.X);
            Assert.AreEqual(32, i2.Y);

            // Index2-Parameter
            Index2 i3 = new Index2(new Index2(-2, 80));
            Assert.AreEqual(-2, i3.X);
            Assert.AreEqual(80, i3.Y);

            // Index3 Parameter
            Index2 i4 = new Index2(new Index3(int.MinValue, int.MaxValue, 0));
            Assert.AreEqual(int.MinValue, i4.X);
            Assert.AreEqual(int.MaxValue, i4.Y);
        }
Exemplo n.º 49
0
        public IChunk[] GenerateChunk(IEnumerable<IBlockDefinition> blockDefinitions, IPlanet planet, Index2 index)
        {
            IBlockDefinition sandDefinition = blockDefinitions.FirstOrDefault(d => typeof(SandBlockDefinition) == d.GetType());
            ushort sandIndex = (ushort)(Array.IndexOf(blockDefinitions.ToArray(), sandDefinition) + 1);

            IBlockDefinition groundDefinition = blockDefinitions.FirstOrDefault(d => typeof(GroundBlockDefinition) == d.GetType());
            ushort groundIndex = (ushort)(Array.IndexOf(blockDefinitions.ToArray(), groundDefinition) + 1);

            IBlockDefinition stoneDefinition = blockDefinitions.FirstOrDefault(d => typeof(StoneBlockDefinition) == d.GetType());
            ushort stoneIndex = (ushort)(Array.IndexOf(blockDefinitions.ToArray(), stoneDefinition) + 1);

            IBlockDefinition waterDefinition = blockDefinitions.FirstOrDefault(d => typeof(WaterBlockDefinition) == d.GetType());
            ushort waterIndex = (ushort)(Array.IndexOf(blockDefinitions.ToArray(), waterDefinition) + 1);

            IBlockDefinition grassDefinition = blockDefinitions.FirstOrDefault(d => typeof(GrassBlockDefinition) == d.GetType());
            ushort grassIndex = (ushort)(Array.IndexOf(blockDefinitions.ToArray(), grassDefinition) + 1);

            if (!(planet is ComplexPlanet))
                throw new ArgumentException("planet is not a Type of ComplexPlanet");

            ComplexPlanet localPlanet = (ComplexPlanet)planet;

            float[,] localHeightmap = localPlanet.BiomeGenerator.GetHeightmap(index);

            IChunk[] chunks = new IChunk[planet.Size.Z];
            for (int i = 0; i < planet.Size.Z; i++)
                chunks[i] = new Chunk(new Index3(index, i), planet.Id);

            int obersteSchicht;
            bool surfaceBlock;
            bool ozeanSurface;

            for (int x = 0; x < Chunk.CHUNKSIZE_X; x++)
            {
                for (int y = 0; y < Chunk.CHUNKSIZE_Y; y++)
                {
                    obersteSchicht = 5;
                    surfaceBlock = true;
                    ozeanSurface = false;

                    for (int i = chunks.Length - 1; i >= 0; i--)
                    {
                        for (int z = Chunk.CHUNKSIZE_Z - 1; z >= 0; z--)
                        {
                            int absoluteZ = (z + (i * Chunk.CHUNKSIZE_Z));

                            if (absoluteZ <= localHeightmap[x, y] * localPlanet.Size.Z * Chunk.CHUNKSIZE_Z)
                            {
                                if (obersteSchicht > 0)
                                {
                                    float temp = localPlanet.ClimateMap.GetTemperature(new Index3(index.X * Chunk.CHUNKSIZE_X + x, index.Y * Chunk.CHUNKSIZE_Y + y, i * Chunk.CHUNKSIZE_Z + z));

                                    if ((ozeanSurface || surfaceBlock) && (absoluteZ <= (localPlanet.BiomeGenerator.SeaLevel + 2)) && (absoluteZ >= (localPlanet.BiomeGenerator.SeaLevel - 2)))
                                    {
                                        chunks[i].SetBlock(x, y, z, sandIndex);
                                    }
                                    else if (temp >= 35)
                                    {
                                        chunks[i].SetBlock(x, y, z, sandIndex);
                                    }
                                    else if (absoluteZ >= localPlanet.Size.Z * Chunk.CHUNKSIZE_Z * 0.6f)
                                    {
                                        if (temp > 12)
                                            chunks[i].SetBlock(x, y, z, groundIndex);
                                        else
                                            chunks[i].SetBlock(x, y, z, stoneIndex);
                                    }
                                    else if (temp >= 8)
                                    {
                                        if (surfaceBlock && !ozeanSurface)
                                        {
                                            chunks[i].SetBlock(x, y, z, grassIndex);
                                            surfaceBlock = false;
                                        }
                                        else
                                        {
                                            chunks[i].SetBlock(x, y, z, groundIndex);
                                        }
                                    }
                                    else
                                    {
                                        chunks[i].SetBlock(x, y, z, groundIndex);
                                    }
                                    obersteSchicht--;
                                }
                                else
                                {
                                    chunks[i].SetBlock(x, y, z, stoneIndex);
                                }

                            }
                            else if ((z + (i * Chunk.CHUNKSIZE_Z)) <= localPlanet.BiomeGenerator.SeaLevel)
                            {

                                chunks[i].SetBlock(x, y, z, waterIndex);
                                ozeanSurface = true;
                            }

                        }
                    }
                }
            }

            //float[,] cloudmap = null;
            ////Biomes.BiomeBlockValue[, ,] blockValues = localPlanet.BiomeGenerator.GetBlockValues(index,heightmap,0f,1f);

            ////for (int x = 0; x < Chunk.CHUNKSIZE_X; x++)
            //Parallel.For(0, Chunk.CHUNKSIZE_X, x =>
            //{
            //    for (int y = 0; y < Chunk.CHUNKSIZE_Y; y++)
            //    {
            //        bool grass = true, sand = false;

            //        for (int i = chunks.Length - 1; i >= 0; i--)
            //        {

            //            for (int z = Chunk.CHUNKSIZE_Z - 1; z >= 0; z--)
            //            {
            //                //Biomes.BiomeBlockValue blockValue = blockValues[x, y, z + i * Chunk.CHUNKSIZE_Z];
            //                int blockHeight = Math.Max(z + Chunk.CHUNKSIZE_Z * (i), 0);
            //                //float density = heightmap[x,y] * (Chunk.CHUNKSIZE_Z * (planet.Size.Z)) - blockHeight;
            //                Index3 blockIndex = new Index3(index.X * Chunk.CHUNKSIZE_X + x, index.Y * Chunk.CHUNKSIZE_Y + y, i * Chunk.CHUNKSIZE_Z + z);

            //                if (blockValue.Density > 0.6f || (z < 3 && i == 0))
            //                {
            //                    if (blockValue.IsDessert || (grass | sand) && (z + (i * Chunk.CHUNKSIZE_Z)) <= localPlanet.BiomeGenerator.SeaLevel && (z + (i * Chunk.CHUNKSIZE_Z)) >= localPlanet.BiomeGenerator.SeaLevel - 2)
            //                    {
            //                        chunks[i].SetBlock(new Index3(x, y, z), new SandBlock());
            //                        grass = false;
            //                        sand = true;
            //                    }
            //                    else if (grass && planet.ClimateMap.GetTemperature(blockIndex) > 18.0f)
            //                    {
            //                        chunks[i].SetBlock(new Index3(x, y, z), new GrassBlock());
            //                        grass = false;
            //                    }
            //                    //else if (z < Chunk.CHUNKSIZE_Z - 1 && noiseplus >= resDensity)
            //                    //{
            //                    //    chunks[i].SetBlock(new Index3(x, y, z), new StoneBlock());
            //                    //}
            //                    else
            //                    {
            //                        chunks[i].SetBlock(new Index3(x, y, z), new GroundBlock());
            //                        grass = false;
            //                    }

            //                }
            //                else if ((z + (i * Chunk.CHUNKSIZE_Z)) <= localPlanet.BiomeGenerator.SeaLevel)
            //                {
            //                    grass = false;
            //                    sand = true;
            //                    chunks[i].SetBlock(new Index3(x, y, z), new WaterBlock());
            //                }
            //            }
            //        }
            //    }
            //});

            return chunks;
        }
Exemplo n.º 50
0
        private bool FillChunkRenderer()
        {
            if (player.ActorHost == null)
                return false;

            Index2 destinationChunk = new Index2(player.ActorHost.Position.ChunkIndex);

            // Nur ausführen wenn der Spieler den Chunk gewechselt hat
            if (destinationChunk != currentChunk)
            {
                localChunkCache.SetCenter(planet, new Index2(player.ActorHost.Position.ChunkIndex));

                int mask = (int)Math.Pow(2, VIEWRANGE) - 1;
                int span = (int)Math.Pow(2, VIEWRANGE);
                int spanOver2 = span >> 1;

                for (int x = 0; x < span; x++)
                {
                    for (int y = 0; y < span; y++)
                    {
                        Index2 local = new Index2(x - spanOver2, y - spanOver2) + destinationChunk;
                        local.NormalizeXY(planet.Size);

                        int virtualX = local.X & mask;
                        int virtualY = local.Y & mask;

                        int rendererIndex = virtualX +
                            (virtualY << VIEWRANGE);

                        for (int z = 0; z < planet.Size.Z; z++)
                        {
                            chunkRenderer[rendererIndex, z].SetChunk(localChunkCache, local.X, local.Y, z);
                        }
                    }
                }

                Index3 comparationIndex = player.ActorHost.Position.ChunkIndex;
                orderedChunkRenderer.Sort((x, y) =>
                {
                    if (!x.ChunkPosition.HasValue) return 1;
                    if (!y.ChunkPosition.HasValue) return -1;

                    Index3 distX = comparationIndex.ShortestDistanceXYZ(x.ChunkPosition.Value, planet.Size);
                    Index3 distY = comparationIndex.ShortestDistanceXYZ(y.ChunkPosition.Value, planet.Size);
                    return distX.LengthSquared().CompareTo(distY.LengthSquared());
                });

                currentChunk = destinationChunk;
            }

            foreach (var renderer in orderedChunkRenderer)
            {
                if (!renderer.NeedUpdate())
                    continue;

                renderer.RegenerateVertexBuffer();
                return true;
            }

            return false;
        }
Exemplo n.º 51
0
        public void Index2ShortestDistanceMethodenTest()
        {
            Index2 size = new Index2(20, 20);
            Index2 i1 = new Index2(5, 7); // Startwert
            Index2 i2 = new Index2(12, 13); // Destinations
            Index2 i3 = new Index2(7, 6); // Results

            Assert.AreEqual(i3.X, i1.ShortestDistanceX(i2.X, size.X));
            Assert.AreEqual(i3.Y, i1.ShortestDistanceY(i2.Y, size.Y));
            Assert.AreEqual(i3, i1.ShortestDistanceXY(i2, size));
        }
 void input_OnLeftMouseUp(Index2 position)
 {
     if (ActiveScreen != null)
     {
         foreach (var control in ActiveScreen.Controls)
         {
             if (position.X >= control.Position.X &&
                 position.X <= control.Position.X + control.Size.X &&
                 position.Y >= control.Position.Y &&
                 position.Y <= control.Position.Y + control.Size.Y)
             {
                 control.FireMouseUp();
             }
         }
     }
 }
Exemplo n.º 53
0
        public void Index2SubtraktionTest()
        {
            Index2 i1 = new Index2(20, 15);     // Startwert
            Index2 i2 = new Index2(-100, -130); // Negativ Addition
            Index2 i3 = new Index2(120, 145);  // Ergebnis i1 - i2
            Index2 i4 = new Index2(77, 44); // positive Addition
            Index2 i5 = new Index2(-57, -29);  // Ergebnis i1 - i4

            // Addition
            Assert.AreEqual(i3, i1 - i2);
            Assert.AreEqual(i5, i1 - i4);
        }
Exemplo n.º 54
0
        public void Index2MultiplikationTest()
        {
            Index2 i1 = new Index2(20, 15); // Startwert
            Index2 i2 = new Index2(60, 45); // Multiplikation mit 3
            Index2 i3 = new Index2(-40, -30); // Multi mit -2

            Assert.AreEqual(i2, i1 * 3);
            Assert.AreEqual(i3, i1 * -2);
        }
Exemplo n.º 55
0
        public override void Update(GameTime gameTime)
        {
            bool nextInteract = false;
            bool nextJump = false;
            bool nextApply = false;
            bool nextInventory = false;
            bool[] nextSlot = new bool[SlotTriggerLength];
            bool nextSlotLeft = false;
            bool nextSlotRight = false;
            MoveX = 0f;
            MoveY = 0f;
            HeadX = 0f;
            HeadY = 0f;

            if (ScreenMode)
            {
                Game.IsMouseVisible = true;
                screenMouse.Update();
                screenKeyboard.Update();
                mousePointer = screenMouse.PointerPosition;
            }
            else
            {
                Game.IsMouseVisible = false;
                gamepad.Update();
                keyboard.Update();
                if (Game.IsActive)
                    mouse.Update();

                foreach (var device in inputDevices)
                {
                    nextInteract |= device.InteractTrigger;
                    nextApply |= device.ApplyTrigger;
                    nextJump |= device.JumpTrigger;
                    nextInventory |= device.InventoryTrigger;
                    nextSlotLeft |= device.SlotLeftTrigger;
                    nextSlotRight |= device.SlotRightTrigger;
                    if (device.SlotTrigger != null)
                        for (int i = 0; i < Math.Min(device.SlotTrigger.Length, SlotTriggerLength); i++)
                            nextSlot[i] |= device.SlotTrigger[i];

                    MoveX += device.MoveX;
                    MoveY += device.MoveY;
                    HeadX += device.HeadX;
                    HeadY += device.HeadY;
                }

                InteractTrigger.Value = nextInteract;
                ApplyTrigger.Value = nextApply;
                InventoryTrigger.Value = nextInventory;
                JumpTrigger.Value = nextJump;
                SlotLeftTrigger.Value = nextSlotLeft;
                SlotRightTrigger.Value = nextSlotRight;
                for (int i = 0; i < SlotTriggerLength; i++)
                    SlotTrigger[i].Value = nextSlot[i];

                MoveX = Math.Min(1, Math.Max(-1, MoveX));
                MoveY = Math.Min(1, Math.Max(-1, MoveY));
            }
        }
Exemplo n.º 56
0
        public void LoadMultipleChunksTest()
        {
            int planet1 = 4;
            int planet2 = 12;
            Index2 index1 = new Index2(5, 6);
            Index2 index2 = new Index2(15, 16);
            IChunkColumn result1 = null;
            IChunkColumn result2 = null;
            int loadCallCounter = 0;
            int saveCallCounter = 0;

            GlobalChunkCache cache = new GlobalChunkCache(
                (p, i) =>
                {
                    loadCallCounter++;
                    if (p == planet1)
                    {
                        Assert.AreEqual(i, index1);
                        return result1 = new TestChunkColumn(p, index1);
                    }
                    else if (p == planet2)
                    {
                        Assert.AreEqual(i, index2);
                        return result2 = new TestChunkColumn(p, index2);
                    }

                    throw new NotSupportedException();
                },
                (p, i, c) =>
                {
                    saveCallCounter++;
                    if (p == planet1)
                    {
                        Assert.AreEqual(i, index1);
                        Assert.AreEqual(c, result1);
                        return;
                    }
                    else if (p == planet2)
                    {
                        Assert.AreEqual(i, index2);
                        Assert.AreEqual(c, result2);
                        return;
                    }

                    throw new NotSupportedException();
                });

            // Load 1
            Assert.AreEqual(0, cache.LoadedChunkColumns);
            Assert.AreEqual(0, loadCallCounter);
            Assert.AreEqual(0, saveCallCounter);

            IChunkColumn x1 = cache.Subscribe(planet1, index1);
            Assert.AreEqual(x1, result1);
            Assert.AreEqual(x1.Planet, planet1);
            Assert.AreEqual(x1.Index, index1);

            Assert.AreEqual(1, cache.LoadedChunkColumns);
            Assert.AreEqual(1, loadCallCounter);
            Assert.AreEqual(0, saveCallCounter);

            // Load 2
            IChunkColumn x2 = cache.Subscribe(planet2, index2);
            Assert.AreEqual(x2, result2);
            Assert.AreEqual(x2.Planet, planet2);
            Assert.AreEqual(x2.Index, index2);

            Assert.AreEqual(2, cache.LoadedChunkColumns);
            Assert.AreEqual(2, loadCallCounter);
            Assert.AreEqual(0, saveCallCounter);

            // Unload 1
            cache.Release(planet1, index1);

            Assert.AreEqual(1, cache.LoadedChunkColumns);
            Assert.AreEqual(2, loadCallCounter);
            Assert.AreEqual(1, saveCallCounter);

            // Unload 2
            cache.Release(planet2, index2);

            Assert.AreEqual(0, cache.LoadedChunkColumns);
            Assert.AreEqual(2, loadCallCounter);
            Assert.AreEqual(2, saveCallCounter);
        }
Exemplo n.º 57
0
        private bool FillChunkRenderer()
        {
            Index2 destinationChunk = new Index2(player.ActorHost.Position.ChunkIndex);

            // Nur ausführen wenn der Spieler den Chunk gewechselt hat
            if (destinationChunk != currentChunk)
            {
                int mask = (int)Math.Pow(2, VIEWRANGE) - 1;

                int span = (int)Math.Pow(2, VIEWRANGE);
                int spanOver2 = span >> 1;

                for (int x = 0; x < span; x++)
                {
                    for (int y = 0; y < span; y++)
                    {
                        Index2 local = new Index2(x - spanOver2, y - spanOver2) + destinationChunk;
                        local.NormalizeXY(planet.Size);

                        int virtualX = local.X & mask;
                        int virtualY = local.Y & mask;

                        int rendererIndex = virtualX +
                            (virtualY << VIEWRANGE);

                        for (int z = 0; z < planet.Size.Z; z++)
                        {
                            chunkRenderer[rendererIndex, z].SetChunk(_manager, local.X, local.Y, z);
                        }
                    }
                }

                currentChunk = destinationChunk;
            }

            #region Chunkrenderer updaten

            //            int shortestDistance = int.MaxValue;
            //            ChunkRenderer updatableRenderer = null;
            foreach (var renderer in chunkRenderer)
            {
                if (!renderer.NeedUpdate())
                    continue;

                renderer.RegenerateVertexBuffer();

                //                Index2 absoluteIndex = new Index2(renderer.ChunkPosition.Value);
                //                Index2 relativeIndex = destinationChunk.ShortestDistanceXY(
                //                                   absoluteIndex, new Index2(
                //                                       planet.Size.X,
                //                                       planet.Size.Y));
                //
                //                int distance = relativeIndex.LengthSquared();
                //                if (distance < shortestDistance)
                //                {
                //                    updatableRenderer = renderer;
                //                    shortestDistance = distance;
                //                }
            }

            //            if (updatableRenderer != null)
            //                updatableRenderer.RegenerateVertexBuffer();

            #endregion

            return true;
            //            return updatableRenderer != null;
        }
Exemplo n.º 58
0
 public abstract float[,] GetHeightmap(Index2 chunkIndex);
Exemplo n.º 59
0
        public void LoadChunkWithMultipleReferencesTest()
        {
            int planet = 4;
            Index2 index = new Index2(5, 6);
            IChunkColumn result = null;
            int loadCallCounter = 0;
            int saveCallCounter = 0;

            GlobalChunkCache cache = new GlobalChunkCache(
                (p, i) =>
                {
                    loadCallCounter++;
                    Assert.AreEqual(i, index);
                    return result = new TestChunkColumn(planet, index);
                },
                (p, i, c) =>
                {
                    saveCallCounter++;
                    Assert.AreEqual(i, index);
                    Assert.AreEqual(c, result);
                });

            // Load 1
            Assert.AreEqual(0, cache.LoadedChunkColumns);
            Assert.AreEqual(0, loadCallCounter);
            Assert.AreEqual(0, saveCallCounter);

            IChunkColumn x1 = cache.Subscribe(planet, index);
            Assert.AreEqual(x1, result);
            Assert.AreEqual(x1.Planet, planet);
            Assert.AreEqual(x1.Index, index);

            Assert.AreEqual(1, cache.LoadedChunkColumns);
            Assert.AreEqual(1, loadCallCounter);
            Assert.AreEqual(0, saveCallCounter);

            // Load 2
            IChunkColumn x2 = cache.Subscribe(planet, index);
            Assert.AreEqual(x2, result);
            Assert.AreEqual(x2.Planet, planet);
            Assert.AreEqual(x2.Index, index);
            Assert.AreEqual(x1, x2);

            Assert.AreEqual(1, cache.LoadedChunkColumns);
            Assert.AreEqual(1, loadCallCounter);
            Assert.AreEqual(0, saveCallCounter);

            // Unload 1
            cache.Release(planet, index);

            Assert.AreEqual(1, cache.LoadedChunkColumns);
            Assert.AreEqual(1, loadCallCounter);
            Assert.AreEqual(0, saveCallCounter);

            // Unload 2
            cache.Release(planet, index);

            Assert.AreEqual(0, cache.LoadedChunkColumns);
            Assert.AreEqual(1, loadCallCounter);
            Assert.AreEqual(1, saveCallCounter);
        }
Exemplo n.º 60
0
        private void item_CellChanged(Item item, Index2 newValue)
        {
            // Environment Information aktualisieren
            VisibleEnvironment env = viewers[item.Id].Environment;

            // Element außerhalb des Spielfeldes
            Index2 limit = Engine.Map.GetCellCount();
            if (newValue.X < 0 || newValue.X >= limit.X ||
                newValue.Y < 0 || newValue.Y >= limit.Y)
            {
                env.Center = null;
                env.North = null;
                env.South = null;
                env.West = null;
                env.East = null;
                env.NorthWest = null;
                env.NorthEast = null;
                env.SouthWest = null;
                env.SouthEast = null;
                return;
            }

            // Umgebungszellen durchlaufen
            for (int x = -1; x <= 1; x++)
                for (int y = -1; y <= 1; y++)
                {
                    var offset = new Index2(x, y);
                    Index2 cell = newValue + offset;

                    if (cell.X < 0 || cell.X >= limit.X ||
                        cell.Y < 0 || cell.Y >= limit.Y)
                    {
                        // Es existiert keine Zelle mehr
                        env[offset] = null;
                    }
                    else
                    {
                        // Zelleninfos ermitteln
                        float speed = Engine.Map.Tiles[cell.X, cell.Y].GetSpeedMultiplicator();
                        TileHeight height = Engine.Map.Tiles[cell.X, cell.Y].Height;
                        env[offset] = new VisibleCell
                        {
                            Speed = speed,
                            Height = height
                        };
                    }
                }

            // Inform user
            viewers[item.Id].RefreshEnvironment();
        }