示例#1
0
        private void CreateIndicesChunk(CHeightmap heightMap, ref Dictionary <int, int[]> indicesdict, int reCurisiveCounter)
        {
            int terrainWidthChunk  = heightMap.Image.Width / chunksplit;
            int terrainHeightChunk = heightMap.Image.Height / chunksplit;

            // indicies
            int counter = 0;
            var indices = new int[(terrainWidthChunk - 1) * (terrainHeightChunk - 1) * 6];

            for (int y = 0; y < terrainHeightChunk - 1; y++)
            {
                for (int x = 0; x < terrainWidthChunk - 1; x++)
                {
                    int topLeft    = x + y * terrainWidthChunk;
                    int topRight   = (x + 1) + y * terrainWidthChunk;
                    int lowerLeft  = x + (y + 1) * terrainWidthChunk;
                    int lowerRight = (x + 1) + (y + 1) * terrainWidthChunk;

                    indices[counter++] = topLeft;
                    indices[counter++] = lowerRight;
                    indices[counter++] = lowerLeft;

                    indices[counter++] = topLeft;
                    indices[counter++] = topRight;
                    indices[counter++] = lowerRight;
                }
            }
            indicesdict.Add(reCurisiveCounter, indices);
            if (reCurisiveCounter + 1 < chunksplit * chunksplit)
            {
                CreateIndicesChunk(heightMap, ref indicesdict, reCurisiveCounter + 1);
            }
        }
示例#2
0
        private void CreateVerticesChunks(CHeightmap cheightmap,
                                          ref Dictionary <int, VertexPositionNormalColor[]> vertexdict, int reCurisiveCounter, int xOffset)
        {
            Random rn = new Random();

            int terrainWidth  = cheightmap.Image.Width / chunksplit;
            int terrainHeight = cheightmap.Image.Height / chunksplit;
            int globaly       = 0;
            int globalx       = 0;
            int yOffset       = 0;

            if (reCurisiveCounter % chunksplit == 0 && reCurisiveCounter != 0)
            {
                xOffset += terrainWidth;
                xOffset--;
            }
            var vertices         = new VertexPositionNormalColor[terrainWidth * terrainHeight];
            var vertRandomOffset = 0.45f;

            for (int x = 0; x < terrainWidth; x++)
            {
                for (int y = 0; y < terrainHeight; y++)
                {
                    yOffset = terrainHeight * (reCurisiveCounter % chunksplit);
                    if (yOffset > 0)
                    {
                        yOffset = yOffset - reCurisiveCounter % chunksplit;
                    }
                    globalx = x + xOffset;
                    globaly = y + yOffset;
                    float height = cheightmap.HeightData[globalx, globaly].R + vertRandomOffset - (float)(rn.NextDouble() * vertRandomOffset * 2);
                    vertices[x + y * terrainWidth].Position = new Vector3(globalx, height, globaly);
                    vertices[x + y * terrainWidth].Color    = materialPick(cheightmap.HeightData[globalx, globaly].G);

                    //vertices[x + y * terrainWidth].TextureCoordinate = new Vector2((float) x / terrainWidth,
                    //(float) y / terrainHeight);
                }
            }
            vertexdict.Add(reCurisiveCounter, vertices);


            if (reCurisiveCounter + 1 < chunksplit * chunksplit)
            {
                CreateVerticesChunks(cheightmap, ref vertexdict, reCurisiveCounter + 1, xOffset);
            }
        }
示例#3
0
        private void CalculateHeightData(CHeightmap compHeight, int key)
        {
            CTransform transformComponent = (CTransform)Game1.Inst.Scene.GetComponentFromEntity <CTransform>(key);

            int terrainWidth  = compHeight.Image.Width;
            int terrainHeight = compHeight.Image.Height;

            var colorMap = new Color[terrainWidth * terrainHeight];

            compHeight.Image.GetData(colorMap);

            compHeight.HeightData = new Color[terrainWidth, terrainHeight];
            mHeightData           = new float[terrainWidth, terrainHeight];

            for (int x = 0; x < terrainWidth; x++)
            {
                for (int y = 0; y < terrainHeight; y++)
                {
                    compHeight.HeightData[x, y] = colorMap[x + y * terrainWidth];
                    mHeightData[x, y]           = colorMap[x + y * terrainWidth].R + transformComponent.Position.Y;
                    if (compHeight.elements.ContainsKey(colorMap[x + y * terrainWidth].B))
                    {
                        var s = 0.05f;
                        compHeight.EnvironmentSpawn.Add(new Vector4(s * x, mHeightData[x, y], s * y, colorMap[x + y * terrainWidth].B));
                    }
                }
            }

            float minHeight = float.MaxValue;
            float maxHeight = float.MinValue;

            for (int x = 0; x < terrainWidth; x++)
            {
                for (int y = 0; y < terrainHeight; y++)
                {
                    if (compHeight.HeightData[x, y].R < minHeight)
                    {
                        compHeight.LowestPoint = compHeight.HeightData[x, y].R;
                    }
                    if (compHeight.HeightData[x, y].R > maxHeight)
                    {
                        compHeight.HeighestPoint = compHeight.HeightData[x, y].R;
                    }
                }
            }
        }
        private void CalculateHeightData(CHeightmap compHeight)
        {
            int terrainWidth  = compHeight.Image.Width;
            int terrainHeight = compHeight.Image.Height;

            var colorMap = new Color[terrainWidth * terrainHeight];

            compHeight.Image.GetData(colorMap);

            compHeight.HeightData = new Color[terrainWidth, terrainHeight];
            mHeightData           = new int[terrainWidth, terrainHeight];
            for (int x = 0; x < terrainWidth; x++)
            {
                for (int y = 0; y < terrainHeight; y++)
                {
                    compHeight.HeightData[x, y] = colorMap[x + y * terrainWidth];
                    mHeightData[x, y]           = colorMap[x + y * terrainWidth].R;
                }
            }

            float minHeight = float.MaxValue;
            float maxHeight = float.MinValue;

            for (int x = 0; x < terrainWidth; x++)
            {
                for (int y = 0; y < terrainHeight; y++)
                {
                    if (compHeight.HeightData[x, y].R < minHeight)
                    {
                        compHeight.LowestPoint = compHeight.HeightData[x, y].R;
                    }
                    if (compHeight.HeightData[x, y].R > maxHeight)
                    {
                        compHeight.HeighestPoint = compHeight.HeightData[x, y].R;
                    }
                }
            }
        }
示例#5
0
        private ModelMeshPart buildGround(CHeightmap heightmap, int height)
        {
            int width = heightmap.Image.Width;
            int depth = heightmap.Image.Height;

            // Normals
            Vector3 RIGHT = new Vector3(1, 0, 0);             // +X
            Vector3 LEFT  = new Vector3(-1, 0, 0);            // -X
            // Vector3 UP = new Vector3(0, 1, 0); // +Y
            // Vector3 DOWN = new Vector3(0, -1, 0); // -Y
            Vector3 FORWARD  = new Vector3(0, 0, 1);            // +Z
            Vector3 BACKWARD = new Vector3(0, 0, -1);           // -Z

            Color groundColor = Color.SaddleBrown;
            var   vertexList  = new List <VertexPositionNormalColor>();

            // Front and back
            for (int x = 0; x < width - 1; x++)
            {
                // Front Face
                var z                  = depth - 1;
                var currY              = heightmap.HeightData[x, z].R;
                var nextY              = heightmap.HeightData[x + 1, z].R;
                var FRONT_TOP_LEFT     = new Vector3(x, currY, z);
                var FRONT_TOP_RIGHT    = new Vector3(x + 1, nextY, z);
                var FRONT_BOTTOM_LEFT  = new Vector3(x, -height, z);
                var FRONT_BOTTOM_RIGHT = new Vector3(x + 1, -height, z);
                vertexList.Add(new VertexPositionNormalColor(FRONT_TOP_LEFT, FORWARD, groundColor));
                vertexList.Add(new VertexPositionNormalColor(FRONT_BOTTOM_RIGHT, FORWARD, groundColor));
                vertexList.Add(new VertexPositionNormalColor(FRONT_BOTTOM_LEFT, FORWARD, groundColor));
                vertexList.Add(new VertexPositionNormalColor(FRONT_TOP_LEFT, FORWARD, groundColor));
                vertexList.Add(new VertexPositionNormalColor(FRONT_TOP_RIGHT, FORWARD, groundColor));
                vertexList.Add(new VertexPositionNormalColor(FRONT_BOTTOM_RIGHT, FORWARD, groundColor));

                //Back face
                z     = 0;
                currY = heightmap.HeightData[x, z].R;
                nextY = heightmap.HeightData[x + 1, z].R;
                var BACK_TOP_RIGHT    = new Vector3(x, currY, z);
                var BACK_TOP_LEFT     = new Vector3(x + 1, nextY, z);
                var BACK_BOTTOM_RIGHT = new Vector3(x, -height, z);
                var BACK_BOTTOM_LEFT  = new Vector3(x + 1, -height, z);
                vertexList.Add(new VertexPositionNormalColor(BACK_TOP_LEFT, BACKWARD, groundColor));
                vertexList.Add(new VertexPositionNormalColor(BACK_BOTTOM_RIGHT, BACKWARD, groundColor));
                vertexList.Add(new VertexPositionNormalColor(BACK_BOTTOM_LEFT, BACKWARD, groundColor));
                vertexList.Add(new VertexPositionNormalColor(BACK_TOP_LEFT, BACKWARD, groundColor));
                vertexList.Add(new VertexPositionNormalColor(BACK_TOP_RIGHT, BACKWARD, groundColor));
                vertexList.Add(new VertexPositionNormalColor(BACK_BOTTOM_RIGHT, BACKWARD, groundColor));
            }
            // Left and right
            for (int z = 0; z < depth - 1; z++)
            {
                // Left face
                var x                 = 0;
                var currY             = heightmap.HeightData[x, z].R;
                var nextY             = heightmap.HeightData[x, z + 1].R;
                var BACK_TOP_LEFT     = new Vector3(x, currY, z);
                var BACK_TOP_RIGHT    = new Vector3(x, nextY, z + 1);
                var BACK_BOTTOM_LEFT  = new Vector3(x, -height, z);
                var BACK_BOTTOM_RIGHT = new Vector3(x, -height, z + 1);
                vertexList.Add(new VertexPositionNormalColor(BACK_TOP_LEFT, LEFT, groundColor));
                vertexList.Add(new VertexPositionNormalColor(BACK_BOTTOM_RIGHT, LEFT, groundColor));
                vertexList.Add(new VertexPositionNormalColor(BACK_BOTTOM_LEFT, LEFT, groundColor));
                vertexList.Add(new VertexPositionNormalColor(BACK_TOP_LEFT, LEFT, groundColor));
                vertexList.Add(new VertexPositionNormalColor(BACK_TOP_RIGHT, LEFT, groundColor));
                vertexList.Add(new VertexPositionNormalColor(BACK_BOTTOM_RIGHT, LEFT, groundColor));
                // Right face
                x     = depth - 1;
                currY = heightmap.HeightData[x, z].R;
                nextY = heightmap.HeightData[x, z + 1].R;
                var FRONT_TOP_RIGHT    = new Vector3(x, currY, z);
                var FRONT_TOP_LEFT     = new Vector3(x, nextY, z + 1);
                var FRONT_BOTTOM_RIGHT = new Vector3(x, -height, z);
                var FRONT_BOTTOM_LEFT  = new Vector3(x, -height, z + 1);
                vertexList.Add(new VertexPositionNormalColor(FRONT_TOP_LEFT, RIGHT, groundColor));
                vertexList.Add(new VertexPositionNormalColor(FRONT_BOTTOM_RIGHT, RIGHT, groundColor));
                vertexList.Add(new VertexPositionNormalColor(FRONT_BOTTOM_LEFT, RIGHT, groundColor));
                vertexList.Add(new VertexPositionNormalColor(FRONT_TOP_LEFT, RIGHT, groundColor));
                vertexList.Add(new VertexPositionNormalColor(FRONT_TOP_RIGHT, RIGHT, groundColor));
                vertexList.Add(new VertexPositionNormalColor(FRONT_BOTTOM_RIGHT, RIGHT, groundColor));
            }

            var vertices = vertexList.ToArray();
            // indicies
            var indexLength = (width * 6 * 2) + (depth * 6 * 2);

            short[] indexList = new short[indexLength];
            for (int i = 1; i < indexLength; i++)
            {
                indexList[i] = (short)i;
            }
            var indices = indexList;

            var vertexBuffer = new VertexBuffer(mGraphicsDevice, VertexPositionNormalColor.VertexDeclaration, vertices.Length, BufferUsage.None);

            vertexBuffer.SetData(vertices);

            var indexBuffer = new IndexBuffer(mGraphicsDevice, typeof(short), indices.Length, BufferUsage.None);

            indexBuffer.SetData(indices);

            var groundMeshPart = new ModelMeshPart {
                VertexBuffer = vertexBuffer, IndexBuffer = indexBuffer, NumVertices = vertices.Length, PrimitiveCount = vertices.Length / 3
            };

            return(groundMeshPart);
        }
示例#6
0
        public void Load()
        {
            CHeightmap heightmap = null;

            // for each heightmap component, create Model instance to enable Draw calls when rendering
            foreach (var renderable in Game1.Inst.Scene.GetComponents <C3DRenderable>())
            {
                if (renderable.Value.GetType() != typeof(CHeightmap))
                {
                    continue;
                }
                heightmap = (CHeightmap)renderable.Value;
                int key = renderable.Key;

                /* use each color channel for different data, e.g.
                 * R for height,
                 * G for texture/material/terrain type,
                 * B for fixed spawned models/entities (houses, trees etc.),
                 * A for additional data
                 */


                List <ModelMesh> meshes = new List <ModelMesh>();
                var bones = new List <ModelBone>();

                var indices  = new Dictionary <int, int[]>();
                var vertices = new Dictionary <int, VertexPositionNormalColor[]>();

                CreateIndicesChunk(heightmap, ref indices, 0);
                CalculateHeightData(heightmap, key);
                CreateVerticesChunks(heightmap, ref vertices, 0, 0);
                //basicEffect.Texture = heightmap.Image;
                basicEffect.DiffuseColor  = new Vector3(1, 1, 1);
                basicEffect.SpecularPower = 100;
                basicEffect.SpecularColor = new Vector3(0.25f);

                basicEffect.EnableDefaultLighting();
                basicEffect.LightingEnabled   = true;
                basicEffect.AmbientLightColor = Game1.Inst.Scene.LightConfig.AmbientColor;
                basicEffect.DirectionalLight0.SpecularColor = Game1.Inst.Scene.LightConfig.SpecularColor;
                basicEffect.DirectionalLight0.Direction     = Game1.Inst.Scene.LightConfig.Direction;
                basicEffect.DirectionalLight0.DiffuseColor  = Game1.Inst.Scene.LightConfig.DiffuseColor;
                basicEffect.DirectionalLight0.Enabled       = true;
                basicEffect.PreferPerPixelLighting          = true;


                for (int j = 0; j < vertices.Values.Count; j++)
                {
                    var vert = vertices[j];
                    var ind  = indices[j];
                    CalculateNormals(ref vert, ref ind);

                    /*
                     * for(int i = 0; i < vertices[j].Length; i++)
                     *  vertices[j][i].Color = Color.ForestGreen;
                     */
                    vertices[j] = vert;
                    indices[j]  = ind;

                    var modelpart = CreateModelPart(vert, ind);
                    List <ModelMeshPart> meshParts = new List <ModelMeshPart>();
                    meshParts.Add(modelpart);

                    ModelMesh modelMesh = new ModelMesh(mGraphicsDevice, meshParts);
                    modelMesh.BoundingSphere = new BoundingSphere();
                    ModelBone modelBone = new ModelBone();
                    modelBone.AddMesh(modelMesh);
                    modelBone.Transform = Matrix.CreateTranslation(new Vector3(0, 0, 0));                     // changing object world (frame) / origo

                    modelMesh.ParentBone = modelBone;
                    bones.Add(modelBone);
                    meshes.Add(modelMesh);
                    modelMesh.BoundingSphere = BoundingSphere.CreateFromBoundingBox(GenericUtil.BuildBoundingBoxForVertex(vert, Matrix.Identity));
                    modelpart.Effect         = basicEffect;
                }
                ModelMeshPart        ground          = buildGround(heightmap, 20);
                List <ModelMeshPart> groundMeshParts = new List <ModelMeshPart>();
                groundMeshParts.Add(ground);
                ModelMesh groundMesh = new ModelMesh(mGraphicsDevice, groundMeshParts);
                groundMesh.BoundingSphere = new BoundingSphere();
                ModelBone groundBone = new ModelBone();
                groundBone.AddMesh(groundMesh);
                groundBone.Transform  = Matrix.CreateTranslation(new Vector3(0, 0, 0));
                groundMesh.ParentBone = groundBone;
                groundMesh.Name       = "FrontFace";
                bones.Add(groundBone);
                meshes.Add(groundMesh);
                ground.Effect = basicEffect;

                heightmap.model = new Model(mGraphicsDevice, bones, meshes);

                heightmap.model.Tag = "Map";
            }
        }
示例#7
0
        public void Load()
        {
            Model model = null;

            foreach (var renderable in Game1.Inst.Scene.GetComponents <C3DRenderable>())
            {
                if (renderable.Value.GetType() != typeof(CHeightmap))
                {
                    continue;
                }
                CHeightmap heightmap = (CHeightmap)renderable.Value;

                //                heightmap.HeightData
                // Create vertices
                Random rnd = new Random(1990);


                var terrainHeight = 1081;
                var terrainWidth  = 1081;
                //
                int counter = 0;
                indices     = new int[(terrainWidth - 1) * (terrainHeight - 1) * 6];
                vertices    = new VertexPositionNormalColor[terrainWidth * terrainHeight];
                vibirations = new int[terrainWidth * terrainHeight];
                // Create vertices
                for (int x = 0; x < terrainWidth; x++)
                {
                    for (int y = 0; y < terrainHeight; y++)
                    {
                        vertices[x + y * terrainWidth].Position = new Vector3(x, heightmap.LowestPoint + 10, y);
                        var color = Color.Blue;
                        color.A = 100;
                        vertices[x + y * terrainWidth].Color = color;

                        // Randomly set the direction of the vertex up or down
                        vibirations[x + y * terrainWidth] = rnd.Next(0, 100) > 50 ? -1 : 1;
                    }
                }
                for (int y = 0; y < terrainHeight - 1; y++)
                {
                    for (int x = 0; x < terrainWidth - 1; x++)
                    {
                        int topLeft    = x + y * terrainWidth;
                        int topRight   = (x + 1) + y * terrainWidth;
                        int lowerLeft  = x + (y + 1) * terrainWidth;
                        int lowerRight = (x + 1) + (y + 1) * terrainWidth;

                        indices[counter++] = (int)topLeft;
                        indices[counter++] = (int)lowerRight;
                        indices[counter++] = (int)lowerLeft;

                        indices[counter++] = (int)topLeft;
                        indices[counter++] = (int)topRight;
                        indices[counter++] = (int)lowerRight;
                    }
                }
                // Calculate normals
                for (int i = 0; i < vertices.Length; i++)
                {
                    vertices[i].Normal = new Vector3(0, 0, 0);
                }

                for (int i = 0; i < indices.Length / 3; i++)
                {
                    int index1 = indices[i * 3];
                    int index2 = indices[i * 3 + 1];
                    int index3 = indices[i * 3 + 2];

                    Vector3 side1  = vertices[index1].Position - vertices[index3].Position;
                    Vector3 side2  = vertices[index1].Position - vertices[index2].Position;
                    Vector3 normal = Vector3.Cross(side1, side2);

                    vertices[index1].Normal += normal;
                    vertices[index2].Normal += normal;
                    vertices[index3].Normal += normal;
                }



                var vertexBuffer = new VertexBuffer(mGraphicsDevice, VertexPositionNormalColor.VertexDeclaration,
                                                    vertices.Length, BufferUsage.None);
                vertexBuffer.SetData(vertices);
                var indexBuffer = new IndexBuffer(mGraphicsDevice, typeof(int), indices.Length, BufferUsage.None);
                indexBuffer.SetData(indices);

                var bones  = new List <ModelBone>();
                var meshes = new List <ModelMesh>();

                List <ModelMeshPart> parts    = new List <ModelMeshPart>();
                ModelMeshPart        meshPart = new ModelMeshPart();
                meshPart.VertexBuffer   = vertexBuffer;
                meshPart.IndexBuffer    = indexBuffer;
                meshPart.NumVertices    = indices.Length;
                meshPart.PrimitiveCount = indices.Length / 3;
                parts.Add(meshPart);

                ModelMesh mesh = new ModelMesh(mGraphicsDevice, parts);
                meshPart.Effect = bEffect;

                mesh.Name = "water";
                ModelBone bone = new ModelBone();
                bone.Name = "Water";
                bone.AddMesh(mesh);
                bone.Transform  = Matrix.Identity;
                mesh.ParentBone = bone;

                bones.Add(bone);
                meshes.Add(mesh);
                model = new Model(Game1.Inst.GraphicsDevice, bones, meshes);
            }
            int id = Game1.Inst.Scene.AddEntity();

            Game1.Inst.Scene.AddComponent(id, new CTransform()
            {
                Position = new Vector3(-590, -900, -590) * 0.01f, Orientation = Quaternion.CreateFromRotationMatrix(Matrix.Identity), Scale = new Vector3(0.01f)
            });
            CModel = new CImportedModel()
            {
                model = model
            };
            Game1.Inst.Scene.AddComponent <C3DRenderable>(id, CModel);
        }
示例#8
0
        public void Load()
        {
            // for each heightmap component, create Model instance to enable Draw calls when rendering
            foreach (var renderable in Game1.Inst.Scene.GetComponents <C3DRenderable>())
            {
                if (renderable.Value.GetType() != typeof(CHeightmap))
                {
                    continue;
                }
                CHeightmap heightmap = (CHeightmap)renderable.Value;

                /* use each color channel for different data, e.g.
                 * R for height,
                 * G for texture/material/terrain type,
                 * B for fixed spawned models/entities (houses, trees etc.),
                 * A for additional data
                 */


                List <ModelMesh> meshes = new List <ModelMesh>();
                var bones = new List <ModelBone>();

                var indices  = new Dictionary <int, int[]>();
                var vertices = new Dictionary <int, VertexPositionNormalColor[]>();

                CreateIndicesChunk(heightmap, ref indices, 0);
                CalculateHeightData(heightmap);
                CreateVerticesChunks(heightmap, ref vertices, 0, 0);
                for (int j = 0; j < vertices.Values.Count; j++)
                {
                    var vert = vertices[j];
                    var ind  = indices[j];
                    CalculateNormals(ref vert, ref ind);
                    vertices[j] = vert;
                    indices[j]  = ind;

                    var modelpart = CreateModelPart(vert, ind);
                    List <ModelMeshPart> meshParts = new List <ModelMeshPart>();
                    meshParts.Add(modelpart);

                    ModelMesh modelMesh = new ModelMesh(mGraphicsDevice, meshParts);
                    modelMesh.BoundingSphere = new BoundingSphere();
                    ModelBone modelBone = new ModelBone();
                    modelBone.AddMesh(modelMesh);
                    modelBone.Transform = Matrix.CreateTranslation(new Vector3(0, 0, 0));                     // changing object world (frame) / origo

                    modelMesh.ParentBone = modelBone;
                    bones.Add(modelBone);
                    meshes.Add(modelMesh);
                    modelMesh.BoundingSphere = BoundingSphere.CreateFromBoundingBox(GenericUtil.BuildBoundingBoxForVertex(vert, Matrix.Identity));
                    modelpart.Effect         = basicEffect;
                }
                ModelMeshPart        ground          = buildGround(heightmap, 20);
                List <ModelMeshPart> groundMeshParts = new List <ModelMeshPart>();
                groundMeshParts.Add(ground);
                ModelMesh groundMesh = new ModelMesh(mGraphicsDevice, groundMeshParts);
                groundMesh.BoundingSphere = new BoundingSphere();
                ModelBone groundBone = new ModelBone();
                groundBone.AddMesh(groundMesh);
                groundBone.Transform  = Matrix.CreateTranslation(new Vector3(0, 0, 0));
                groundMesh.ParentBone = groundBone;
                groundMesh.Name       = "FrontFace";
                bones.Add(groundBone);
                meshes.Add(groundMesh);
                ground.Effect = basicEffect;

                heightmap.model     = new Model(mGraphicsDevice, bones, meshes);
                heightmap.model.Tag = "Map";
            }
        }
示例#9
0
        public override void Init()
        {
            InitGameComponents();

            mPostProcessor = new PostProcessor();
            mUnderWaterFx  = Game1.Inst.Content.Load <Effect>("Effects/UnderWater");
            mRT            = GfxUtil.CreateRT();

            var physicsSys = new PhysicsSystem();

            physicsSys.Bounds          = new BoundingBox(-worldSize * Vector3.One, worldSize * Vector3.One);
            physicsSys.InvSpatPartSize = 0.07f;
            physicsSys.Gravity        *= 2.0f;
            physicsSys.WaterY          = configs.WaterHeight;
            var inputSys = new InputSystem();

            inputSys.WaterY = configs.WaterHeight;
            AddSystems(
                physicsSys,
                inputSys,
                new AISystem(),
                new AnimationSystem(),
                mParticleSys = new ParticleSystem(),
                new InventorySystem(),
                new CameraSystem(),
                new LogicSystem(),
                mRenderer = new RenderingSystem(),
                new Rendering2DSystem(),
                new HealthSystem(),
                new HitSystem()
                );

#if DEBUG
            AddSystem(new DebugOverlay());
#endif

            var heightmap = Heightmap.Load("Textures/" + configs.Map,
                                           stepX: 8,
                                           stepY: 8,
                                           smooth: false,
                                           scale: configs.HeightMapScale,
                                           yScale: configs.YScaleMap,
                                           randomTris: true,
                                           blur: 16,
                                           colorFn: configs.colorsMap);

            physicsSys.Heightmap = heightmap;
            inputSys.Heightmap   = heightmap;


            base.Init();


            WaterFactory.Create(configs.WaterHeight, configs.HeightMapScale, configs.HeightMapScale);

            SceneUtils.SpawnEnvironment(heightmap, configs.HeightMapScale);

            //add network after init since we dont want reinit and lose our connections.
            if (_networkSystem != null)
            {
                var sync = new GameObjectSyncSystem(_networkSystem._isMaster);
                _networkSystem.AddGameEvents();
                sync.Init();
                AddSystem(_networkSystem);
                AddSystem(sync);
            }

            // Camera entity
            float fieldofview = MathHelper.PiOver2;
            float nearplane   = 0.1f;
            float farplane    = 100f;

            player = AddEntity();



            AddComponent(player, new CBody()
            {
                MaxVelocity     = 5f,
                InvMass         = 0.01f,
                SpeedMultiplier = 1,
                Radius          = 0.7f,
                Aabb            = new BoundingBox(new Vector3(-0.5f, -0.9f, -0.5f), new Vector3(0.5f, 0.9f, 0.5f)),
                LinDrag         = 0.8f,
                ReachableArea   = new BoundingBox(new Vector3(-1.5f, -2.0f, -1.5f), new Vector3(1.5f, 2.0f, 1.5f)),
                Restitution     = 0.1f
            });

            AddComponent(player, new CInput());
            var playery = (heightmap.HeightAt(configs.Playerx, configs.Playerz));
            var chitid  = AddEntity();
            AddComponent(chitid, new CHit()
            {
                PlayerId = player
            });
            AddComponent(chitid, new CTransform()
            {
                Heading = MathHelper.PiOver2, Position = new Vector3(configs.Playerx, playery, configs.Playerz) + new CHit().HitBoxOffset
            });
            AddComponent(chitid, new CBody()
            {
                Aabb = new BoundingBox(new Vector3(-0.4f, -1.3f, -0.4f), new Vector3(0.4f, 0.9f, 0.4f))
            });
            AddComponent(player, new CPlayer()
            {
                HitId = chitid
            });



            var playerTransf = new CTransform()
            {
                Heading = MathHelper.PiOver2, Position = new Vector3(configs.Playerx, playery, configs.Playerz), Scale = new Vector3(0.5f)
            };

            AddComponent(player, playerTransf);

            // Glossy helmet, lol!
            //var cubeMap = Game1.Inst.Content.Load<Effect>("Effects/CubeMap");
            //var envMap = new EnvMapMaterial(mRenderer, player, playerTransf, cubeMap);

            AddComponent <C3DRenderable>(player,
                                         new CImportedModel()
            {
                animFn   = SceneUtils.playerAnimation(player, 24, 0.1f),
                model    = Game1.Inst.Content.Load <Model>("Models/viking"),
                fileName = "viking",

                /*materials = new Dictionary<int, MaterialShader> {
                 *  { 8, envMap }
                 * }*/
            });
            AddComponent(player, new CSyncObject {
                fileName = "viking"
            });

            AddComponent(player, new CInventory());
            AddComponent(player, new CHealth {
                MaxHealth = 3, Health = 3, DeathSound = "Sounds/Effects/entia"
            });
            AddComponent(player, new CScore {
            });

            /*
             * AddComponent(player, new CLogic {
             *  InvHz = 1.0f/30.0f,
             *  Fn = (t, dt) => {
             *      var cam = (CCamera)GetComponentFromEntity<CCamera>(player);
             *      envMap.Update();
             *  }
             * });
             */
            AddComponent(player, new CCamera
            {
                Height     = 3.5f,
                Distance   = 3.5f,
                Projection = Matrix.CreatePerspectiveFieldOfView(fieldofview, Game1.Inst.GraphicsDevice.Viewport.AspectRatio, nearplane, farplane)
                ,
                ClipProjection = Matrix.CreatePerspectiveFieldOfView(fieldofview * 1.2f, Game1.Inst.GraphicsDevice.Viewport.AspectRatio, nearplane * 0.5f, farplane * 1.2f)
            });

            // Heightmap entity

            var mapMat = new ToonMaterial(Vector3.One * 0.2f,
                                          new Vector3(1.0f, 0.0f, 1.0f), // ignored
                                          Vector3.Zero,
                                          40.0f,
                                          null,  // diftex
                                          null,  // normtex
                                          1.0f,  // normcoeff
                                          5,     // diflevels
                                          2,     // spelevels,
                                          true); // use vert col


            int hme = AddEntity();
            AddComponent <C3DRenderable>(hme, new C3DRenderable {
                model             = heightmap.Model,
                enableVertexColor = true,
                specular          = 0.03f,
                // materials = new Dictionary<int, MaterialShader> { {0, mapMat } }
            });
            AddComponent(hme, new CTransform {
                Position = Vector3.Zero,
                Rotation = Matrix.Identity,
                Scale    = Vector3.One
            });

            int heightMapId   = AddEntity();
            var heightMapComp = new CHeightmap()
            {
                Image = Game1.Inst.Content.Load <Texture2D>("Textures/" + configs.Map)
            };
            var heightTrans = new CTransform()
            {
                Position = new Vector3(-590, 0, -590), Rotation = Matrix.Identity, Scale = new Vector3(1, 0.5f, 1)
            };
            AddComponent <C3DRenderable>(heightMapId, heightMapComp);
            AddComponent(heightMapId, heightTrans);
            // manually start loading all heightmap components, should be moved/automated

            OnEvent("hit", data => {
                var key = data as int?;
                if (key == null)
                {
                    return;
                }
                var transform         = (CTransform)GetComponentFromEntity <CTransform>(key.Value);
                var id                = AddEntity();
                Func <float> rndSize  = () => 0.05f + 0.1f * (float)rnd.NextDouble();
                Func <Vector3> rndVel = () => new Vector3((float)rnd.NextDouble() - 0.5f,
                                                          (float)rnd.NextDouble(),
                                                          (float)rnd.NextDouble() - 0.5f);
                mParticleSys.SpawnParticles(100, () => new EcsComponent[] {
                    new CParticle     {
                        Position = transform.Position,
                        Velocity = 6.0f * rndVel(),
                        Life     = 1.7f,
                        F        = () => new Vector3(0.0f, -9.81f, 0.0f)
                    },
                    new C3DRenderable {
                        model = Game1.Inst.Content.Load <Model>("Models/blood")
                    },
                    new CTransform    {
                        Position = transform.Position,
                        Rotation = Matrix.Identity,
                        Scale    = rndSize() * Vector3.One
                    }
                });
                SceneUtils.CreateSplatter(transform.Position.X, transform.Position.Z, heightmap);
                SfxUtil.PlaySound("Sounds/Effects/Hit", randomPitch: true);
            });

            OnEvent("game_end", data =>
            {
                won         = Game1.Inst.Scene.EntityHasComponent <CInput>((int)data);
                shouldLeave = true;
                // We reached the goal and wants to leave the scene-
            });


            if ((_networkSystem != null && _networkSystem._isMaster) || _networkSystem == null)
            {
                Utils.SceneUtils.CreateAnimals(configs.NumFlocks, configs.HeightMapScale / 2);
                Utils.SceneUtils.CreateTriggerEvents(configs.NumTriggers, configs.HeightMapScale / 2);
                Utils.SceneUtils.CreateCollectables(configs.NumPowerUps, configs.HeightMapScale / 2);
                SceneUtils.SpawnBirds(configs);
                // Add tree as sprint goal
                int sprintGoal = AddEntity();
                AddComponent(sprintGoal, new CBody()
                {
                    Radius = 5, Aabb = new BoundingBox(new Vector3(-5, -5, -5), new Vector3(5, 5, 5)), LinDrag = 0.8f
                });
                AddComponent(sprintGoal, new CTransform()
                {
                    Position = new Vector3(100, -0, 100), Scale = new Vector3(1f)
                });
                var treefilename = "tree";
                AddComponent(sprintGoal, new CSyncObject());
                AddComponent <C3DRenderable>(sprintGoal, new CImportedModel()
                {
                    model = Game1.Inst.Content.Load <Model>("Models/" + treefilename), fileName = treefilename
                });

                OnEvent("collision", data => {
                    foreach (var key in Game1.Inst.Scene.GetComponents <CPlayer>().Keys)
                    {
                        if ((((PhysicsSystem.CollisionInfo)data).Entity1 == key &&
                             ((PhysicsSystem.CollisionInfo)data).Entity2 == sprintGoal)
                            ||
                            (((PhysicsSystem.CollisionInfo)data).Entity2 == key &&
                             ((PhysicsSystem.CollisionInfo)data).Entity1 == sprintGoal))
                        {
                            Game1.Inst.Scene.Raise("network_game_end", key);
                            Game1.Inst.Scene.Raise("game_end", key);
                        }
                    }
                });
            }

            Log.GetLog().Debug("WorldScene initialized.");

            InitHud();

            SfxUtil.PlaySound("Sounds/Effects/horn_start");

            var billboards = new [] {
                new Tuple <string, float>("Grass", 1.0f),
                new Tuple <string, float>("Grass", 1.0f),
                new Tuple <string, float>("Grass", 1.0f),
                new Tuple <string, float>("Grass", 1.0f),
                new Tuple <string, float>("Grass", 1.0f),
                new Tuple <string, float>("Grass", 1.0f),
                new Tuple <string, float>("Grass", 1.0f),
                new Tuple <string, float>("Grass", 1.0f),
                new Tuple <string, float>("Grass", 1.0f),
                new Tuple <string, float>("Grass", 1.0f),
                new Tuple <string, float>("Grass", 1.0f),
                new Tuple <string, float>("Grass", 1.0f),
                new Tuple <string, float>("Grass", 1.0f),
                new Tuple <string, float>("Grass", 1.0f),
                new Tuple <string, float>("Grass", 1.0f),
                new Tuple <string, float>("Bush", 1.2f),
                new Tuple <string, float>("Flowers", 0.6f)
            };

            var billboards2 = new [] {
                new Tuple <string, float>("Seaweed1", 0.6f),
                new Tuple <string, float>("Seaweed2", 0.6f),
            };
            ;
            for (var i = 0; i < 10000; i++)
            {
                var bbs = billboards;

                var x = configs.HeightMapScale * ((float)rnd.NextDouble() - 0.5f);
                var z = configs.HeightMapScale * ((float)rnd.NextDouble() - 0.5f);
                var y = heightmap.HeightAt(x, z);

                if (y < configs.WaterHeight)
                {
                    bbs = billboards2;
                }

                var bb = bbs[rnd.Next(0, bbs.Length)];
                var s  = (1.0f + 0.8f * (float)rnd.NextDouble()) * bb.Item2;

                AddComponent(AddEntity(), new CBillboard {
                    Pos   = new Vector3(x, y + 0.5f * s, z),
                    Tex   = Game1.Inst.Content.Load <Texture2D>("Textures/" + bb.Item1),
                    Scale = s
                });
            }

            //CreatePlatforms(heightmap);
        }
示例#10
0
        private void LoadHeightmap()
        {
            var heightmap = Game1.Inst.Content.Load <Texture2D>("Textures/US_Canyon");

            var pixels = new Color[heightmap.Width * heightmap.Height];

            heightmap.GetData <Color>(pixels);

            var indices  = new List <int>();
            var vertices = new List <VertexPositionNormalTexture>();

            var k = (int)0;
            var q = 2;

            for (var j = 0; j < heightmap.Height / q; j++)
            {
                for (var i = 0; i < heightmap.Width / q; i++)
                {
                    // skapa triangel med index 0, 1, 2
                    var v0 = CreateHeightmapVertex(pixels, heightmap.Width, heightmap.Height, i * q, j * q);
                    vertices.Add(v0);
                }
            }

            for (var j = 0; j < heightmap.Height / q - 1; j++)
            {
                for (var i = 0; i < heightmap.Width / q - 1; i++)
                {
                    var a = i + j * (heightmap.Width / q);
                    var b = (i + 1) + j * (heightmap.Width / q);
                    var c = (i + 1) + (j + 1) * (heightmap.Width / q);
                    var d = i + (j + 1) * (heightmap.Width / q);

                    indices.Add(a);
                    indices.Add(b);
                    indices.Add(c);
                    indices.Add(a);
                    indices.Add(c);
                    indices.Add(d);
                }
            }

            var v = vertices.ToArray();

            for (int i = 0; i < indices.Count - 2; i += 3)
            {
                var a = indices[i];
                var b = indices[i + 1];
                var c = indices[i + 2];
                var N = Vector3.Cross(v[b].Position - v[a].Position, v[c].Position - v[a].Position);

                //N.Normalize();

                v[a].Normal -= N;
                v[b].Normal -= N;
                v[c].Normal -= N;
            }

            for (int i = 0; i < vertices.Count; i++)
            {
                v[i].Normal.Normalize();
            }

            VertexBuffer vb = new VertexBuffer(Game1.Inst.GraphicsDevice, typeof(VertexPositionNormalTexture), v.Length, BufferUsage.WriteOnly);

            vb.SetData <VertexPositionNormalTexture>(v);
            IndexBuffer ib = new IndexBuffer(Game1.Inst.GraphicsDevice, typeof(int), indices.Count, BufferUsage.WriteOnly);

            ib.SetData(indices.ToArray());

            heightmap.Dispose();

            var cmp = new CHeightmap {
                VertexBuffer = vb,
                IndexBuffer  = ib,
                NumVertices  = vertices.Count,
                NumTriangles = indices.Count
            };

            var e = new Entity();

            e.AddComponents(cmp);

            AddEntity(e);
        }