Exemple #1
0
        /// <summary>
        /// Takes a scala field as input anf generates a 2D texture.
        /// </summary>
        /// <param name="device"></param>
        /// <param name="field"></param>
        /// <returns></returns>
        public static Texture2D GenerateTextureFromField(Device device, Field field, Texture2DDescription? description = null)
        {
            System.Diagnostics.Debug.Assert(field.Size.Length == 2);

            Texture2DDescription desc;

            // Either use the given description, or create a render target/shader resource bindable one.
            if (description == null)
                desc = new Texture2DDescription
                {
                    ArraySize = 1,
                    BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource,
                    CpuAccessFlags = CpuAccessFlags.None,
                    Format = Format.R32_Float,
                    Width = field.Size[0],
                    Height = field.Size[1],
                    MipLevels = 1,
                    OptionFlags = ResourceOptionFlags.None,
                    SampleDescription = new SampleDescription(1, 0),
                    Usage = ResourceUsage.Default
                };
            else
                desc = (Texture2DDescription)description;

            // Put field data into stream/rectangle object
            DataRectangle texData = new DataRectangle(field.Size[0] * sizeof(float), field.GetDataStream());

            // Create texture.
            Texture2D tex = new Texture2D(device, desc, texData);

            return tex;
        }
Exemple #2
0
        public QuadBuffers(Device device) {
            VertexBuffer = new Buffer(
                    device,
                    new DataStream(new[] {
                        new InputLayouts.VerticePT(new Vector3(-1, -1, 0.999f), new Vector2(0, 1)),
                        new InputLayouts.VerticePT(new Vector3(-1, 1, 0.999f), new Vector2(0, 0)),
                        new InputLayouts.VerticePT(new Vector3(1, 1, 0.999f), new Vector2(1, 0)),
                        new InputLayouts.VerticePT(new Vector3(1, -1, 0.999f), new Vector2(1, 1))
                    }, false, false),
                    new BufferDescription(
                            InputLayouts.VerticePT.StrideValue * 4,
                            ResourceUsage.Immutable,
                            BindFlags.VertexBuffer,
                            CpuAccessFlags.None,
                            ResourceOptionFlags.None,
                            0));

            IndexBuffer = new Buffer(
                    device,
                    new DataStream(new ushort[] { 0, 1, 2, 0, 2, 3 }, false, false),
                    new BufferDescription(
                            sizeof(short) * 6,
                            ResourceUsage.Immutable,
                            BindFlags.IndexBuffer,
                            CpuAccessFlags.None,
                            ResourceOptionFlags.None,
                            0));

            VertexBinding = new VertexBufferBinding(VertexBuffer, InputLayouts.VerticePT.StrideValue, 0);
        }
Exemple #3
0
        public D3D11RenderingPane( Factory dxgiFactory, SlimDX.Direct3D11.Device d3D11Device, DeviceContext d3D11DeviceContext, D3D11HwndDescription d3D11HwndDescription )
        {
            mDxgiFactory = dxgiFactory;
            mD3D11Device = d3D11Device;
            mD3D11DeviceContext = d3D11DeviceContext;

            var swapChainDescription = new SwapChainDescription
                                       {
                                           BufferCount = 1,
                                           ModeDescription =
                                               new ModeDescription( d3D11HwndDescription.Width,
                                                                    d3D11HwndDescription.Height,
                                                                    new Rational( 60, 1 ),
                                                                    Format.R8G8B8A8_UNorm ),
                                           IsWindowed = true,
                                           OutputHandle = d3D11HwndDescription.Handle,
                                           SampleDescription = new SampleDescription( 1, 0 ),
                                           SwapEffect = SwapEffect.Discard,
                                           Usage = Usage.RenderTargetOutput
                                       };

            mSwapChain = new SwapChain( mDxgiFactory, mD3D11Device, swapChainDescription );
            mDxgiFactory.SetWindowAssociation( d3D11HwndDescription.Handle, WindowAssociationFlags.IgnoreAll );

            CreateD3D11Resources( d3D11HwndDescription.Width, d3D11HwndDescription.Height );

            PauseRendering = false;
        }
Exemple #4
0
        public ShaderResourceView ToTexture3D(Device graphicsDevice, Format format)
        {
            int sizeInBytes = sizeof(float) * width * height * depth;

            DataStream stream = new DataStream(sizeInBytes, true, true);
            for (int x = 0; x < width; x++)
                for (int y = 0; y < height; y++)
                    for (int z = 0; z < depth; z++)
                        stream.Write(values[x, y, z]);
            stream.Position = 0;

            DataBox dataBox = new DataBox(sizeof(float) * width, sizeof(float) * width * height, stream);
            Texture3DDescription description = new Texture3DDescription()
            {
                BindFlags = BindFlags.ShaderResource,
                CpuAccessFlags = CpuAccessFlags.None,
                Depth = depth,
                Format = format,
                Height = height,
                MipLevels = 1,
                OptionFlags = ResourceOptionFlags.None,
                Usage = ResourceUsage.Default,
                Width = width
            };
            Texture3D texture = new Texture3D(graphicsDevice, description, dataBox);

            stream.Dispose();

            return new ShaderResourceView(graphicsDevice, texture);
        }
Exemple #5
0
 public DX11RenderContext(Device device)
 {
     this.Device = device;
     this.immediatecontext = this.Device.ImmediateContext;
     this.immediatecontext.Dispose(); //Remove ref
     this.CurrentDeviceContext = this.immediatecontext;
 }
Exemple #6
0
        public void Initialize(Device device, int resolutionX, int resolutionY)
        {
            m_BokehSpriteTexture = Texture2D.FromFile(device, "textures\\bokeh.dds");
            m_BokehSpriteTextureSRV = new ShaderResourceView(device, m_BokehSpriteTexture);

            m_HalfResDescriptor = new RenderTargetSet.RenderTargetDescriptor()
            {
                m_Format = Format.R16G16B16A16_Float,
                m_HasDepth = false,
                m_NumSurfaces = 1,
                m_Height = resolutionY / 2,
                m_Width = resolutionX / 2
            };

            m_HalfHeightDescriptor = new RenderTargetSet.RenderTargetDescriptor()
            {
                m_Format = Format.R16G16B16A16_Float,
                m_HasDepth = false,
                m_NumSurfaces = 1,
                m_Height = resolutionY / 2,
                m_Width = resolutionX
            };

            m_NumQuads = resolutionX * resolutionY / 4;
        }
        public DirectComputeGenerator(Device graphicsDevice, VoxelMeshContainer container)
        {
            this.graphicsDevice = graphicsDevice;
            this.container = container;

            Initialize();
        }
Exemple #8
0
 public static void InitPatchData(int patchWidth, Device device)
 {
     _width = patchWidth;
     BuildCenterIndices(device);
     BuildTopEdges(device);
     BuildLeftEdges(device);
 }
 public DirectComputePrefixScan(Device graphicsDevice)
 {
     this.graphicsDevice = graphicsDevice;
     computeScanExclusiveShared = new ComputeShader(graphicsDevice, ShaderPrecompiler.PrecompileOrLoad(@"Shaders\TerrainGenerator.hlsl", "ScanExclusiveShared", "cs_5_0", ShaderFlags.None, EffectFlags.None));
     computeScanExclusiveShared2 = new ComputeShader(graphicsDevice, ShaderPrecompiler.PrecompileOrLoad(@"Shaders\TerrainGenerator.hlsl", "ScanExclusiveShared2", "cs_5_0", ShaderFlags.None, EffectFlags.None));
     computeUniformUpdate = new ComputeShader(graphicsDevice, ShaderPrecompiler.PrecompileOrLoad(@"Shaders\TerrainGenerator.hlsl", "UniformUpdate", "cs_5_0", ShaderFlags.None, EffectFlags.None));
 }
        public CUDAGenerator(Device graphicsDevice, VoxelMeshContainer container)
        {
            this.graphicsDevice = graphicsDevice;
            this.container = container;

            InitializeCUDA();
        }
Exemple #11
0
        /// <summary>
        /// Crée une nouvelle instance de BasicEffect.
        /// </summary>
        public BasicEffect(Device device)
        {
            m_effect = Ressources.EffectCache.Get("Shaders\\basic_effect2.fx");

            float Km = 0.0025f;
            float Kr = 0.0015f;
            float ESun = Planet.ESun;
            float fOuterRadius = Planet.AtmosphereRadius; // 50
            float fInnerRadius = Planet.PlanetRadius; // 44
            float fScale = 1.0f / (fOuterRadius - fInnerRadius);
            float fScaleDepth = Planet.ScaleDepth;

            m_effect.GetVariableByName("v3InvWavelength").AsVector().Set(new Vector3(1.0f / (float)Math.Pow(0.650, 4),
                1.0f / (float)Math.Pow(0.570f, 4),
                1.0f / (float)Math.Pow(0.475f, 4)));
            m_effect.GetVariableByName("fOuterRadius").AsScalar().Set(fOuterRadius);
            m_effect.GetVariableByName("fOuterRadius2").AsScalar().Set(fOuterRadius * fOuterRadius);
            m_effect.GetVariableByName("fInnerRadius").AsScalar().Set(fInnerRadius);
            m_effect.GetVariableByName("fInnerRadius2").AsScalar().Set(fInnerRadius * fInnerRadius);
            m_effect.GetVariableByName("fKrESun").AsScalar().Set(Kr * ESun);
            m_effect.GetVariableByName("fKmESun").AsScalar().Set(Km * ESun);
            m_effect.GetVariableByName("fKr4PI").AsScalar().Set(Kr * 4.0f * (float)Math.PI);
            m_effect.GetVariableByName("fKm4PI").AsScalar().Set(Km * 4.0f * (float)Math.PI);
            m_effect.GetVariableByName("fScaleDepth").AsScalar().Set(fScaleDepth);
            m_effect.GetVariableByName("fInvScaleDepth").AsScalar().Set(1.0f / fScaleDepth);
            m_effect.GetVariableByName("fScale").AsScalar().Set(fScale);
            m_effect.GetVariableByName("fScaleOverScaleDepth").AsScalar().Set(fScale / fScaleDepth);
            m_effect.GetVariableByName("xFar").AsScalar().Set(100f);
            m_effect.GetVariableByName("xNear").AsScalar().Set(0.1f);
            m_inputLayout = new InputLayout(
                device,
                m_effect.GetTechniqueByIndex(0).GetPassByIndex(0).Description.Signature,
                VertexPositionTextureNormal.LayoutElements);
            m_device = device;
        }
 public Renderer(int Width, int Height, IntPtr? OutputHandle)
 {
     if (Width < 1)
         Width = 1;
     if (Height < 1)
         Height = 1;
     bufferWidth = Width;
     bufferHeight = Height;
     deviceUsers++;
     if (device == null)
         device = new Device(DriverType.Hardware, DeviceCreationFlags.Debug | DeviceCreationFlags.BgraSupport, FeatureLevel.Level_11_0);
     if (OutputHandle.HasValue)
     {
         SwapChainDescription swapChainDesc = new SwapChainDescription()
         {
             BufferCount = 1,
             ModeDescription = new ModeDescription(BufferWidth, BufferHeight, new Rational(120, 1), Format.R8G8B8A8_UNorm),
             IsWindowed = true,
             OutputHandle = OutputHandle.Value,
             SampleDescription = BufferSampleDescription,
             SwapEffect = SwapEffect.Discard,
             Usage = Usage.RenderTargetOutput,
             Flags = SwapChainFlags.AllowModeSwitch,
         };
         swapChain = new SwapChain(device.Factory, Device, swapChainDesc);
         using (var factory = swapChain.GetParent<Factory>())
             factory.SetWindowAssociation(OutputHandle.Value, WindowAssociationFlags.IgnoreAltEnter);
     }
     LightingSystem = new ForwardLighting(this);
     SetupRenderTargets();
     LightingSystem.Initialize();
 }
        public DeviceContextWpf(DeviceSettings settings)
        {
            Contract.Requires(settings != null);

            Settings = settings;
            LogEvent.Engine.Log(settings.ToString());

            eventHandlerList = new EventHandlerList();

            LogEvent.Engine.Log(Resources.INFO_OE_DeviceCreating);
            //SwapChainDescription swapChainDesc = new SwapChainDescription
            //                                         {
            //                                             BufferCount = 1,
            //                                             ModeDescription =
            //                                                 new ModeDescription(Settings.ScreenWidth, Settings.ScreenHeight,
            //                                                                     new Rational(120, 1), Settings.Format),
            //                                             IsWindowed = true,
            //                                             OutputHandle =(new System.Windows.Interop.WindowInteropHelper(Global.Window)).Handle,
            //                                             SampleDescription = Settings.SampleDescription,
            //                                             SwapEffect = SwapEffect.Discard,
            //                                             Usage = Usage.RenderTargetOutput,
            //                                         };

            //LogEvent.Engine.Log(Resources.INFO_OE_DeviceCreating);
            //Device.CreateWithSwapChain(DriverType.Hardware, Settings.CreationFlags, swapChainDesc, out device, out swapChain);
            device = new Device(DriverType.Hardware, Settings.CreationFlags, FeatureLevel.Level_11_0);

            //if (!Settings.IsWindowed)

            immediate = device.ImmediateContext;

            CreateTargets();
            LogEvent.Engine.Log(Resources.INFO_OE_DeviceCreated);
            device.ImmediateContext.Flush();
        }
        public static void Initialize(Device device, DeviceContext context)
        {
            // Create helper textures
            m_PermTexture = RenderTargetSet.CreateRenderTargetSet(device, 256, 1, Format.R8_UNorm, 1, false);
            m_PermTexture2D = RenderTargetSet.CreateRenderTargetSet(device, 256, 256, Format.R8G8B8A8_UNorm, 1, false);
            m_GradTexture = RenderTargetSet.CreateRenderTargetSet(device, 16, 1, Format.R8G8B8A8_SNorm, 1, false);
            m_PermGradTexture = RenderTargetSet.CreateRenderTargetSet(device, 256, 1, Format.R8G8B8A8_SNorm, 1, false);
            m_PermGrad4DTexture = RenderTargetSet.CreateRenderTargetSet(device, 256, 1, Format.R8G8B8A8_SNorm, 1, false);
            m_GradTexture4D = RenderTargetSet.CreateRenderTargetSet(device, 32, 1, Format.R8G8B8A8_SNorm, 1, false);

            m_PermTexture.BindAsRenderTarget(context);
            PostEffectHelper.RenderFullscreenTriangle(context, "GeneratePermTexture");
            RenderTargetSet.BindNull(context);

            m_PermTexture2D.BindAsRenderTarget(context);
            PostEffectHelper.RenderFullscreenTriangle(context, "GeneratePermTexture2d");
            RenderTargetSet.BindNull(context);

            m_GradTexture.BindAsRenderTarget(context);
            PostEffectHelper.RenderFullscreenTriangle(context, "GenerateGradTexture");
            RenderTargetSet.BindNull(context);

            m_PermGradTexture.BindAsRenderTarget(context);
            PostEffectHelper.RenderFullscreenTriangle(context, "GeneratePermGradTexture");
            RenderTargetSet.BindNull(context);

            m_PermGrad4DTexture.BindAsRenderTarget(context);
            PostEffectHelper.RenderFullscreenTriangle(context, "GeneratePermGrad4dTexture");
            RenderTargetSet.BindNull(context);

            m_GradTexture4D.BindAsRenderTarget(context);
            PostEffectHelper.RenderFullscreenTriangle(context, "GenerateGradTexture4d");
            RenderTargetSet.BindNull(context);
        }
Exemple #15
0
        public Minimap(Device device, DeviceContext dc, int minimapWidth, int minimapHeight, Terrain terrain, CameraBase viewCam)
        {
            _dc = dc;

            _minimapViewport = new Viewport(0, 0, minimapWidth, minimapHeight);

            CreateMinimapTextureViews(device, minimapWidth, minimapHeight);

            _terrain = terrain;

            SetupOrthoCamera();
            _viewCam = viewCam;

            // frustum vb will contain four corners of view frustum, with first vertex repeated as the last
            var vbd = new BufferDescription(
                VertexPC.Stride * 5,
                ResourceUsage.Dynamic,
                BindFlags.VertexBuffer,
                CpuAccessFlags.Write,
                ResourceOptionFlags.None,
                0
            );
            _frustumVB = new Buffer(device, vbd);

            _edgePlanes = new[] {
            new Plane(1, 0, 0, -_terrain.Width / 2),
            new Plane(-1, 0, 0, _terrain.Width / 2),
            new Plane(0, 1, 0, -_terrain.Depth / 2),
            new Plane(0, -1, 0, _terrain.Depth / 2)
            };

            ScreenPosition = new Vector2(0.25f, 0.75f);
            Size = new Vector2(0.25f, 0.25f);
        }
 public static CustomConstantBufferInstance CreateConstantBufferInstance(String name, Device device)
 {
     if (m_ConstantBuffers.ContainsKey(name))
     {
         return new CustomConstantBufferInstance(m_ConstantBuffers[name], device);
     }
     throw new Exception("Unrecognized constant buffer" + name);
 }
Exemple #17
0
 protected override int SetLayout(Device device)
 {
     layout = new InputLayout(device, effect.GetTechniqueByIndex(0).GetPassByIndex(0).Description.Signature, new[] {
         new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
         new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0)
     });
     return 16 * 2;
 }
        public ModelRenderer(Device device, Model model)
        {
            _device = device;
            Model = model;

            RenderParameters = new RenderParameters();

            CompileShaders(Path.Combine("Textures", "Texture.dds"), Path.Combine("Shaders", "Tessellation.hlsl"));
        }
Exemple #19
0
        public Ssao(Device device, DeviceContext dc, int width, int height, float fovY, float farZ) {
            _device = device;
            _dc = dc;
            OnSize(width, height, fovY, farZ);

            BuildFullScreenQuad();
            BuildOffsetVectors();
            BuildRandomVectorTexture();
        }
Exemple #20
0
        /// <summary>
        /// Initializes object.
        /// </summary>
        /// <param name="graphicsDevice">Virtual adapter used to perform rendering.</param>
        /// <param name="camera">Reference to camera, which is used in some computations.</param>
        public VoxelMesh(Device graphicsDevice, Camera camera)
        {
            Container = new VoxelMeshContainer
            {
                Settings = new VoxelMeshSettings(graphicsDevice)
            };

            Renderer = new DefaultRenderer(graphicsDevice, camera, Container);
            Generator = new CPUGenerator(graphicsDevice, Container);
        }
Exemple #21
0
 protected override int SetLayout(Device device)
 {
     layout = new InputLayout(device, effect.GetTechniqueByIndex(0).GetPassByIndex(0).Description.Signature, new[] {
         new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0), //16
         new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0), //16
         new InputElement("NORMAL", 0, Format.R32G32B32_Float, 32, 0), //12
         new InputElement("TEXCOORD", 0, Format.R32G32_Float, 44, 0),  //8
         new InputElement("PSIZE", 0, Format.R32_Float, 52, 0),  //4
     });
     return 56;
 }
Exemple #22
0
        public void Initialize(Device device)
        {
            m_VolumeX = (int)ShaderManager.GetUIntShaderDefine("VOLUME_WIDTH");
            m_VolumeY = (int)ShaderManager.GetUIntShaderDefine("VOLUME_HEIGHT");
            m_VolumeZ = (int)ShaderManager.GetUIntShaderDefine("VOLUME_DEPTH");

            m_DensityTexture = TextureObject.CreateTexture3D(device, m_VolumeX, m_VolumeY, m_VolumeZ, Format.R16_Float);
            m_LightingTexturePing = TextureObject.CreateTexture3D(device, m_VolumeX, m_VolumeY, m_VolumeZ, Format.R16G16B16A16_Float);
            m_LightingTexturePong = TextureObject.CreateTexture3D(device, m_VolumeX, m_VolumeY, m_VolumeZ, Format.R16G16B16A16_Float);
            m_ScatteringTexture = TextureObject.CreateTexture3D(device, m_VolumeX, m_VolumeY, m_VolumeZ, Format.R16G16B16A16_Float);
        }
Exemple #23
0
 /// <summary>
 /// Lists supported DXGI formats for a given usage
 /// </summary>
 /// <param name="dev">Device to check format support for</param>
 /// <param name="usage">Requested Usage</param>
 /// <returns>List of Supported formats</returns>
 public List<string> SupportedFormats(Device dev, FormatSupport usage)
 {
     List<string> result = new List<string>();
     foreach (string s in Enum.GetNames(typeof(Format)))
     {
         if (IsSupported(dev, usage, (Format)Enum.Parse(typeof(Format), s)))
         {
             result.Add(s);
         }
     }
     return result;
 }
        public TerrainObject(TerrainRenderer renderer, Device renderingDevice)
        {
            this.renderingDevice = renderingDevice;
            this.renderer = renderer;

            // Default position
            Position = new Vector3(0, 20, 0);

            // Load textures
            noiseTexture = ShaderResourceView.FromFile(renderingDevice, renderer.Directory + "\\Resources\\Noise.dds");
            grassTexture = ShaderResourceView.FromFile(renderingDevice, renderer.Directory + "\\Resources\\Grass.dds");
            sandTexture = ShaderResourceView.FromFile(renderingDevice, renderer.Directory + "\\Resources\\Sand.dds");
            snowTexture = ShaderResourceView.FromFile(renderingDevice, renderer.Directory + "\\Resources\\Snow.dds");
            snowRockTexture = ShaderResourceView.FromFile(renderingDevice, renderer.Directory + "\\Resources\\SnowRock.dds");

            // Create shader
            SetSourceCode(" float4 getColor(float4 position, float4 normal, float4 camera) { return float4(0, 0, 0, 0); } ");

            // Read data from file
            Vector3[] vertices; int[] indices;

            new XLoader().LoadFile(renderer.Directory + "\\Resources\\Terrain.X", out vertices, out indices);

            //
            DataStream vertexStream = new DataStream(vertices.Length * 12, true, true);
            vertexStream.WriteRange(vertices);
            vertexStream.Position = 0;

            DataStream indexStream = new DataStream(indices.Length * 4, true, true);
            indexStream.WriteRange(indices);
            indexStream.Position = 0;

            //
            BufferDescription vbufferDescription = new BufferDescription();
            vbufferDescription.BindFlags = BindFlags.VertexBuffer;
            vbufferDescription.CpuAccessFlags = CpuAccessFlags.None;
            vbufferDescription.OptionFlags = ResourceOptionFlags.None;
            vbufferDescription.SizeInBytes = (int)vertexStream.Length;
            vbufferDescription.Usage = ResourceUsage.Immutable;

            vertexBuffer = new Buffer(renderingDevice, vertexStream, vbufferDescription);

            //
            BufferDescription ibufferDescription = new BufferDescription();
            ibufferDescription.BindFlags = BindFlags.IndexBuffer;
            ibufferDescription.CpuAccessFlags = CpuAccessFlags.None;
            ibufferDescription.OptionFlags = ResourceOptionFlags.None;
            ibufferDescription.SizeInBytes = (int)indexStream.Length;
            ibufferDescription.Usage = ResourceUsage.Immutable;

            indexBuffer = new Buffer(renderingDevice, indexStream, ibufferDescription);
            indexCount = (int)indexStream.Length / 4;
        }
        public DeviceFormatHelper(Device device)
        {
            this.device = device;

            foreach (object o in Enum.GetValues(typeof(FormatSupport)))
            {
                FormatSupport usage = (FormatSupport)o;
                this.RegisterFormats(usage);

                string[] fmts = this.usageformats[usage].ToArray();
                //host.UpdateEnum(this.GetEnumName(usage), fmts[0], fmts);
                EnumManager.UpdateEnum(this.GetEnumName(usage), fmts[0], fmts);
            }
        }
Exemple #26
0
        public void CreateMesh(Terrain terrain, Rectangle r, Device device)
        {
            _patchBounds = r;
            if (_vb != null) {
                Util.ReleaseCom(ref _vb);
                _vb = null;
            }

            var halfWidth = 0.5f * terrain.Width;
            var halfDepth = 0.5f * terrain.Depth;

            var patchWidth = terrain.Width / (terrain.NumPatchVertCols - 1);
            var patchDepth = terrain.Depth / (terrain.NumPatchVertRows - 1);
            var vertWidth = terrain.Info.CellSpacing;
            var vertDepth = terrain.Info.CellSpacing;
            var du = 1.0f / (terrain.NumPatchVertCols - 1) / Terrain.CellsPerPatch;
            var dv = 1.0f / (terrain.NumPatchVertRows - 1) / Terrain.CellsPerPatch;

            _verts = new List<TerrainCP>();
            var min = new Vector3(float.MaxValue);
            var max = new Vector3(float.MinValue);
            for (int z = r.Top, z0 = 0; z <= r.Bottom; z++, z0++) {
                var zp = halfDepth - r.Top / Terrain.CellsPerPatch * patchDepth - z0 * vertDepth;

                for (int x = r.Left, x0 = 0; x <= r.Right; x++, x0++) {
                    var xp = -halfWidth + r.Left / Terrain.CellsPerPatch * patchWidth + x0 * vertWidth;
                    var pos = new Vector3(xp, terrain.Height(xp, zp), zp);

                    min = Vector3.Minimize(min, pos);
                    max = Vector3.Maximize(max, pos);

                    var uv = new Vector2(r.Left * du + x0 * du, r.Top * dv + z0 * dv);
                    var v = new TerrainCP(pos, uv, new Vector2());
                    _verts.Add(v);
                }
            }

            Bounds = new BoundingBox(min, max);

            var vbd = new BufferDescription(
                TerrainCP.Stride * _verts.Count,
                ResourceUsage.Immutable,
                BindFlags.VertexBuffer,
                CpuAccessFlags.None,
                ResourceOptionFlags.None,
                0
            );
            _vb = new Buffer(device, new DataStream(_verts.ToArray(), false, false), vbd);
        }
Exemple #27
0
 public static Buffer CreateVertexBuffer(SlimDX.Direct3D11.Device graphicsDevice, System.Array vertices)
 {
     using (SlimDX.DataStream vertexStream = new SlimDX.DataStream(vertices, true, true))
     {
         return(new Buffer(
                    graphicsDevice,
                    vertexStream,
                    new BufferDescription
         {
             SizeInBytes = (int)vertexStream.Length,
             BindFlags = BindFlags.VertexBuffer,
         }
                    ));
     }
 }
Exemple #28
0
        public SSAOEffectPass(SlimDX.Direct3D11.Device device, int resolutionX, int resolutionY)
        {
            m_RTDescriptor = new RenderTargetSet.RenderTargetDescriptor()
            {
                m_Format      = Format.R8G8B8A8_UNorm,
                m_HasDepth    = false,
                m_NumSurfaces = 1,
                m_Height      = resolutionY,
                m_Width       = resolutionX
            };

            TemporalSurfaceManager.InitializeRenderTarget("SSAO", m_RTDescriptor);

            m_SSAOBuffer = ShaderManager.CreateConstantBufferInstance("SSAOBuffer", device);
        }
        protected override void OnInitialization(Graphics3DConfiguration config)
        {
            if (GraphicsDirect3D11.Device != null)
            {
                throw new Graphics3DStateException("Cannot do device initialization: Device already initialized!");
            }

            Device11 device = null;

            Device11.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, Direct3DConverter11.ConvertToSwapChainDescription(config), out device, out swapChain);
            //Setup device to main device
            GraphicsDirect3D11.Device = device;

            SetupRenderTarget();
        }
        // Static functions
        static public GPUBufferObject CreateBuffer(Device device, int size, int elementSizeInBytes, DataStream stream = null, bool append = false, bool allowStaging = false)
        {
            GPUBufferObject newBuffer = new GPUBufferObject();

            // Variables
            newBuffer.m_Size = size;

            BindFlags bindFlags = BindFlags.ShaderResource | BindFlags.UnorderedAccess;

            BufferDescription description = new BufferDescription(size * elementSizeInBytes, ResourceUsage.Default, bindFlags, CpuAccessFlags.None, ResourceOptionFlags.StructuredBuffer, elementSizeInBytes);

            newBuffer.m_BufferObject = stream != null ? new Buffer(device, stream, description) : new Buffer(device, description);

            ShaderResourceViewDescription srvViewDesc = new ShaderResourceViewDescription
            {
                FirstElement = 0,
                ElementCount = size,
                Format       = Format.Unknown,
                Dimension    = ShaderResourceViewDimension.ExtendedBuffer,
                Flags        = 0,
            };

            newBuffer.m_ShaderResourceView = new ShaderResourceView(device, newBuffer.m_BufferObject, srvViewDesc);


            UnorderedAccessViewDescription uavDesc = new UnorderedAccessViewDescription
            {
                ArraySize    = 0,
                Dimension    = UnorderedAccessViewDimension.Buffer,
                ElementCount = size,
                Flags        = append ? UnorderedAccessViewBufferFlags.AllowAppend : UnorderedAccessViewBufferFlags.None,
                Format       = Format.Unknown,
                MipSlice     = 0
            };

            newBuffer.m_UnorderedAccessView = new UnorderedAccessView(device, newBuffer.m_BufferObject, uavDesc);

            if (allowStaging)
            {
                description = new BufferDescription(size * elementSizeInBytes, ResourceUsage.Staging, BindFlags.None, CpuAccessFlags.Read, ResourceOptionFlags.StructuredBuffer, elementSizeInBytes);
                newBuffer.m_StagingBufferObject = new Buffer(device, description);

                description = new BufferDescription(16, ResourceUsage.Staging, BindFlags.None, CpuAccessFlags.Read, ResourceOptionFlags.None, 4);
                newBuffer.m_StagingCountBufferObject = new Buffer(device, description);
            }

            return(newBuffer);
        }
Exemple #31
0
        private void StartD3D()
        {
            DeviceCreationFlags creationFlags = DeviceCreationFlags.BgraSupport;

#if DEBUG
            creationFlags |= DeviceCreationFlags.Debug;
#endif
            this.Device = new Device(DriverType.Hardware, creationFlags, FeatureLevel.Level_11_0);

            this.D3DSurface = new DX11ImageSource();
            this.D3DSurface.IsFrontBufferAvailableChanged += OnIsFrontBufferAvailableChanged;

            this.CreateAndBindTargets();

            this.Source = this.D3DSurface;
        }
Exemple #32
0
 public static Buffer CreateIndexBuffer(SlimDX.Direct3D11.Device graphicsDevice, uint[] indices)
 {
     using (SlimDX.DataStream indicesStream = new SlimDX.DataStream(indices, true, true))
     {
         return(new Buffer(
                    graphicsDevice,
                    indicesStream,
                    new BufferDescription
         {
             SizeInBytes = (int)indicesStream.Length,
             BindFlags = BindFlags.IndexBuffer,
             StructureByteStride = sizeof(uint)
         }
                    ));
     }
 }
Exemple #33
0
        internal override void Apply(SlimDX.Direct3D11.Buffer vertices)
        {
            Device device = t.Device;

            device.ImmediateContext.InputAssembler.InputLayout = layout;
            device.ImmediateContext.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertices, stride, 0));
            effect.GetVariableByName("gWorld").AsMatrix().SetMatrix(Camera.Instance.World);
            effect.GetVariableByName("gView").AsMatrix().SetMatrix(Camera.Instance.View);
            effect.GetVariableByName("gProj").AsMatrix().SetMatrix(Camera.Instance.Projection);
            effect.GetVariableByName("intexture").AsResource().SetResource(t.ActiveTexture);
            effect.GetVariableByName("eye").AsVector().Set(Camera.Instance.EyePosition);
            effect.GetVariableByName("fogNear").AsScalar().Set((float)GameSettings.ViewRadius - 32f);
            effect.GetVariableByName("fogFar").AsScalar().Set((float)GameSettings.ViewRadius);
            effect.GetVariableByName("fogColor").AsVector().Set(GlobalRenderer.Instance.BackgroundColor);
            effect.GetTechniqueByIndex(TechniqueIndex).GetPassByIndex(0).Apply(device.ImmediateContext);
        }
Exemple #34
0
        public void SetVertices <TVertexType>(Device device, List <TVertexType> vertices) where TVertexType : struct
        {
            Util.ReleaseCom(ref _vb);
            _vertexStride = Marshal.SizeOf(typeof(TVertexType));

            var vbd = new BufferDescription(
                _vertexStride * vertices.Count,
                ResourceUsage.Immutable,
                BindFlags.VertexBuffer,
                CpuAccessFlags.None,
                ResourceOptionFlags.None,
                0
                );

            _vb = new Buffer(device, new DataStream(vertices.ToArray(), false, false), vbd);
        }
Exemple #35
0
        static public void Initialize(Device device)
        {
            if (m_Initialized)
            {
                throw new Exception("Already initialized!");
            }

            string[] filters = new[] { "*.hlsl", "*.fx" };

            foreach (string f in filters)
            {
                FileSystemWatcher w = new FileSystemWatcher();
                w.Filter              = f;
                w.Changed            += new FileSystemEventHandler(OnFileChanged);
                w.Renamed            += new RenamedEventHandler(OnFileChanged);
                w.NotifyFilter        = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName;
                w.Path                = Directory.GetCurrentDirectory() + "\\shaders";
                w.EnableRaisingEvents = true;
                m_Watchers.Add(w);
            }

            m_Initialized = true;
            m_Include     = new IncludeFX();

            CultureInfo ci = new CultureInfo("en-US", false);

            string[] filePaths = filters.SelectMany(f => Directory.GetFiles(Directory.GetCurrentDirectory() + "\\shaders", f)).ToArray();

            foreach (string path in filePaths)
            {
                string     fileName = GetFileNameFromPath(path);
                ShaderFile sf       = new ShaderFile();
                sf.m_DirectlyIncludedFiles = new List <String>();
                sf.m_FileName       = fileName;
                sf.m_FilePath       = path;
                sf.m_FlattenedFiles = new HashSet <String>();

                m_AllShaderFiles.Add(fileName, sf);
            }

            foreach (string path in filePaths)
            {
                ParseFile(path);
            }
            FlattenIncludes();
            FinalizeCompilationOnDevice(device);
        }
        public static void Initialize(Device device)
        {
            {
                var blendStateDescription = new BlendStateDescription();
                blendStateDescription.RenderTargets[0].BlendEnable           = false;
                blendStateDescription.RenderTargets[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;
                blendStateDescription.RenderTargets[1].BlendEnable           = false;
                blendStateDescription.RenderTargets[1].RenderTargetWriteMask = ColorWriteMaskFlags.None;
                blendStateDescription.RenderTargets[2].BlendEnable           = false;
                blendStateDescription.RenderTargets[2].RenderTargetWriteMask = ColorWriteMaskFlags.None;
                blendStateDescription.RenderTargets[3].BlendEnable           = false;
                blendStateDescription.RenderTargets[3].RenderTargetWriteMask = ColorWriteMaskFlags.None;

                m_BlendStates[(int)BlendType.None] = BlendState.FromDescription(device, blendStateDescription);

                blendStateDescription.RenderTargets[0].BlendEnable           = true;
                blendStateDescription.RenderTargets[0].BlendOperation        = BlendOperation.Add;
                blendStateDescription.RenderTargets[0].BlendOperationAlpha   = BlendOperation.Add;
                blendStateDescription.RenderTargets[0].DestinationBlend      = BlendOption.One;
                blendStateDescription.RenderTargets[0].DestinationBlendAlpha = BlendOption.One;
                blendStateDescription.RenderTargets[0].SourceBlend           = BlendOption.One;
                blendStateDescription.RenderTargets[0].SourceBlendAlpha      = BlendOption.One;
                blendStateDescription.RenderTargets[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;

                m_BlendStates[(int)BlendType.Additive] = BlendState.FromDescription(device, blendStateDescription);
            }

            {
                var depthStencilStateDescription = new DepthStencilStateDescription();
                depthStencilStateDescription.DepthComparison  = Comparison.Always;
                depthStencilStateDescription.DepthWriteMask   = DepthWriteMask.Zero;
                depthStencilStateDescription.IsDepthEnabled   = false;
                depthStencilStateDescription.IsStencilEnabled = false;

                m_DepthStencilStates[(int)DepthConfigurationType.NoDepth] = DepthStencilState.FromDescription(device, depthStencilStateDescription);

                depthStencilStateDescription.DepthComparison = Comparison.LessEqual;
                depthStencilStateDescription.DepthWriteMask  = DepthWriteMask.All;
                depthStencilStateDescription.IsDepthEnabled  = true;

                m_DepthStencilStates[(int)DepthConfigurationType.DepthWriteCompare] = DepthStencilState.FromDescription(device, depthStencilStateDescription);

                depthStencilStateDescription.DepthWriteMask = DepthWriteMask.Zero;

                m_DepthStencilStates[(int)DepthConfigurationType.DepthCompare] = DepthStencilState.FromDescription(device, depthStencilStateDescription);
            }
        }
Exemple #37
0
        private static void BuildIndices(Device device)
        {
            for (var tessLevel = 0; tessLevel <= 6; tessLevel++)
            {
                var t       = (int)Math.Pow(2, tessLevel);
                var indices = new List <short>();
                for (int z = 0, z0 = 0; z < width; z += t, z0 += t)
                {
                    for (int x = 0, x0 = 0; x < width; x += t, x0 += t)
                    {
                        indices.Add((short)(z0 * (width + 1) + x0));
                        indices.Add((short)(z0 * (width + 1) + x0 + t));
                        indices.Add((short)((z0 + t) * (width + 1) + x0));

                        indices.Add((short)((z0 + t) * (width + 1) + x0));
                        indices.Add((short)(z0 * (width + 1) + x0 + t));
                        indices.Add((short)((z0 + t) * (width + 1) + x0 + t));
                    }
                }

                var ibd = new BufferDescription(
                    sizeof(short) * indices.Count,
                    ResourceUsage.Dynamic,
                    BindFlags.IndexBuffer,
                    CpuAccessFlags.Write,
                    ResourceOptionFlags.None,
                    0
                    );

                if (IB != null)
                {
                    if (indices.Count > 0)
                    {
                        IB[t] = new Buffer(
                            device,
                            new DataStream(indices.ToArray(), false, true),
                            ibd
                            );
                    }
                    else
                    {
                        IB[t] = null;
                    }
                }
                IndexCount[t] = indices.Count;
            }
        }
        // Static functions
        static public GPUBufferObject CreateBuffer(Device device, int size, int elementSizeInBytes, DataStream stream = null, bool append = false, bool allowStaging = false)
        {
            GPUBufferObject newBuffer = new GPUBufferObject();

            // Variables
            newBuffer.m_Size = size;

            BindFlags bindFlags = BindFlags.ShaderResource | BindFlags.UnorderedAccess;

            BufferDescription description = new BufferDescription(size * elementSizeInBytes, ResourceUsage.Default, bindFlags, CpuAccessFlags.None, ResourceOptionFlags.StructuredBuffer, elementSizeInBytes);

            newBuffer.m_BufferObject = stream != null ? new Buffer(device, stream, description) : new Buffer(device, description);

            ShaderResourceViewDescription srvViewDesc = new ShaderResourceViewDescription
            {
                FirstElement = 0,
                ElementCount = size,
                Format = Format.Unknown,
                Dimension = ShaderResourceViewDimension.ExtendedBuffer,
                Flags = 0,
            };

            newBuffer.m_ShaderResourceView = new ShaderResourceView(device, newBuffer.m_BufferObject, srvViewDesc);


            UnorderedAccessViewDescription uavDesc = new UnorderedAccessViewDescription
            {
                ArraySize = 0,
                Dimension = UnorderedAccessViewDimension.Buffer,
                ElementCount = size,
                Flags = append ? UnorderedAccessViewBufferFlags.AllowAppend : UnorderedAccessViewBufferFlags.None,
                Format = Format.Unknown,
                MipSlice = 0
            };
            newBuffer.m_UnorderedAccessView = new UnorderedAccessView(device, newBuffer.m_BufferObject, uavDesc);

            if (allowStaging)
            {
                description = new BufferDescription(size * elementSizeInBytes, ResourceUsage.Staging, BindFlags.None, CpuAccessFlags.Read, ResourceOptionFlags.StructuredBuffer, elementSizeInBytes);
                newBuffer.m_StagingBufferObject = new Buffer(device, description);

                description = new BufferDescription(16, ResourceUsage.Staging, BindFlags.None, CpuAccessFlags.Read, ResourceOptionFlags.None, 4);
                newBuffer.m_StagingCountBufferObject = new Buffer(device, description);
            }

            return newBuffer;
        }
Exemple #39
0
        public QuadBuffers(Device device)
        {
            _verticesStream = new DataStream(new[] {
                new InputLayouts.VerticePT(new Vector3(1, 1, 0.999f), new Vector2(1, 0)),
                new InputLayouts.VerticePT(new Vector3(-1, 1, 0.999f), new Vector2(0, 0)),
                new InputLayouts.VerticePT(new Vector3(-1, -1, 0.999f), new Vector2(0, 1)),
                new InputLayouts.VerticePT(new Vector3(1, -1, 0.999f), new Vector2(1, 1))
            }, false, false);
            _verticesBuffer = new Buffer(device, _verticesStream, new BufferDescription(InputLayouts.VerticePT.StrideValue * 4,
                                                                                        ResourceUsage.Immutable, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0));

            _indicesStream = new DataStream(new ushort[] { 0, 2, 1, 0, 3, 2 }, false, false);
            _indicesBuffer = new Buffer(device, _indicesStream, new BufferDescription(sizeof(short) * 6,
                                                                                      ResourceUsage.Immutable, BindFlags.IndexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0));

            VertexBinding = new VertexBufferBinding(_verticesBuffer, InputLayouts.VerticePT.StrideValue, 0);
        }
Exemple #40
0
        /// <summary>
        /// モデルを描画する
        /// </summary>
        public void DrawModel(Dx11.Device device, Dx11.Effect effect)
        {
            int startIdx = 0, indexCount = 0;

            for (int i = 0; i < Cnv.meshSection.matList.PolygonCount; i++)
            {
                //マテリアル名から一致するマテリアルを調べる
                int    matNum  = Cnv.meshSection.matList.materialIndex[i];
                string refName = Cnv.meshSection.matList.materialReferens[matNum];

                Material m = GetMaterialFromReference(refName);
                //Console.WriteLine("mat:" + matNum + "-> ref:" + refName + ",matName:" + m.Name);

                //テクスチャを利用しているかどうか
                if (!m.TextureFileName.Equals(""))
                {
                    effect.GetVariableByName("tex").AsScalar().Set(true);
                    effect.GetVariableByName("normalTexture").AsResource().SetResource(textureManager.GetTexture(m.Name));
                }
                else
                {
                    effect.GetVariableByName("tex").AsScalar().Set(false);
                    effect.GetVariableByName("mat").AsScalar().Set(true);
                    effect.GetVariableByName("matColor").AsVector().Set(m.DiffuseColor);
                }

                //頂点数が4の場合は2つに分割する
                if (Cnv.meshSection.meshList.mesh[i].Length == VTXNUM_SQUARE)
                {
                    indexCount = 6;
                    effect.GetTechniqueByIndex(0).GetPassByIndex(0).Apply(device.ImmediateContext);
                    device.ImmediateContext.DrawIndexed(indexCount, startIdx, 0);
                }
                else
                {
                    indexCount = 3;
                    effect.GetTechniqueByIndex(0).GetPassByIndex(0).Apply(device.ImmediateContext);
                    device.ImmediateContext.DrawIndexed(indexCount, startIdx, 0);
                }
                startIdx += indexCount;
            }

            effect.GetVariableByName("tex").AsScalar().Set(false);
            effect.GetTechniqueByIndex(0).GetPassByIndex(0).Apply(device.ImmediateContext);
            device.ImmediateContext.DrawIndexed(indices.Count, 0, 0);
        }
Exemple #41
0
        // Static functions
        static public TextureObject CreateTexture3DFromFile(Device device, int width, int height, int depth, Format format, string fileName)
        {
            TextureObject newTexture = new TextureObject();

            // Variables
            newTexture.m_Width     = width;
            newTexture.m_Height    = height;
            newTexture.m_Depth     = depth;
            newTexture.m_TexFormat = format;
            newTexture.m_Mips      = 1;

            BindFlags bindFlags = BindFlags.ShaderResource | BindFlags.RenderTarget | BindFlags.UnorderedAccess;

            ImageLoadInformation imageLoadInfo = new ImageLoadInformation()
            {
                BindFlags      = bindFlags,
                CpuAccessFlags = CpuAccessFlags.None,
                Format         = format,
                Height         = height,
                Width          = width,
                Depth          = depth,
                MipLevels      = 1,
                OptionFlags    = ResourceOptionFlags.None,
                Usage          = ResourceUsage.Default
            };

            newTexture.m_TextureObject3D = Texture3D.FromFile(device, fileName, imageLoadInfo);

            ShaderResourceViewDescription srvViewDesc = new ShaderResourceViewDescription
            {
                ArraySize       = 0,
                Format          = format,
                Dimension       = ShaderResourceViewDimension.Texture3D,
                Flags           = 0,
                FirstArraySlice = 0,
                MostDetailedMip = 0,
                MipLevels       = 1,
            };

            newTexture.m_ShaderResourceView = new ShaderResourceView(device, newTexture.m_TextureObject3D, srvViewDesc);

            newTexture.m_RenderTargetView    = new RenderTargetView(device, newTexture.m_TextureObject3D);
            newTexture.m_UnorderedAccessView = new UnorderedAccessView(device, newTexture.m_TextureObject3D);

            return(newTexture);
        }
        public TeapotObject(TeapotRenderer renderer, Device renderingDevice)
        {
            this.renderingDevice = renderingDevice;
            this.renderer = renderer;

            // Default position
            Position = new Vector3(0, 20, 0);

            // Create shader
            SetSourceCode(" float4 getColor(float4 position, float4 normal, float4 camera) { return float4(0, 0, 0, 0); } ");

            // Read data from file
            Vector3[] vertices; short[] indices;

            new XLoader().LoadFile(renderer.Directory + "\\Resources\\Teapot.X" , out vertices, out indices);

            //
            DataStream vertexStream = new DataStream(vertices.Length * 12, true, true);
            vertexStream.WriteRange(vertices);
            vertexStream.Position = 0;

            DataStream indexStream = new DataStream(indices.Length * 2, true, true);
            indexStream.WriteRange(indices);
            indexStream.Position = 0;
            
            //
            BufferDescription vbufferDescription = new BufferDescription();
            vbufferDescription.BindFlags = BindFlags.VertexBuffer;
            vbufferDescription.CpuAccessFlags = CpuAccessFlags.None;
            vbufferDescription.OptionFlags = ResourceOptionFlags.None;
            vbufferDescription.SizeInBytes = (int)vertexStream.Length;
            vbufferDescription.Usage = ResourceUsage.Immutable;

            vertexBuffer = new Buffer(renderingDevice, vertexStream, vbufferDescription);

            //
            BufferDescription ibufferDescription = new BufferDescription();
            ibufferDescription.BindFlags = BindFlags.IndexBuffer;
            ibufferDescription.CpuAccessFlags = CpuAccessFlags.None;
            ibufferDescription.OptionFlags = ResourceOptionFlags.None;
            ibufferDescription.SizeInBytes = (int)indexStream.Length;
            ibufferDescription.Usage = ResourceUsage.Immutable;
            
            indexBuffer = new Buffer(renderingDevice, indexStream, ibufferDescription);
            indexCount = (int)indexStream.Length / 2;
        }
Exemple #43
0
            //// RESOURCE MANAGEMENT
            //// maybe some of this can be moved to util class too?

            public static void InitDevice()
            {
                var description = new SwapChainDescription()
                {
                    BufferCount       = 1,
                    Usage             = Usage.RenderTargetOutput,
                    OutputHandle      = Data.Window.Handle,
                    IsWindowed        = true,
                    ModeDescription   = new ModeDescription(0, 0, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                    SampleDescription = new SampleDescription(1, 0),
                    Flags             = SwapChainFlags.AllowModeSwitch,
                    SwapEffect        = SwapEffect.Discard
                };

                Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, description, out Data.DX11Device, out Data.DX11SwapChain);
                Data.DX11Device.Factory.SetWindowAssociation(Data.Window.Handle, WindowAssociationFlags.IgnoreAll);
            }
Exemple #44
0
        public DxDeviceContext(IntPtr formHandle, Control renderAreaObject, bool fullscreen)
        {
            _isFullscreen = fullscreen;

            SwapChainDescription desc = new SwapChainDescription();

            if (fullscreen)
            {
                throw new ApplicationException("Not implemented yet");
            }
            else
            {
                FrameWidth  = renderAreaObject.Width;
                FrameHeight = renderAreaObject.Height;

                desc.BufferCount     = 1;
                desc.ModeDescription = new ModeDescription(FrameWidth,
                                                           FrameHeight,
                                                           new SlimDX.Rational(60, 1),
                                                           Format.R8G8B8A8_UNorm);
                desc.IsWindowed = true;
                desc.SwapEffect = SwapEffect.Discard;
            }

            desc.OutputHandle      = renderAreaObject.Handle;
            desc.SampleDescription = new SampleDescription(1, 0);
            desc.Usage             = Usage.RenderTargetOutput;

            Device    dev;
            SwapChain swapChain;

            Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, desc, out dev, out swapChain);
            Device    = dev;
            SwapChain = swapChain;
            Device.Factory.SetWindowAssociation(renderAreaObject.Handle, WindowAssociationFlags.IgnoreAll);

            _dInput = new DirectInput();
            CooperativeLevel cooLevel = CooperativeLevel.Foreground;

            cooLevel |= CooperativeLevel.Nonexclusive;
            _mouse    = new Mouse(_dInput);
            _mouse.SetCooperativeLevel(formHandle, cooLevel);

            _shaderByteCode = ShaderBytecode.CompileFromFile(GetFxFile(), "fx_5_0", ShaderFlags.None, EffectFlags.None);
            Effect          = new SlimDX.Direct3D11.Effect(Device, _shaderByteCode);
        }
Exemple #45
0
        private static void WriteData(SlimDX.Direct3D11.Device device, Texture2D texture, Stream destination)
        {
            var width  = texture.Description.Width;
            var height = texture.Description.Height;

            using (var copy = new Texture2D(device, new Texture2DDescription {
                SampleDescription = new SampleDescription(1, 0),
                Width = width,
                Height = height,
                ArraySize = texture.Description.ArraySize,
                MipLevels = texture.Description.MipLevels,
                Format = texture.Description.Format,
                Usage = ResourceUsage.Staging,
                BindFlags = BindFlags.None,
                CpuAccessFlags = CpuAccessFlags.Read
            })) {
                device.ImmediateContext.CopyResource(texture, copy);

                try {
                    var dataBox        = device.ImmediateContext.MapSubresource(copy, 0, MapMode.Read, SlimDX.Direct3D11.MapFlags.None);
                    var ddsData        = dataBox.Data;
                    var ddsDataRowSize = dataBox.RowPitch;

                    // scanline offsets from the beginning of the file
                    var scanlineDataSize = ValueSize * ChannelCount * width;
                    var channelsBytes    = new byte[scanlineDataSize];
                    var temporary        = new byte[16];

                    for (var i = 0; i < height; i++)
                    {
                        WriteInt(destination, i, scanlineDataSize);
                        CopyAll(ddsData, temporary, width, channelsBytes);
                        destination.Write(channelsBytes, 0, channelsBytes.Length);

                        var wentDownRow = ddsData.Position % ddsDataRowSize;
                        if (wentDownRow > 0)
                        {
                            ddsData.Seek(ddsDataRowSize - wentDownRow, SeekOrigin.Current);
                        }
                    }
                } finally {
                    device.ImmediateContext.UnmapSubresource(texture, 0);
                }
            }
        }
Exemple #46
0
        /// <summary>
        /// Get Device (could be temporary, could be not), set proper SampleDescription
        /// </summary>
        private Device InitializeDevice()
        {
            Debug.Assert(Initialized == false);

            var device = new Device(DriverType.Hardware, DeviceCreationFlags.None);

            if (device.FeatureLevel < FeatureLevel)
            {
                throw new Exception($"Direct3D Feature {FeatureLevel} unsupported");
            }

            if (UseMsaa)
            {
                SampleDescription = GetMsaaDescription(device);
            }

            return(device);
        }
Exemple #47
0
        /// <summary>
        /// 頂点バッファの格納
        /// </summary>
        /// <param name="device">GraphicsDevice</param>
        private void InitVertexBuffer(Dx11.Device device)
        {
            for (int i = 0; i < Cnv.meshSection.vtxList.VertexCount; i++)
            {
                Vector3 vtxPos = Cnv.meshSection.vtxList.vertex[i];
                Vector2 uvPos  = Cnv.meshSection.uvList.uvs[i];

                vtxPos += Position;

                Console.WriteLine("Model:" + OldPath + " -> InitVertexBuffer");
                Console.WriteLine("AddVertex [" + i + "] : x:" + vtxPos.X + ",y:" + vtxPos.Y + ",z:" + vtxPos.Z);
                Console.WriteLine("AddUv [" + i + "] : x:" + uvPos.X + ",y:" + uvPos.Y);

                vtxList.Add(MyDirectXHelper.CreateVertexPositionTexture(vtxPos, uvPos));
            }

            vertexBuffer = MyDirectXHelper.CreateVertexBuffer(device, vtxList.ToArray());
        }
Exemple #48
0
 /// <summary>
 /// Creates a new instance of the D3D11Controll class with the specified device and swapchain
 /// properties.
 /// </summary>
 /// <param name="type">
 /// The type of device to create.
 /// </param>
 /// <param name="flags">
 /// A list of runtime layers to enable.
 /// </param>
 /// <param name="featureLevels">
 /// A list of feature levels which determine the order of feature levels to attempt to create.
 /// </param>
 /// <param name="swapChainDescription">
 /// The properties to use for creating the swapchain.
 /// </param>
 /// <exception cref="Direct3D11Exception">
 /// The requested device could not be created. Use the ResultCode property to obtain the
 /// specific error condition.
 /// </exception>
 public D3D11Control(DriverType type, DeviceCreationFlags flags, FeatureLevel[] featureLevels,
                     SwapChainDescription?swapChainDescription) : base()
 {
     // Setup control styles for owner draw.
     SetStyle(ControlStyles.Opaque | ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint,
              true);
     DoubleBuffered     = false;
     AutoAdjustViewPort = true;
     designMode         = DesignMode || LicenseManager.UsageMode == LicenseUsageMode.Designtime;
     if (!designMode)
     {
         // Create the D3D11 device.
         device = new Device(type, flags, featureLevels);
         // Defer swapchain creation until the control's handle has been created.
         this.swapChainDescription = swapChainDescription;
     }
     InitializeComponent();
 }
Exemple #49
0
        public Mesh(Device device, DataStream vertices, PrimitiveTopology topology, int stride)
        {
            topology_ = topology;

            offset_    = 0;
            startVert_ = 0;
            stride_    = stride;
            vertCount_ = (int)vertices.Length / stride;

            vertices_ = new SlimDX.Direct3D11.Buffer(device, vertices, new BufferDescription()
            {
                BindFlags      = BindFlags.VertexBuffer,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags    = ResourceOptionFlags.None,
                SizeInBytes    = (int)vertices.Length,
                Usage          = ResourceUsage.Default
            });
        }
        public TextureTargetContext(RenderContext context, MatrixManager matrixManager, Size size, SampleDescription sampleDesc) : base(context)
        {
            HitChecker    = new TexturedBufferHitChecker(context, this);
            context.Timer = new MotionTimer(context);
            Device device = context.DeviceManager.Device;

            // サイズを設定(ターゲットは初期化しない)
            this.size = size;
            // マルチサンプルの設定(ターゲットも初期化する)
            this.SampleDesc = sampleDesc;

            // その他設定
            this.MatrixManager = matrixManager;
            this.WorldSpace    = new WorldSpace(context);
            fpsCounter         = new FPSCounter();
            SetViewport();
            HitChecker = new TexturedBufferHitChecker(Context, this);
        }
Exemple #51
0
        void DxInitDevice()
        {
            CurrentDevice = new Device(DriverType.Hardware, DeviceCreationFlags.None);
            if (CurrentDevice.FeatureLevel < FeatureLevel.Level_10_1)
            {
                throw new System.Exception("Direct3D Feature Level 10.1 unsupported");
            }

            _dx11Mode = CurrentDevice.FeatureLevel >= FeatureLevel.Level_11_0;

            var msaaQuality = CurrentDevice.CheckMultisampleQualityLevels(Format.R8G8B8A8_UNorm, 4);

            _sampleDesc = _dx11Mode ? new SampleDescription(1, 0) : new SampleDescription(4, msaaQuality - 1);

            Logging.Write("MSAA Quality: " + msaaQuality);

            _context = CurrentDevice.ImmediateContext;
        }
Exemple #52
0
            public Cursor(Device device, InputLayout lineLayout, EffectTechnique _tech)
            {
                this.device     = device;
                this.lineLayout = lineLayout;
                this._pass      = _tech.GetPassByIndex(0);

                var transDesc = new BlendStateDescription
                {
                    AlphaToCoverageEnable  = false,
                    IndependentBlendEnable = false
                };

                transDesc.RenderTargets[0].BlendEnable           = true;
                transDesc.RenderTargets[0].SourceBlend           = BlendOption.InverseDestinationColor;
                transDesc.RenderTargets[0].DestinationBlend      = BlendOption.DestinationColor;
                transDesc.RenderTargets[0].BlendOperation        = BlendOperation.Add;
                transDesc.RenderTargets[0].SourceBlendAlpha      = BlendOption.One;
                transDesc.RenderTargets[0].DestinationBlendAlpha = BlendOption.Zero;
                transDesc.RenderTargets[0].BlendOperationAlpha   = BlendOperation.Add;
                transDesc.RenderTargets[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;
                cursorBS = BlendState.FromDescription(device, transDesc);

                PositionColored[] cursorGeometry = new PositionColored[]
                {
                    new PositionColored(new Vector3(-1, 0, 0), Color.SkyBlue),
                    new PositionColored(new Vector3(1, 0, 0), Color.SkyBlue),

                    new PositionColored(new Vector3(0, -1, 0), Color.SkyBlue),
                    new PositionColored(new Vector3(0, 1, 0), Color.SkyBlue),

                    new PositionColored(new Vector3(0, 0, -1), Color.SkyBlue),
                    new PositionColored(new Vector3(0, 0, 1), Color.SkyBlue)
                };
                device.ImmediateContext.InputAssembler.InputLayout       = lineLayout;
                device.ImmediateContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.LineList;
                BufferDescription vbd = new BufferDescription(PositionColored.Stride * cursorGeometry.Length, ResourceUsage.Immutable, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);

                uint[]            indices            = new uint[] { 0, 1, 2, 3, 4, 5 };
                BufferDescription ibd                = new BufferDescription(sizeof(uint) * indices.Length, ResourceUsage.Immutable, BindFlags.IndexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);
                Buffer            cursorVertexBuffer = new Buffer(device, new DataStream(cursorGeometry, true, false), vbd);

                vertexBufferBinding = new VertexBufferBinding(cursorVertexBuffer, PositionColored.Stride, 0);
                IndexBuffer         = new Buffer(device, new DataStream(indices, false, false), ibd);
            }
        public DefaultRenderer(Device graphicsDevice, Camera camera, VoxelMeshContainer container)
        {
            this.graphicsDevice = graphicsDevice;
            this.camera = camera;
            this.container = container;

#if DEBUG
            shader = new Effect(graphicsDevice, ShaderPrecompiler.PrecompileOrLoad(@"Shaders\VoxelMesh.hlsl", "fx_5_0", ShaderFlags.Debug, EffectFlags.None));
#else
            shader = new Effect(graphicsDevice, ShaderPrecompiler.PrecompileOrLoad(@"Shaders\VoxelMesh.hlsl", "fx_5_0", ShaderFlags.None, EffectFlags.None));
#endif

            layout = new InputLayout(graphicsDevice, shader.GetTechniqueByIndex(0).GetPassByIndex(0).Description.Signature, new[]
			{
				new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0),
				new InputElement("NORMAL", 0, Format.R32G32B32_Float, 12, 0, InputClassification.PerVertexData, 0),
				new InputElement("AMBIENT", 0, Format.R32_Float, 24, 0, InputClassification.PerVertexData, 0)
			});
        }
        public DefaultRenderer(Device graphicsDevice, Camera camera, VoxelMeshContainer container)
        {
            this.graphicsDevice = graphicsDevice;
            this.camera         = camera;
            this.container      = container;

#if DEBUG
            shader = new Effect(graphicsDevice, ShaderPrecompiler.PrecompileOrLoad(@"Shaders\VoxelMesh.hlsl", "fx_5_0", ShaderFlags.Debug, EffectFlags.None));
#else
            shader = new Effect(graphicsDevice, ShaderPrecompiler.PrecompileOrLoad(@"Shaders\VoxelMesh.hlsl", "fx_5_0", ShaderFlags.None, EffectFlags.None));
#endif

            layout = new InputLayout(graphicsDevice, shader.GetTechniqueByIndex(0).GetPassByIndex(0).Description.Signature, new[]
            {
                new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0),
                new InputElement("NORMAL", 0, Format.R32G32B32_Float, 12, 0, InputClassification.PerVertexData, 0),
                new InputElement("AMBIENT", 0, Format.R32_Float, 24, 0, InputClassification.PerVertexData, 0)
            });
        }
        public ShadowMap(Device device, int width, int height)
        {
            _width  = width;
            _height = height;

            _viewport = new Viewport(0, 0, _width, _height, 0, 1.0f);

            var texDesc = new Texture2DDescription {
                Width             = _width,
                Height            = _height,
                MipLevels         = 1,
                ArraySize         = 1,
                Format            = Format.R24G8_Typeless,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = ResourceUsage.Default,
                BindFlags         = BindFlags.DepthStencil | BindFlags.ShaderResource,
                CpuAccessFlags    = CpuAccessFlags.None,
                OptionFlags       = ResourceOptionFlags.None
            };

            var depthMap = new Texture2D(device, texDesc);

            depthMap.DebugName = "shadowmap depthmap";
            var dsvDesc = new DepthStencilViewDescription {
                Flags     = DepthStencilViewFlags.None,
                Format    = Format.D24_UNorm_S8_UInt,
                Dimension = DepthStencilViewDimension.Texture2D,
                MipSlice  = 0
            };

            _depthMapDSV = new DepthStencilView(device, depthMap, dsvDesc);

            var srvDesc = new ShaderResourceViewDescription {
                Format          = Format.R24_UNorm_X8_Typeless,
                Dimension       = ShaderResourceViewDimension.Texture2D,
                MipLevels       = texDesc.MipLevels,
                MostDetailedMip = 0
            };

            DepthMapSRV = new ShaderResourceView(device, depthMap, srvDesc);

            Util.ReleaseCom(ref depthMap);
        }
Exemple #56
0
        public BlobRenderable(string effectFilename, string techniqueName, SlimDX.Direct3D11.Device device, Matrix world, Scene scene, SamplerState sampler, Vector2 screenSize, float scale)
        {
            mesh_ = Mesh.MakeQuadMesh(device, scale);
            var effect = scene.LoadEffect(effectFilename);

            technique_ = effect.GetTechniqueByName(techniqueName);
            layout_    = new InputLayout(device, technique_.GetPassByIndex(0).Description.Signature, new[] {
                new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
                new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0)
            });
            world_  = world;
            effect_ = effect;

            m_screenSize = screenSize;

            m_scale = new Vector2(1.0f, 1.0f);

            IsVisible = true; // Visible by default
        }
Exemple #57
0
        private void LoadAllTileTextures()
        {
            Device           device   = t.Device;
            List <Texture2D> textures = new List <Texture2D>();
            List <string>    allFiles = Directory.GetFiles("01.Frontend/Textures/Blocks/", "*.png").ToList();

            allFiles.AddRange(Directory.GetFiles("01.Frontend/Textures/Items/", "*.png"));
            allFiles.AddRange(Directory.GetFiles("01.Frontend/Textures/Gui/", "*.png"));

            ImageLoadInformation info = new ImageLoadInformation()
            {
                BindFlags      = BindFlags.ShaderResource,
                CpuAccessFlags = CpuAccessFlags.None,
                FilterFlags    = FilterFlags.None,
                Format         = SlimDX.DXGI.Format.R8G8B8A8_UNorm,
                MipFilterFlags = FilterFlags.Point,
                OptionFlags    = ResourceOptionFlags.None,
                Usage          = ResourceUsage.Default,
                MipLevels      = 2
            };

            foreach (string filename in allFiles)
            {
                textures.Add(Texture2D.FromFile(device, filename, info));
            }

            var textureArrayDescription = textures[0].Description;

            textureArrayDescription.ArraySize = textures.Count;
            var textureArray = new Texture2D(device, textureArrayDescription);
            var mipLevels    = textureArrayDescription.MipLevels;

            for (int j = 0; j < textures.Count; j++)
            {
                indexMap.Add(Path.GetFileNameWithoutExtension(allFiles[j]), j);
                for (var i = 0; i < mipLevels; i++)
                {
                    // for both textures
                    device.ImmediateContext.CopySubresourceRegion(textures[j], i, textureArray, mipLevels * j + i, 0, 0, 0);
                }
            }
            View = new ShaderResourceView(device, textureArray);
        }
        public RenderTarget(Device device, DeviceContext context, int w, int h, int samplecount, string name = "rt")
        {
            // Store parameters
            this.device = device;
            this.context = context;
            this.samplecount = samplecount;
            this.name = name;
            Width = w;
            Height = h;

            // Setup viewport
            Viewport = new Viewport(0.0f, 0.0f, w, h);

            // Setup components
            components = new List<Component>();

            // Setup defaults
            ClearColour = new Color4(1.0f, 0.0f, 0.0f, 0.0f);
        }
        // Static functions
        static public GPUBufferObject CreateBuffer(Device device, int size)
        {
            GPUBufferObject newBuffer = new GPUBufferObject();

            // Variables
            newBuffer.m_Size = size;

            BindFlags bindFlags = BindFlags.ShaderResource | BindFlags.UnorderedAccess;

            BufferDescription description = new BufferDescription(size * 4, ResourceUsage.Default, bindFlags, CpuAccessFlags.None, ResourceOptionFlags.StructuredBuffer, 4);

            newBuffer.m_BufferObject = new Buffer(device, description);

            ShaderResourceViewDescription srvViewDesc = new ShaderResourceViewDescription
            {
                ArraySize       = 0,
                ElementCount    = size,
                ElementWidth    = size,
                Format          = Format.Unknown,
                Dimension       = ShaderResourceViewDimension.Buffer,
                Flags           = 0,
                FirstArraySlice = 0,
                MostDetailedMip = 0,
                MipLevels       = 0
            };

            newBuffer.m_ShaderResourceView = new ShaderResourceView(device, newBuffer.m_BufferObject, srvViewDesc);


            UnorderedAccessViewDescription uavDesc = new UnorderedAccessViewDescription
            {
                ArraySize    = 0,
                Dimension    = UnorderedAccessViewDimension.Buffer,
                ElementCount = size,
                Flags        = UnorderedAccessViewBufferFlags.None,
                Format       = Format.Unknown,
                MipSlice     = 0
            };

            newBuffer.m_UnorderedAccessView = new UnorderedAccessView(device, newBuffer.m_BufferObject, uavDesc);

            return(newBuffer);
        }
        public MergeSegmentationRenderingStrategy(SlimDX.Direct3D11.Device device, DeviceContext deviceContext, TileManager tileManager)
        {
            mTileManager   = tileManager;
            mDebugRenderer = new DebugRenderer(device);

            mEffect = EffectUtil.CompileEffect(device, @"Shaders\MergeRenderer2D.fx");

            var positionTexcoordInputElements = new[]
            {
                new InputElement("POSITION", 0, POSITION_FORMAT, POSITION_SLOT),
                new InputElement("TEXCOORD", 0, TEXCOORD_FORMAT, TEXCOORD_SLOT)
            };

            EffectTechnique effectTechnique = mEffect.GetTechniqueByName("TileManager2D");

            mPass = effectTechnique.GetPassByName("TileManager2D");

            mInputLayout = new InputLayout(device, mPass.Description.Signature, positionTexcoordInputElements);

            mPositionVertexBuffer = new Buffer(device,
                                               null,
                                               QUAD_NUM_VERTICES * POSITION_NUM_COMPONENTS_PER_VERTEX * POSITION_NUM_BYTES_PER_COMPONENT,
                                               ResourceUsage.Dynamic,
                                               BindFlags.VertexBuffer,
                                               CpuAccessFlags.Write,
                                               ResourceOptionFlags.None,
                                               0);

            mTexCoordVertexBuffer = new Buffer(device,
                                               null,
                                               QUAD_NUM_VERTICES * TEXCOORD_NUM_COMPONENTS_PER_VERTEX * TEXCOORD_NUM_BYTES_PER_COMPONENT,
                                               ResourceUsage.Dynamic,
                                               BindFlags.VertexBuffer,
                                               CpuAccessFlags.Write,
                                               ResourceOptionFlags.None,
                                               0);

            //bool result;
            //mTinyTextContext = new Context( device, deviceContext, Constants.MAX_NUM_TINY_TEXT_CHARACTERS, out result );
            //Release.Assert( result );

            mStopwatch.Start();
        }