Ejemplo n.º 1
0
        private void OpenFile()
        {
            string path = OpenFileDialog(OpenFileFilter);

            if (path == null)
            {
                return;
            }
            ModelGeometry.Clear();
            Task.Run(() => {
                if (Path.GetExtension(path).ToLower() == ".3ds")
                {
                    Load3ds(path);
                }
                else if (Path.GetExtension(path).ToLower() == ".obj")
                {
                    LoadObj(path);
                }
                else if (Path.GetExtension(path).ToLower() == ".stl")
                {
                    LoadStl(path);
                }
                else if (Path.GetExtension(path).ToLower() == ".ply")
                {
                    LoadPly(path);
                }
            });
        }
Ejemplo n.º 2
0
        public void loadContent(ContentManager contentManager, GraphicsDeviceManager graphicsManager, ModelGeometry collisionGeometry)
        {
            mGraphicsDevice = graphicsManager.GraphicsDevice;

            mInstanceVertexDeclaration = new VertexDeclaration(new[]
            {
                new VertexElement(0, VertexElementFormat.Vector4, VertexElementUsage.TextureCoordinate, 2),
                new VertexElement(16, VertexElementFormat.Vector4, VertexElementUsage.TextureCoordinate, 3),
                new VertexElement(32, VertexElementFormat.Vector4, VertexElementUsage.TextureCoordinate, 4),
                new VertexElement(48, VertexElementFormat.Vector4, VertexElementUsage.TextureCoordinate, 5)
            });

            mCollidingFacesVertexDeclaration = new VertexDeclaration(new[]
            {
                // ideally we'd use Byte4 for Color0 but it's so much easier to fill vertex buffers with Vector3. There's only very little data anyway
                new VertexElement(0, VertexElementFormat.Vector3, VertexElementUsage.Position, 0 ),
                new VertexElement(12, VertexElementFormat.Vector3, VertexElementUsage.Normal, 0 ),
                new VertexElement(24, VertexElementFormat.Vector3, VertexElementUsage.Color, 0 )
            });

            mCollidingFacesVertices = new VertexBuffer(mGraphicsDevice, mCollidingFacesVertexDeclaration, collisionGeometry.faces.Length * 3, BufferUsage.WriteOnly);

            // load collisions shader and configure material properties
            mCollisionsShader = contentManager.Load<Effect>("Effects/CollisionsShader");
            mCollisionsShader.Parameters["MaterialColor"].SetValue(new Vector3(0.39f, 0.8f, 1f));

            mAlphaBlendState = new BlendState();
            mAlphaBlendState.ColorSourceBlend = Blend.SourceAlpha;
            mAlphaBlendState.AlphaSourceBlend = Blend.SourceAlpha;
            mAlphaBlendState.ColorDestinationBlend = Blend.InverseSourceAlpha;
            mAlphaBlendState.AlphaDestinationBlend = Blend.InverseSourceAlpha;
        }
Ejemplo n.º 3
0
        public void Initialize(Game2D game, ILevelDataProvider levelDataProvider)
        {
            _gameInformation = new GameInformation(game, levelDataProvider)
            {
                Width = BombGame.Tilesize * 15
            };

            _graphicsDevice  = game.GraphicsDevice;
            _levelData       = levelDataProvider;
            _context         = new Render3DContext(game);
            _objectsToRender = new List <IRenderObject> {
                new Level(game.GraphicsDevice, game.Content, levelDataProvider)
            };
            _bombGeometry             = new ModelGeometry(this, game.GraphicsDevice, game.Content.Load <Model>("Models/Bomb/BombMesh"), _context.ToonEffect);
            _playerGeometry           = new ModelGeometry(this, game.GraphicsDevice, game.Content.Load <Model>("Models/Player/bomberman"), _context.ToonEffect);
            _baseItemGeometry         = new ModelGeometry(this, game.GraphicsDevice, game.Content.Load <Model>("Models/items/itemBase"), _context.ToonEffect);
            _fireOverlayGeometry      = new ModelGeometry(this, game.GraphicsDevice, game.Content.Load <Model>("Models/items/fireoverlay"), _context.ToonEffect);
            _explosionFragmentManager = new ExplosionFragmentManager(game, _levelData);

            _players = new List <Player>();
            foreach (var figure in _levelData.Figures)
            {
                var player = new Player(figure, _playerGeometry);
                AddRenderObject(player);
                _players.Add(player);
            }

            foreach (var itemDataProvider in _levelData.ItemData)
            {
                AddRenderObject(new Item3D(itemDataProvider, _baseItemGeometry, _fireOverlayGeometry));
            }
        }
Ejemplo n.º 4
0
 public Item3D(IItemDataProvider item, ModelGeometry baseGeometry, ModelGeometry fireGeometry)
 {
     _item         = item;
     _baseGeometry = baseGeometry;
     _fireGeometry = fireGeometry;
     World         = Matrix.CreateScale(0.025f) * Matrix.CreateTranslation(_item.TilePosition.X + 0.5f, 0.0f, _item.TilePosition.Y + 0.5f);
     _overlayWorld = Matrix.CreateScale(0.006f) * Matrix.CreateTranslation(_item.TilePosition.X + 0.5f, 1.0f, _item.TilePosition.Y + 0.5f);
 }
Ejemplo n.º 5
0
 public ModelGeometry.Scene.XbimMeshLayer<WpfMeshGeometry3D, WpfMaterial> GetLayer(string LayerKey, IO.XbimModel model, ModelGeometry.Scene.XbimScene<WpfMeshGeometry3D, WpfMaterial> scene)
 {
     if (LayerKey == "Even")
     {
         XbimColour colour = new XbimColour("Red", 1.0, 0.0, 0.0, 1);
         return new XbimMeshLayer<WpfMeshGeometry3D, WpfMaterial>(model, colour) { Name = LayerKey };
     }
     else
     {
         XbimColour colour = new XbimColour("Green", 0.0, 1.0, 0.0, 1);
         return new XbimMeshLayer<WpfMeshGeometry3D, WpfMaterial>(model, colour) { Name = LayerKey };
     }
 }
Ejemplo n.º 6
0
        public void renderCollisionGeometry(ModelGeometry collisionGeometry, Camera camera)
        {
            foreach (var mesh in collisionGeometry.visualizationData.Meshes)
            {
                foreach (var effect in mesh.Effects.Cast <BasicEffect>())
                {
                    effect.View            = camera.viewMatrix;
                    effect.Projection      = camera.projectionMatrix;
                    effect.LightingEnabled = true;
                }

                mesh.Draw();
            }
        }
Ejemplo n.º 7
0
        private static List <ModelGeometry> LoadGeometries(XElement geometryNode, SemanticAssociations association, List <Vector4> weights = null, List <Vector4> joints = null)
        {
            List <ModelGeometry> geometries = new List <ModelGeometry>();

            //geometry
            if (geometryNode.GetNode("mesh") != null)
            {
                //if mesh load data
                var mesh = geometryNode.GetNode("mesh");

                var sources  = mesh.GetNodes("source");
                var vertices = mesh.GetNodes("vertices");

                //load data, only triangles supported

                foreach (var elem in mesh.Elements())
                {
                    ModelGeometry geometry = new ModelGeometry();
                    geometry.Name = geometryNode.GetAttribute("id");
                    //lines
                    //linestrips
                    switch (elem.Name.LocalName)
                    {
                    case "polygons":
                        break;

                    case "polylist":
                        break;

                    case "triangles":
                        GetTriangleMesh(geometry, elem, mesh, association, weights, joints);
                        geometry.Optimize();
                        geometries.Add(geometry);
                        break;

                    case "trifans":
                        break;

                    case "tristrips":
                        break;

                    default:
                        break;
                    }
                }
            }

            return(geometries);
        }
Ejemplo n.º 8
0
        static public ModelGeometry LoadMesh(string assetName)
        {
            if (CachedMeshes.ContainsKey(assetName))
            {
                return(CachedMeshes[assetName]);
            }

            MeshAsset     MA = AssetsManagerInstance.GetManager().LoadAsset <MeshAsset>(assetName);
            ModelGeometry MG = new ModelGeometry(MA.FileScale, MA.Pivot, MA.Vertices, MA.Indexes, MA.BoundingMinimum, MA.BoundingMaximum);

            MA = null;
            CachedMeshes.Add(assetName, MG);
            Debug.Log("AssetManager", "Mesh " + assetName + " loaded.");
            return(MG);
        }
Ejemplo n.º 9
0
        public void renderCollidingFaces(ModelGeometry collisionGeometry, IDictionary <Face, uint> collidingFaces, Camera camera, uint min, uint max)
        {
            if (collidingFaces.Count > 0)
            {
                // fill vertex buffer with collision geometry and set on device
                {
                    float range = Math.Max(max - min, 0.0001f);
                    var   data  = collidingFaces.SelectMany(face =>
                    {
                        var colour = new Vector3((face.Value - min) / range);
                        return(new[]
                        {
                            collisionGeometry.vertices[face.Key.v1],
                            collisionGeometry.normals[face.Key.n1],
                            colour,

                            collisionGeometry.vertices[face.Key.v2],
                            collisionGeometry.normals[face.Key.n2],
                            colour,

                            collisionGeometry.vertices[face.Key.v3],
                            collisionGeometry.normals[face.Key.n3],
                            colour
                        });
                    });

                    mCollidingFacesVertices.SetData <Vector3>(data.ToArray());
                    mGraphicsDevice.SetVertexBuffer(mCollidingFacesVertices);
                }

                // enable alpha blending
                var previousBlendState = mGraphicsDevice.BlendState;
                mGraphicsDevice.BlendState = mAlphaBlendState;

                // draw
                mCollisionsShader.Parameters["WorldViewProjection"].SetValue(camera.viewMatrix * camera.projectionMatrix);
                mCollisionsShader.CurrentTechnique.Passes[0].Apply();
                mGraphicsDevice.DrawPrimitives(PrimitiveType.TriangleList, 0, collidingFaces.Count);

                // restore previous blend mode
                mGraphicsDevice.BlendState = previousBlendState;
            }
        }
Ejemplo n.º 10
0
        static public MeshInfo LoadMeshInfo(PrimitivesMesh primitive)
        {
            ModelGeometry MG   = null;
            string        name = "";

            switch (primitive)
            {
            case PrimitivesMesh.Cube:
                name = "Primitives.Cube";
                MG   = Primitives.Cube;
                break;

            case PrimitivesMesh.Sphere:
                name = "Primitives.Sphere";
                MG   = Primitives.Sphere(32);  //20
                break;
            }
            return(new MeshInfo(name, new BoundsBox(MG.BoundingMinimum, MG.BoundingMaximum)));
        }
Ejemplo n.º 11
0
        public override bool ImportAsset(string path, string ext)
        {
            ModelGeometry[] MG = new ModelGeometry[1];

            if (ext == "obj")
            {
                MG[0] = ObjLoader.Load(path);
            }
            else if (ext == "fbx")
            {
                MG = FbxLoader.Load(path);
                if (MG.Length > 1)
                {
                    subAssets = new MeshAsset[MG.Length - 1];
                    for (int i = 1; i < MG.Length; i++)
                    {
                        subAssets[i - 1] = new MeshAsset()
                        {
                            Name            = this.Name + "_" + i,
                            FileScale       = FileScale,
                            Pivot           = Vector3.Zero,
                            Vertices        = MG[i].Points,
                            Indexes         = MG[i].Indexes,
                            BoundingMinimum = MG[i].BoundingMinimum,
                            BoundingMaximum = MG[i].BoundingMaximum,
                        };
                    }
                }
            }
            else
            {
                Console.WriteLine("Unknown mesh extension: {0}", ext);
                return(false);
            }

            Pivot           = Vector3.Zero;
            Vertices        = MG[0].Points;
            Indexes         = MG[0].Indexes;
            BoundingMinimum = MG[0].BoundingMinimum;
            BoundingMaximum = MG[0].BoundingMaximum;
            return(true);
        }
Ejemplo n.º 12
0
        //Load Triangle Mesh
        private static void GetTriangleMesh(ModelGeometry model, XElement triangle, XElement mesh, SemanticAssociations association, List <Vector4> weights = null, List <Vector4> joints = null)
        {
            //Indices
            List <int> indices = GetIntList(triangle.GetNode("p").Value);

            //Load Channel
            var inputs = triangle.GetNodes("input");
            List <ChannelData> inputData = new List <ChannelData>();

            foreach (XElement elem in inputs)
            {
                inputData.Add(new ChannelData(elem));
            }

            //Load Material
            model.Material = new MaterialData();
            model.Material = GetMaterial(triangle.Document, triangle.GetAttribute("material"));

            //Create Vertices
            int k = 0;

            while (k < indices.Count)
            {
                VertexFormat v = new VertexFormat();

                foreach (ChannelData e in inputData)
                {
                    var data = e.GetChannel(indices[k]);

                    switch (association[e.Semantic])
                    {
                    case ChannelCode.Position:
                        v.Position = new Vector3(data);

                        //Add weights and joints if loaded for skinned model
                        if (weights != null)
                        {
                            v.Weight = weights[indices[k]];
                        }

                        if (joints != null)
                        {
                            v.Joint = joints[indices[k]];
                        }

                        break;

                    case ChannelCode.Normal:
                        v.Normal = new Vector3(data);
                        break;

                    case ChannelCode.Tangent:
                        v.Tangent = new Vector3(data);
                        break;

                    case ChannelCode.Binormal:
                        v.Binormal = new Vector3(data);
                        break;

                    case ChannelCode.TexCoord1:
                        if (data.Length >= 2)
                        {
                            v.TextureSet1 = new Vector2(data.Take(2).ToArray());
                        }
                        break;

                    case ChannelCode.TexCoord2:
                        v.TextureSet2 = new Vector2(data.Take(2).ToArray());
                        break;

                    case ChannelCode.Joint:
                        v.Joint = new Vector4(data);
                        break;

                    case ChannelCode.Weight:
                        v.Weight = new Vector4(data);
                        break;

                    case ChannelCode.None:

                        break;

                    default:
                        break;
                    }

                    k++;
                }


                //Save to model
                model.Vertices.Add(v);
                model.Indices.Add(model.Indices.Count);
            }
        }
Ejemplo n.º 13
0
        static public MeshInfo LoadMeshInfo(string assetName)
        {
            ModelGeometry MG = LoadMesh(assetName);

            return(new MeshInfo(assetName, new BoundsBox(MG.BoundingMinimum, MG.BoundingMaximum)));
        }
Ejemplo n.º 14
0
 public Player(IFigureDataProvider figure, ModelGeometry geometry) : base(geometry)
 {
     _figure = figure;
 }
Ejemplo n.º 15
0
        public void loadContent(ContentManager contentManager, GraphicsDeviceManager graphicsManager, ModelGeometry collisionGeometry)
        {
            mGraphicsDevice = graphicsManager.GraphicsDevice;

            mInstanceVertexDeclaration = new VertexDeclaration(new[]
            {
                new VertexElement(0, VertexElementFormat.Vector4, VertexElementUsage.TextureCoordinate, 2),
                new VertexElement(16, VertexElementFormat.Vector4, VertexElementUsage.TextureCoordinate, 3),
                new VertexElement(32, VertexElementFormat.Vector4, VertexElementUsage.TextureCoordinate, 4),
                new VertexElement(48, VertexElementFormat.Vector4, VertexElementUsage.TextureCoordinate, 5)
            });

            mCollidingFacesVertexDeclaration = new VertexDeclaration(new[]
            {
                // ideally we'd use Byte4 for Color0 but it's so much easier to fill vertex buffers with Vector3. There's only very little data anyway
                new VertexElement(0, VertexElementFormat.Vector3, VertexElementUsage.Position, 0),
                new VertexElement(12, VertexElementFormat.Vector3, VertexElementUsage.Normal, 0),
                new VertexElement(24, VertexElementFormat.Vector3, VertexElementUsage.Color, 0)
            });

            mCollidingFacesVertices = new VertexBuffer(mGraphicsDevice, mCollidingFacesVertexDeclaration, collisionGeometry.faces.Length * 3, BufferUsage.WriteOnly);

            // load collisions shader and configure material properties
            mCollisionsShader = contentManager.Load <Effect>("Effects/CollisionsShader");
            mCollisionsShader.Parameters["MaterialColor"].SetValue(new Vector3(0.39f, 0.8f, 1f));

            mAlphaBlendState = new BlendState();
            mAlphaBlendState.ColorSourceBlend      = Blend.SourceAlpha;
            mAlphaBlendState.AlphaSourceBlend      = Blend.SourceAlpha;
            mAlphaBlendState.ColorDestinationBlend = Blend.InverseSourceAlpha;
            mAlphaBlendState.AlphaDestinationBlend = Blend.InverseSourceAlpha;
        }
Ejemplo n.º 16
0
        public void renderCollidingFaces(ModelGeometry collisionGeometry, IDictionary<Face, uint> collidingFaces, Camera camera, uint min, uint max)
        {
            if (collidingFaces.Count > 0)
            {
                // fill vertex buffer with collision geometry and set on device
                {
                    float range = Math.Max(max - min, 0.0001f);
                    var data = collidingFaces.SelectMany(face =>
                        {
                            var colour = new Vector3((face.Value - min)/range);
                            return new[]
                            {
                                collisionGeometry.vertices[face.Key.v1],
                                collisionGeometry.normals[face.Key.n1],
                                colour,

                                collisionGeometry.vertices[face.Key.v2],
                                collisionGeometry.normals[face.Key.n2],
                                colour,

                                collisionGeometry.vertices[face.Key.v3],
                                collisionGeometry.normals[face.Key.n3],
                                colour
                            };
                        });

                    mCollidingFacesVertices.SetData<Vector3>(data.ToArray());
                    mGraphicsDevice.SetVertexBuffer(mCollidingFacesVertices);
                }

                // enable alpha blending
                var previousBlendState = mGraphicsDevice.BlendState;
                mGraphicsDevice.BlendState = mAlphaBlendState;

                // draw
                mCollisionsShader.Parameters["WorldViewProjection"].SetValue(camera.viewMatrix * camera.projectionMatrix);
                mCollisionsShader.CurrentTechnique.Passes[0].Apply();
                mGraphicsDevice.DrawPrimitives(PrimitiveType.TriangleList, 0, collidingFaces.Count);

                // restore previous blend mode
                mGraphicsDevice.BlendState = previousBlendState;
            }
        }
Ejemplo n.º 17
0
        public void renderCollisionGeometry(ModelGeometry collisionGeometry, Camera camera)
        {
            foreach (var mesh in collisionGeometry.visualizationData.Meshes)
            {
                foreach (var effect in mesh.Effects.Cast<BasicEffect>())
                {
                    effect.View = camera.viewMatrix;
                    effect.Projection = camera.projectionMatrix;
                    effect.LightingEnabled = true;
                }

                mesh.Draw();
            }
        }
Ejemplo n.º 18
0
        public static ModelGeometry Sphere(int tessellation)
        {
            if (SphereCache == null)
            {
                SphereCache = new Dictionary <int, ModelGeometry>();
            }

            if (SphereCache.ContainsKey(tessellation))
            {
                return(SphereCache[tessellation]);
            }

            int verticalSegments   = tessellation;
            int horizontalSegments = tessellation * 2;

            Vector3[] vertices = new Vector3[(verticalSegments + 1) * (horizontalSegments + 1)];
            Vector3[] normals  = new Vector3[(verticalSegments + 1) * (horizontalSegments + 1)];
            Vector2[] uvs      = new Vector2[(verticalSegments + 1) * (horizontalSegments + 1)];
            int[]     indices  = new int[(verticalSegments) * (horizontalSegments + 1) * 6];

            float radius = 1.0f * 0.5f;

            int vertexCount = 0;

            // Create rings of vertices at progressively higher latitudes.
            for (int i = 0; i <= verticalSegments; i++)
            {
                float v = 1.0f - (float)i / verticalSegments;

                var latitude = (float)((i * Math.PI / verticalSegments) - Math.PI / 2.0);
                var dy       = (float)Math.Sin(latitude);
                var dxz      = (float)Math.Cos(latitude);

                // Create a single ring of vertices at this latitude.
                for (int j = 0; j <= horizontalSegments; j++)
                {
                    float u = (float)j / horizontalSegments;

                    var longitude = (float)(j * 2.0 * Math.PI / horizontalSegments);
                    var dx        = (float)Math.Sin(longitude);
                    var dz        = (float)Math.Cos(longitude);

                    dx *= dxz;
                    dz *= dxz;

                    var normal            = new Vector3(dx, dy, dz);
                    var textureCoordinate = new Vector2(u, v);

                    vertices[vertexCount] = normal * radius;
                    normals[vertexCount]  = normal;
                    uvs[vertexCount]      = textureCoordinate;
                    vertexCount++;
                }
            }

            // Fill the index buffer with triangles joining each pair of latitude rings.
            int stride = horizontalSegments + 1;

            int indexCount = 0;

            for (int i = 0; i < verticalSegments; i++)
            {
                for (int j = 0; j <= horizontalSegments; j++)
                {
                    int nextI = i + 1;
                    int nextJ = (j + 1) % stride;

                    indices[indexCount++] = (i * stride + j);
                    indices[indexCount++] = (i * stride + nextJ);
                    indices[indexCount++] = (nextI * stride + j);

                    indices[indexCount++] = (i * stride + nextJ);
                    indices[indexCount++] = (nextI * stride + nextJ);
                    indices[indexCount++] = (nextI * stride + j);
                }
            }

            SphereCache[tessellation] = new ModelGeometry(
                vertices,
                null,
                uvs,
                indices,
                null,
                normals
                );

            return(SphereCache[tessellation]);
        }