Exemplo n.º 1
0
        private void Run()
        {
            // Choose sampler settings that will prevent our texture from blurring when it is scaled up.
            _graphics.TextureSamplerManager
            .Create("crisp", new TextureSamplerSettings(TextureWrapping.Clamp, TextureWrapping.Clamp, TextureWrapping.Clamp, TextureFiltering.MinMagMipPoint))
            .Activate(0);

            // Create a texture that we can write to, making sure the dimensions are a power of 2
            _texture = _graphics.TextureResourceManager.Create2DDynamic("foo", 8, 8, PixelFormat.R32G32B32A32_Float);
            _texture.Activate(0);

            // Prepare our default material with which we will render our dynamic texture. We then set the material
            // active, which sets the active shaders in GPU memory, ready for drawing with.
            var material = _graphics.MaterialManager.Create("simple");

            material.VertexShaderSpec = new VertexShaderSpec(Resources.VertexShader, Vertex.ShaderInputLayout);
            material.PixelShaderSpec  = new PixelShaderSpec(Resources.PixelShader);
            material.Textures.Add("foo");
            material.Activate();

            // We'll use Grasshopper's procedural tools to quickly build a set of vertices for our quad
            var vertices = QuadBuilder.New
                           .XY()
                           .Colors(Color.Red, Color.Green, Color.Blue, Color.Yellow)
                           .Select(v => new Vertex(v.Position, v.Color, v.TextureCoordinate))
                           .ToArray();

            // Create a vertex buffer. We don't need to dispose of it ourselves; it'll automatically get cleaned
            // up when the vertex manager that created it is disposed of.
            var vertexBuffer = _vertexBufferManager.Create("quad");

            // Six vertices will be written here; 3 per triangle
            using (var writer = vertexBuffer.BeginWrite(vertices.Length))
                writer.Write(vertices);

            // Normal vertex buffers should be activated in slot 0; we only use other slots when doing more
            // advanced things with shaders.
            vertexBuffer.Activate(0);

            // Now that our material and vertex buffers are activated and ready to go, let's initiate our main
            // loop and draw our quad!
            _app.Run(_renderTarget, (frame, context) =>
            {
                UpdateTexture(frame);

                context.Clear(Color.CornflowerBlue);
                context.SetDrawType(DrawType.Triangles);
                context.Draw(vertices.Length, 0);
                context.Present();
            });
        }
Exemplo n.º 2
0
        public void Run()
        {
            CreateAndActivateDefaultMaterial();

            // Use Grasshopper's procedural tools to create a cube mesh
            var mesh = CubeBuilder.New.ToMesh("cube",
                                              v => new Vertex(v.Position, v.Color, v.TextureCoordinate, v.FaceIndex));

            // A mesh buffer manager allows us to pack multiple meshes into a vertex buffer and accompanying index
            // buffer, and keep track of the offset locations of each mesh in each buffer. In our case we're only
            // storing one mesh.
            var buffer = _meshBufferManager.Create("default", mesh);

            buffer.Activate();
            var cubeData = buffer["cube"];

            // Create and activate our constant buffer which will hold the final world-view-projection matrix for
            // use by the vertex shader
            var constantBuffer = _constantBufferManager.Create("cube");

            constantBuffer.Activate(0);

            // Create our initial view and projection matrices that will represent the camera
            var view     = Matrix4x4.CreateLookAt(new Vector3(0, 1.25f, 3f), new Vector3(0, 0, 0), Vector3.UnitY);
            var proj     = CreateProjectionMatrix(_renderTarget.Window);
            var viewproj = view * proj;

            // The aspect ratio changes when the window is resized, so we need to reculate the projection matrix, or
            // our cube will look squashed
            _renderTarget.Window.SizeChanged += win => viewproj = view * CreateProjectionMatrix(win);

            // Let's define an arbitrary rotation speed for the cube
            const float rotationsPerSecond = .04f;
            const float twoPI = (float)Math.PI * 2;

            // Let the looping begin!
            _app.Run(_renderTarget, (frame, context) =>
            {
                // Each frame we need to update the cube's rotation, then push the changes to the constant buffer
                var world = Matrix4x4.CreateRotationY(_app.ElapsedSeconds * rotationsPerSecond * twoPI);
                var wvp   = Matrix4x4.Transpose(world * viewproj);
                constantBuffer.Update(wvp);

                context.Clear(Color.CornflowerBlue);
                context.SetDrawType(cubeData.DrawType);
                context.DrawIndexed(cubeData.IndexCount, cubeData.IndexBufferOffset, cubeData.VertexBufferOffset);
                context.Present();
            });
        }
Exemplo n.º 3
0
        static void Main(string[] args)
        {
            using (var app = new GrasshopperApp().UseSharpDX())
                using (var gfx = app.Graphics.CreateContext(enableDebugMode: true))

                    // In this sample we'll create two windows and display each of them with different colours and
                    // titles displaying different information
                    using (var main = gfx.RenderTargetFactory.CreateWindow())
                        using (var other = gfx.RenderTargetFactory.CreateWindow())
                        {
                            main.Window.Visible  = true;
                            other.Window.Visible = true;

                            // Our main loop runs as fast as possible, but we only want to render at 60fps
                            var fpsLimiter = new RateLimiter(60);

                            app.Run(frame =>
                            {
                                if (!fpsLimiter.Ready())
                                {
                                    return(true);
                                }

                                // The first window will show our true frame rate which should be over a million cycles
                                // per second (of which only 60 per second will include the redraws below)
                                main.Render(context =>
                                {
                                    context.Window.Title = "Hello, window #1! Current ticks per second: " + frame.FramesPerSecond.ToString("0");
                                    context.Clear(Color.CornflowerBlue);
                                    context.Present();
                                });

                                // The second window will show the current time
                                other.Render(context =>
                                {
                                    context.Window.Title = "Hello, window #2! It's currently " + DateTime.UtcNow.ToString("F");
                                    context.Clear(Color.Tomato);
                                    context.Present();
                                });

                                // Closing a window sends an exit request, which we can treat as we see fit. In this
                                // case, we will terminate the application by returning false from the main loop only
                                // when both windows are closed.
                                return(!(main.Terminated && other.Terminated));
                            });
                        }
        }
Exemplo n.º 4
0
        private void Run()
        {
            CreateAndActivateDefaultMaterial();

            var vertexCount   = CreateAndActivateVertexBuffer();
            var instanceCount = CreateAndActivateInstanceBuffer();

            // Now that our material and vertex buffers are activated and ready to go, let's initiate our main loop
            // and draw our quad!
            _app.Run(_renderTarget, (frame, context) =>
            {
                context.Clear(Color.CornflowerBlue);
                context.SetDrawType(DrawType.Triangles);
                context.DrawInstanced(vertexCount, instanceCount, 0, 0);
                context.Present();
            });
        }
Exemplo n.º 5
0
        static void Main(string[] args)
        {
            using(var app = new GrasshopperApp().UseSharpDX())
            using(var gfx = app.Graphics.CreateContext(enableDebugMode: true))

            // In this sample we'll create two windows and display each of them with different colours and
            // titles displaying different information
            using(var main = gfx.RenderTargetFactory.CreateWindow())
            using(var other = gfx.RenderTargetFactory.CreateWindow())
            {
                main.Window.Visible = true;
                other.Window.Visible = true;

                // Our main loop runs as fast as possible, but we only want to render at 60fps
                var fpsLimiter = new RateLimiter(60);

                app.Run(() =>
                {
                    if(!fpsLimiter.Ready())
                        return true;

                    // The first window will show our true frame rate which should be over a million cycles
                    // per second (of which only 60 per second will include the redraws below)
                    main.Render(context =>
                    {
                        context.Window.Title = "Hello, window #1! Current ticks per second: " + app.TickCounter.TicksPerSecond.ToString("0");
                        context.Clear(Color.CornflowerBlue);
                        context.Present();
                    });

                    // The second window will show the current time
                    other.Render(context =>
                    {
                        context.Window.Title = "Hello, window #2! It's currently " + DateTime.UtcNow.ToString("F");
                        context.Clear(Color.Tomato);
                        context.Present();
                    });

                    // Closing a window sends an exit request, which we can treat as we see fit. In this
                    // case, we will terminate the application by returning false from the main loop only
                    // when both windows are closed.
                    return !(main.Terminated && other.Terminated);
                });
            }
        }
Exemplo n.º 6
0
        private void Run()
        {
            // Prepare our default material which will simply render out using the vertex colour. We then set the
            // material active, which sets the active shaders in GPU memory, ready for drawing with.
            var material = _graphics.MaterialManager.Create("simple");

            material.VertexShaderSpec = new VertexShaderSpec(Resources.VertexShader, Vertex.ShaderInputLayout);
            material.PixelShaderSpec  = new PixelShaderSpec(Resources.PixelShader);
            material.Activate();

            // We'll use Grasshopper's procedural tools to quickly build a set of vertices for our quad
            var vertices = QuadBuilder.New
                           .XY()
                           .Colors(Color.Red, Color.Green, Color.Blue, Color.Yellow)
                           .Select(v => new Vertex(v.Position, v.Color))
                           .ToArray();

            // Create a vertex buffer. We don't need to dispose of it ourselves; it'll automatically get cleaned
            // up when the vertex manager that created it is disposed of.
            var vertexBuffer = _vertexBufferManager.Create("quad");

            // Six vertices will be written here; 3 per triangle
            using (var writer = vertexBuffer.BeginWrite(vertices.Length))
                writer.Write(vertices);

            // Normal vertex buffers should be activated in slot 0; we only use other slots when doing more
            // advanced things with shaders.
            vertexBuffer.Activate(0);

            // Now that our material and vertex buffers are activated and ready to go, let's initiate our main
            // loop and draw our quad!
            _app.Run(_renderTarget, (frame, context) =>
            {
                context.Clear(Color.CornflowerBlue);
                context.SetDrawType(DrawType.Triangles);
                context.Draw(vertices.Length, 0);
                context.Present();
            });
        }
Exemplo n.º 7
0
        public void Run()
        {
            ConfigureInput();
            CreateAndActivateDefaultMaterial();

            // Use Grasshopper's procedural tools to create a cube mesh
            var mesh = CubeBuilder.New
                       .Size(0.25f)
                       .ToMesh("cube", v => new Vertex(v.Position, v.Color, v.TextureCoordinate));

            // A mesh buffer manager allows us to pack multiple meshes into a vertex buffer and accompanying index
            // buffer, and keep track of the offset locations of each mesh in each buffer. In our case we're only
            // storing one mesh.
            var meshBuffer = _meshBufferManager.Create("default", mesh);

            meshBuffer.Activate();
            var cubeData = meshBuffer["cube"];

            // Create a set of cube instance data with different sizes and rotation values for each cube instance
            var       rand          = new Random();
            const int instanceCount = 100000;
            var       instances     = Enumerable.Range(0, instanceCount)
                                      .Select(i =>
            {
                // rotation on each axis
                var rotX = rand.Next(200) - 100.0f;
                var rotY = rand.Next(200) - 100.0f;
                var rotZ = rand.Next(200) - 100.0f;
                // rotation speed
                var rotS = (rand.Next(200)) / 5000.0f;
                // cube offset from the origin
                var posX = (rand.Next(20000) - 10000) / 100.0f;
                var posY = (rand.Next(20000) - 10000) / 100.0f;
                var posZ = (rand.Next(20000) - 10000) / 100.0f;
                // cube size variation
                var scale = (rand.Next(8) == 0 ? (rand.Next(1500) + 100.0f) : rand.Next(200) + 50.0f) / 100.0f;

                return(new CubeInstance
                {
                    Position = new Vector4(posX, posY, posZ, 0),
                    Rotation = new Vector4(rotX, rotY, rotZ, rotS),
                    Scale = new Vector4(scale, scale, scale, 1),
                    Texture = rand.Next(5)
                });
            });

            // Create an instance buffer and write the instance data to it, then active the buffer in slot 1, so
            // that its values will be included for each vertex in the vertex shader
            var instanceBuffer = _instanceBufferManager.Create("default");

            using (var writer = instanceBuffer.BeginWrite(instanceCount))
                writer.Write(instances.ToArray());
            instanceBuffer.Activate(1);

            // Create our initial view matrix that will represent the camera
            var view = Matrix4x4.CreateLookAt(new Vector3(0, 1.25f, -75f), new Vector3(0, 0, 0), Vector3.UnitY);

            // Create and activate our constant buffer which will hold the world-view-projection data and time
            // signature for use by the vertex shader
            var constantBuffer = _constantBufferManager.Create("cube");

            constantBuffer.Activate(0);

            // Define the data that will go into the constant buffer
            var sceneData = new SceneData {
                View = Matrix4x4.Transpose(view)
            };

            constantBuffer.Update(ref sceneData);

            // Let the looping begin!
            _app.Run(_renderTarget, (frame, context) =>
            {
                MoveCamera();

                sceneData.Projection     = Matrix4x4.Transpose(_camera.ProjectionMatrix);
                sceneData.View           = Matrix4x4.Transpose(_camera.ViewMatrix);
                sceneData.SecondsElapsed = _app.ElapsedSeconds;
                constantBuffer.Update(ref sceneData);

                context.Clear(Color.CornflowerBlue);
                context.SetDrawType(cubeData.DrawType);
                context.DrawIndexedInstanced(cubeData.IndexCount, instanceCount, cubeData.IndexBufferOffset, cubeData.VertexBufferOffset, 0);
                context.Present();
            });
        }