Ejemplo n.º 1
0
        public static List<Mesh> SplitMeshes(List<Mesh> meshes, bool can32bitIndex)
        {
            var finalList = new List<Mesh>();
            foreach (var mesh in meshes)
            {
                var drawDatas = SplitMesh(mesh.Draw, can32bitIndex);
                if (drawDatas.Count <= 1)
                {
                    finalList.Add(mesh);
                }
                else
                {
                    foreach (var draw in drawDatas)
                    {
                        var newMeshData = new Mesh(draw, mesh.Parameters)
                            {
                                MaterialIndex = mesh.MaterialIndex,
                                Name = mesh.Name,
                                NodeIndex = mesh.NodeIndex,
                                Skinning = mesh.Skinning,
                            };
                        finalList.Add(newMeshData);
                    }
                }
            }

            return finalList;
        }
Ejemplo n.º 2
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Mesh"/> class using a shallow copy constructor.
 /// </summary>
 /// <param name="mesh">The mesh.</param>
 public Mesh(Mesh mesh)
 {
     if (mesh == null) throw new ArgumentNullException("mesh");
     Draw = mesh.Draw;
     Parameters = mesh.Parameters.Clone();
     MaterialIndex = mesh.MaterialIndex;
     NodeIndex = mesh.NodeIndex;
     Name = mesh.Name;
     BoundingBox = mesh.BoundingBox;
     Skinning = mesh.Skinning;
 }
Ejemplo n.º 3
0
        protected override async Task LoadContent()
        {
            await base.LoadContent();

            var vertices = new Vertex[4];
            vertices[0] = new Vertex { Position = new Vector3(-1, -1, 0.5f), TexCoords = new Vector2(0, 0) };
            vertices[1] = new Vertex { Position = new Vector3(-1, 1, 0.5f), TexCoords = new Vector2(3, 0) };
            vertices[2] = new Vertex { Position = new Vector3(1, 1, 0.5f), TexCoords = new Vector2(3, 3) };
            vertices[3] = new Vertex { Position = new Vector3(1, -1, 0.5f), TexCoords = new Vector2(0, 3) };

            var indices = new short[] { 0, 1, 2, 0, 2, 3 };

            var vertexBuffer = Buffer.Vertex.New(GraphicsDevice, vertices, GraphicsResourceUsage.Default);
            var indexBuffer = Buffer.Index.New(GraphicsDevice, indices, GraphicsResourceUsage.Default);
            var meshDraw = new MeshDraw
            {
                DrawCount = 4,
                PrimitiveType = PrimitiveType.TriangleList,
                VertexBuffers = new[]
                {
                    new VertexBufferBinding(vertexBuffer,
                        new VertexDeclaration(VertexElement.Position<Vector3>(),
                            VertexElement.TextureCoordinate<Vector2>()),
                        4)
                },
                IndexBuffer = new IndexBufferBinding(indexBuffer, false, indices.Length),
            };

            var mesh = new Mesh
            {
                Draw = meshDraw,
            };

            simpleEffect = new Effect(GraphicsDevice, SpriteEffect.Bytecode);
            parameterCollection = new ParameterCollection();
            parameterCollectionGroup = new EffectParameterCollectionGroup(GraphicsDevice, simpleEffect, new[] { parameterCollection });
            parameterCollection.Set(TexturingKeys.Texture0, UVTexture);

            vao = VertexArrayObject.New(GraphicsDevice, mesh.Draw.IndexBuffer, mesh.Draw.VertexBuffers);

            myDraws = new DrawOptions[3];
            myDraws[0] = new DrawOptions { Sampler = GraphicsDevice.SamplerStates.LinearClamp, Transform = Matrix.Multiply(Matrix.Scaling(0.4f), Matrix.Translation(-0.5f, 0.5f, 0f)) };
            myDraws[1] = new DrawOptions { Sampler = GraphicsDevice.SamplerStates.LinearWrap, Transform = Matrix.Multiply(Matrix.Scaling(0.4f), Matrix.Translation(0.5f, 0.5f, 0f)) };
            myDraws[2] = new DrawOptions { Sampler = SamplerState.New(GraphicsDevice, new SamplerStateDescription(TextureFilter.Linear, TextureAddressMode.Mirror)), Transform = Matrix.Multiply(Matrix.Scaling(0.4f), Matrix.Translation(0.5f, -0.5f, 0f)) };
            //var borderDescription = new SamplerStateDescription(TextureFilter.Linear, TextureAddressMode.Border) { BorderColor = Color.Purple };
            //var border = SamplerState.New(GraphicsDevice, borderDescription);
            //myDraws[3] = new DrawOptions { Sampler = border, Transform = Matrix.Multiply(Matrix.Scale(0.3f), Matrix.Translation(-0.5f, -0.5f, 0f)) };
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Initializes a new instance of the <see cref="RenderMesh" /> class.
        /// </summary>
        /// <param name="renderModel">The render model.</param>
        /// <param name="mesh">The mesh data.</param>
        /// <exception cref="System.ArgumentNullException">mesh</exception>
        public RenderMesh(RenderModel renderModel, Mesh mesh)
        {
            if (renderModel == null) throw new ArgumentNullException("renderModel");
            if (mesh == null) throw new ArgumentNullException("mesh");
            RenderModel = renderModel;
            Mesh = mesh;
            Enabled = true;

            UpdateMaterial();

            // A RenderMesh is inheriting values from Mesh.Parameters
            // We are considering that Mesh.Parameters is not updated frequently (should be almost immutable)
            parameters = new ParameterCollection();
            if (mesh.Parameters != null)
            {
                parameters.AddSources(mesh.Parameters);
            }
        }
Ejemplo n.º 5
0
        public override void Load()
        {
            base.Load();

            slideShowEffect = this.EffectSystemOld.BuildEffect("SlideShow")
                .Using(new StateShaderPlugin() { RenderPassPlugin = this, UseDepthStencilState = true})
                .Using(new BasicShaderPlugin(new ShaderClassSource("PostEffectTransition")) { RenderPassPlugin = this })
                .InstantiatePermutation();

            if (OfflineCompilation)
                return;

            RenderPass.StartPass += (context) =>
                {
                    if (RenderPass.Enabled)
                    {
                        // Setup the Viewport
                        context.GraphicsDevice.SetViewport(MainTargetPlugin.Viewport);

                        // Setup the depth stencil and main render target.
                        context.GraphicsDevice.SetRenderTarget(RenderTarget);
                    }
                };

            RenderPass.EndPass += (context) =>
                {
                    if (RenderPass.Enabled)
                    {
                        context.GraphicsDevice.UnsetRenderTargets();
                    }
                };

            // Generates a quad for post effect rendering (should be utility function)
            var vertices = new[]
            {
                -1.0f,  1.0f, 
                 1.0f,  1.0f,
                -1.0f, -1.0f, 
                 1.0f, -1.0f,
            };

            // Use the quad for this effectMesh
            var quadData = new Mesh();
            quadData.Draw = new MeshDraw
            {
                DrawCount = 4,
                PrimitiveType = PrimitiveType.TriangleStrip,
                VertexBuffers = new[]
                            {
                                new VertexBufferBinding(Buffer.Vertex.New(GraphicsDevice, vertices), new VertexDeclaration(VertexElement.Position<Vector2>()), 4)
                            }
            };
            var textureMesh = new EffectMesh(slideShowEffect, quadData).KeepAliveBy(this);
            textureMesh.Parameters.Set(EffectPlugin.DepthStencilStateKey, GraphicsDevice.DepthStencilStates.None);

            textureMesh.Parameters.AddSources(this.Parameters);
            RenderSystem.GlobalMeshes.AddMesh(textureMesh);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Create a clone with its own ParameterCollection.
        /// It allows reuse of a single Model for multiple ModelComponent.
        /// </summary>
        public Model Instantiate()
        {
            var result = new Model();
            if (Children != null)
            {
                result.Children = new List<Model>();
                foreach (var child in Children)
                {
                    result.Children.Add(child.Instantiate());
                }
            }

            foreach (var mesh in Meshes)
            {
                var meshCopy = new Mesh(mesh);
                result.Meshes.Add(meshCopy);
            }

            result.Hierarchy = Hierarchy;
            result.BoundingBox = BoundingBox;

            return result;
        }
Ejemplo n.º 7
0
 /// <summary>
 /// Adds the specified mesh (for collection initializers).
 /// </summary>
 /// <param name="mesh">The mesh.</param>
 public void Add(Mesh mesh)
 {
     Meshes.Add(mesh);
 }
Ejemplo n.º 8
0
        public override void Load()
        {
            base.Load();

            skyboxEffect = this.EffectSystemOld.BuildEffect("Skybox")
                .Using(new StateShaderPlugin() { RenderPassPlugin = this, UseDepthStencilState = true })
                .Using(new BasicShaderPlugin(
                    new ShaderMixinSource() {
                        Mixins = new List<ShaderClassSource>() { new ShaderClassSource("SkyBox")},
                        Compositions = new Dictionary<string, ShaderSource>() { {"color", SkyBoxColor}}
                    }) { RenderPassPlugin = this })
                .InstantiatePermutation();

            if (OfflineCompilation)
                return;

            Parameters.AddSources(MainPlugin.ViewParameters);

            var zBackgroundValue = MainTargetPlugin.ClearDepth;
            // Generates a quad for post effect rendering (should be utility function)
            var vertices = new[]
                {
                    -1.0f, 1.0f, zBackgroundValue, 1.0f, 
                    1.0f, 1.0f, zBackgroundValue, 1.0f, 
                    -1.0f, -1.0f, zBackgroundValue, 1.0f,  
                    1.0f, -1.0f, zBackgroundValue, 1.0f, 
                };

            Parameters.RegisterParameter(EffectPlugin.DepthStencilStateKey);
            Parameters.Set(TexturingKeys.Sampler, GraphicsDevice.SamplerStates.LinearWrap);

            // Use the quad for this effectMesh
            var quadData = new Mesh();
            quadData.Draw = new MeshDraw
                {
                    DrawCount = 4,
                    PrimitiveType = PrimitiveType.TriangleStrip,
                    VertexBuffers = new[]
                                {
                                    new VertexBufferBinding(Buffer.Vertex.New(GraphicsDevice, vertices), new VertexDeclaration(VertexElement.Position<Vector4>()), 4)
                                }
                };

            RenderPass.StartPass += (context) =>
                {
                    // Setup the Viewport
                    context.GraphicsDevice.SetViewport(MainTargetPlugin.Viewport);

                    // Setup the depth stencil and main render target.
                    context.GraphicsDevice.SetRenderTarget(MainTargetPlugin.DepthStencil, MainTargetPlugin.RenderTarget);
                };

            RenderPass.EndPass += (context) => context.GraphicsDevice.UnsetRenderTargets();

            var skyboxMesh = new EffectMesh(skyboxEffect, quadData).KeepAliveBy(this);
            // If the main target plugin is not clearing anything, we assume that this is the job of the skybox plugin
            if (!MainTargetPlugin.EnableClearTarget && !MainTargetPlugin.EnableClearDepth)
            {
                var description = new DepthStencilStateDescription().Default();
                description.DepthBufferFunction = CompareFunction.Always;
                var alwaysWrite = DepthStencilState.New(GraphicsDevice, description);
                skyboxMesh.Parameters.Set(EffectPlugin.DepthStencilStateKey, alwaysWrite);
            }
            else
            {
                skyboxMesh.Parameters.Set(EffectPlugin.DepthStencilStateKey, MainTargetPlugin.DepthStencilState);
            }

            skyboxMesh.Parameters.AddSources(this.Parameters);
            RenderSystem.GlobalMeshes.AddMesh(skyboxMesh);
        }
        private Entity CreateStandBorder(Material material)
        {
            var mesh = new Mesh
            {
                Draw = GeometricPrimitive.Torus.New(GraphicsDevice, 720, 10, 64).ToMeshDraw(),
                Material = material
            };
            mesh.Parameters.Set(LightingKeys.ReceiveShadows, true);

            return new Entity()
            {
                new ModelComponent
                {
                    Model = new Model()
                    {
                        mesh
                    },
                    Parameters =
                    {
                        {TexturingKeys.Texture0, Asset.Load<Texture>("red")},
                        {TexturingKeys.Sampler0, GraphicsDevice.SamplerStates.AnisotropicWrap},
                        {MaterialKeys.SpecularColorValue, 0.3f*Color4.White}
                    }
                }
            };
        }
        public void Generate(IServiceRegistry services, Model model)
        {
            if (services == null) throw new ArgumentNullException("services");
            if (model == null) throw new ArgumentNullException("model");

            var graphicsDevice = services.GetSafeServiceAs<IGraphicsDeviceService>().GraphicsDevice;

            var data = this.CreatePrimitiveMeshData();

            if (data.Vertices.Length == 0)
            {
                throw new InvalidOperationException("Invalid GeometricPrimitive [{0}]. Expecting non-zero Vertices array");
            }

            var boundingBox = BoundingBox.Empty;
            for (int i = 0; i < data.Vertices.Length; i++)
                BoundingBox.Merge(ref boundingBox, ref data.Vertices[i].Position, out boundingBox);

            BoundingSphere boundingSphere;
            unsafe
            {
                fixed (void* verticesPtr = data.Vertices)
                    BoundingSphere.FromPoints((IntPtr)verticesPtr, 0, data.Vertices.Length, VertexPositionNormalTexture.Size, out boundingSphere);
            }

            var originalLayout = data.Vertices[0].GetLayout();

            // Generate Tangent/BiNormal vectors
            var resultWithTangentBiNormal = VertexHelper.GenerateTangentBinormal(originalLayout, data.Vertices, data.Indices);

            // Generate Multitexcoords
            var result = VertexHelper.GenerateMultiTextureCoordinates(resultWithTangentBiNormal);

            var meshDraw = new MeshDraw();

            var layout = result.Layout;
            var vertexBuffer = result.VertexBuffer;
            var indices = data.Indices;

            if (indices.Length < 0xFFFF)
            {
                var indicesShort = new ushort[indices.Length];
                for (int i = 0; i < indicesShort.Length; i++)
                {
                    indicesShort[i] = (ushort)indices[i];
                }
                meshDraw.IndexBuffer = new IndexBufferBinding(Buffer.Index.New(graphicsDevice, indicesShort).RecreateWith(indicesShort), false, indices.Length);
            }
            else
            {
                if (graphicsDevice.Features.Profile <= GraphicsProfile.Level_9_3)
                {
                    throw new InvalidOperationException("Cannot generate more than 65535 indices on feature level HW <= 9.3");
                }

                meshDraw.IndexBuffer = new IndexBufferBinding(Buffer.Index.New(graphicsDevice, indices).RecreateWith(indices), true, indices.Length);
            }

            meshDraw.VertexBuffers = new[] { new VertexBufferBinding(Buffer.New(graphicsDevice, vertexBuffer, BufferFlags.VertexBuffer).RecreateWith(vertexBuffer), layout, data.Vertices.Length) };

            meshDraw.DrawCount = indices.Length;
            meshDraw.PrimitiveType = PrimitiveType.TriangleList;

            var mesh = new Mesh { Draw = meshDraw, BoundingBox = boundingBox, BoundingSphere = boundingSphere };

            model.BoundingBox = boundingBox;
            model.BoundingSphere = boundingSphere;
            model.Add(mesh);

            if (MaterialInstance != null && MaterialInstance.Material != null)
            {
                model.Materials.Add(MaterialInstance);
            }
        }