示例#1
0
        /// <summary>
        /// Initializes a new instance of <see cref="GraphicsOutput" />.
        /// </summary>
        /// <param name="adapter">The adapter.</param>
        /// <param name="output">The DXGI <see cref="Output" /> counterpart of this instance.</param>
        /// <exception cref="System.ArgumentNullException">output</exception>
        /// <exception cref="ArgumentOutOfRangeException">Is thrown when <paramref name="outputOrdinal" /> is less than zero.</exception>
        /// <exception cref="ArgumentNullException">Is thrown when <paramref name="output" /> is null.</exception>
        internal GraphicsOutput(GraphicsAdapter adapter, Output output)
        {
            if(adapter == null) throw new ArgumentNullException("adapter");
            if (output == null) throw new ArgumentNullException("output");

            this.adapter = adapter;
            this.output = ToDispose(output);
            outputDescription = output.Description;
        }
示例#2
0
        /// <summary>
        /// Initializes a new instance of <see cref="GraphicsOutput"/>.
        /// </summary>
        /// <param name="output">The DXGI <see cref="Output"/> counterpart of this instance.</param>
        /// <exception cref="ArgumentOutOfRangeException">Is thrown when <paramref name="outputOrdinal"/> is less than zero.</exception>
        /// <exception cref="ArgumentNullException">Is thrown when <paramref name="output"/> is null.</exception>
        internal GraphicsOutput(Output output)
        {
            if (output == null) throw new ArgumentNullException("output");

            this.output = ToDispose(output);
            outputDescription = output.Description;

            InitializeSupportedDisplayModes();

            InitializeCurrentDisplayMode();
        }
        /// <summary>
        /// Initializes a new instance of <see cref="GraphicsOutput" />.
        /// </summary>
        /// <param name="adapter">The adapter.</param>
        /// <param name="outputIndex">Index of the output.</param>
        /// <exception cref="System.ArgumentNullException">output</exception>
        /// <exception cref="ArgumentOutOfRangeException">output</exception>
        internal GraphicsOutput(GraphicsAdapter adapter, int outputIndex)
        {
            if (adapter == null) throw new ArgumentNullException("adapter");

            this.outputIndex = outputIndex;
            this.adapter = adapter;
            this.output = adapter.NativeAdapter.GetOutput(outputIndex).DisposeBy(this);
            outputDescription = output.Description;

            unsafe
            {
                var rectangle = outputDescription.DesktopBounds;
                desktopBounds = *(Rectangle*)&rectangle;
            }
        }
示例#4
0
        internal OpenGLSwapchainFramebuffer(
            uint width, uint height,
            PixelFormat colorFormat,
            PixelFormat?depthFormat,
            bool disableSrgbConversion)
        {
            _depthFormat = depthFormat;
            // This is wrong, but it's not really used.
            OutputAttachmentDescription?depthDesc = _depthFormat != null
                ? new OutputAttachmentDescription(_depthFormat.Value)
                : (OutputAttachmentDescription?)null;

            OutputDescription = new OutputDescription(
                depthDesc,
                new OutputAttachmentDescription(colorFormat));

            _colorTexture = new OpenGLPlaceholderTexture(
                width,
                height,
                colorFormat,
                TextureUsage.RenderTarget,
                TextureSampleCount.Count1);
            _colorTargets = new[] { new FramebufferAttachment(_colorTexture, 0) };

            if (_depthFormat != null)
            {
                _depthTexture = new OpenGLPlaceholderTexture(
                    width,
                    height,
                    depthFormat.Value,
                    TextureUsage.DepthStencil,
                    TextureSampleCount.Count1);
                _depthTarget = new FramebufferAttachment(_depthTexture, 0);
            }

            OutputDescription = OutputDescription.CreateFromFramebuffer(this);

            DisableSrgbConversion = disableSrgbConversion;
        }
示例#5
0
        /// <summary>
        /// Constructs a new ImGuiController.
        /// </summary>
        public ImGuiController(GraphicsDevice gd, OutputDescription outputDescription, int width, int height)
        {
            _gd           = gd;
            _windowWidth  = width;
            _windowHeight = height;

            IntPtr context = ImGui.CreateContext();

            ImGui.SetCurrentContext(context);
            var fonts = ImGui.GetIO().Fonts;

            ImGui.GetIO().Fonts.AddFontDefault();
            ImGui.GetIO().BackendFlags |= ImGuiBackendFlags.RendererHasVtxOffset;

            CreateDeviceResources(gd, outputDescription);
            SetKeyMappings();

            SetPerFrameImGuiData(1f / 60f);

            ImGui.NewFrame();
            _frameBegun = true;
        }
        public void WebGetActivity_Equals_Given_Same_OutputDescription_IsEqual()
        {
            //---------------Set up test pack-------------------
            var uniqueId = Guid.NewGuid().ToString();
            var outDescr = new OutputDescription();
            var webGet   = new WebGetActivity()
            {
                UniqueID = uniqueId, OutputDescription = outDescr
            };
            var webGet1 = new WebGetActivity()
            {
                UniqueID = uniqueId, OutputDescription = outDescr
            };

            //---------------Assert Precondition----------------
            Assert.IsNotNull(webGet);
            //---------------Execute Test ----------------------
            var @equals = webGet.Equals(webGet1);

            //---------------Test Result -----------------------
            Assert.IsTrue(@equals);
        }
        /// <summary>
        /// Duplicates the output of the specified monitor on the specified graphics adapter.
        /// </summary>
        /// <param name="whichGraphicsCardAdapter">The adapter which contains the desired outputs.</param>
        /// <param name="whichOutputDevice">The output device to duplicate (i.e. monitor). Begins with zero, which seems to correspond to the primary monitor.</param>
        public DesktopDuplicator(int whichGraphicsCardAdapter, int whichOutputDevice)
        {
            //SharpDX.Configuration.EnableObjectTracking = true;
            this.mWhichOutputDevice = whichOutputDevice;
            Adapter1 adapter = null;

            try
            {
                adapter = new Factory1().GetAdapter1(whichGraphicsCardAdapter);
            }
            catch (SharpDXException)
            {
                throw new DesktopDuplicationException("Could not find the specified graphics card adapter.");
            }
            this.mDevice = new Device(adapter);
            Output output = null;

            try
            {
                output = adapter.GetOutput(whichOutputDevice);
            }
            catch (SharpDXException)
            {
                throw new DesktopDuplicationException("Could not find the specified output device.");
            }
            var output1 = output.QueryInterface <Output1>();

            this.mOutputDesc  = output.Description;
            this.mTextureDesc = new Texture2DDescription()
            {
                CpuAccessFlags    = CpuAccessFlags.Read,
                BindFlags         = BindFlags.None,
                Format            = Format.B8G8R8A8_UNorm,
                Width             = this.mOutputDesc.DesktopBounds.GetWidth(),
                Height            = this.mOutputDesc.DesktopBounds.GetHeight(),
                OptionFlags       = ResourceOptionFlags.None,
                MipLevels         = 1,
                ArraySize         = 1,
                SampleDescription = { Count = 1, Quality = 0 },
                Usage             = ResourceUsage.Staging
            };

            try
            {
                this.mDeskDupl = output1.DuplicateOutput(mDevice);
            }
            catch (SharpDXException ex)
            {
                if (ex.ResultCode.Code == SharpDX.DXGI.ResultCode.NotCurrentlyAvailable.Result.Code)
                {
                    output.Dispose();
                    output1.Dispose();
                    adapter.Dispose();


                    throw new DesktopDuplicationException("There is already the maximum number of applications using the Desktop Duplication API running, please close one of the applications and try again.");
                }
            }
            output.Dispose();
            output1.Dispose();
            adapter.Dispose();
        }
示例#8
0
 public Pipeline CreateNonDepthTestOverrideBlendPipeline(ResourceLayout[] resourceLayouts, ShaderSetDescription shaderSetDescription, OutputDescription outputDescription)
 {
     return(CreateAPipeline(resourceLayouts, shaderSetDescription, outputDescription, BlendStateDescription.SingleOverrideBlend, false));
 }
示例#9
0
        public AssimpMesh(GraphicsDevice gd, OutputDescription outputs, string meshPath, string texturePath)
        {
            _gd = gd;
            ResourceFactory factory = gd.ResourceFactory;

            Shader[] shaders = factory.CreateFromSpirv(
                new ShaderDescription(ShaderStages.Vertex, Encoding.ASCII.GetBytes(vertexGlsl), "main"),
                new ShaderDescription(ShaderStages.Fragment, Encoding.ASCII.GetBytes(fragmentGlsl), "main"));
            _disposables.Add(shaders[0]);
            _disposables.Add(shaders[1]);

            ResourceLayout rl = factory.CreateResourceLayout(new ResourceLayoutDescription(
                                                                 new ResourceLayoutElementDescription("WVP", ResourceKind.UniformBuffer, ShaderStages.Vertex),
                                                                 new ResourceLayoutElementDescription("Input", ResourceKind.TextureReadOnly, ShaderStages.Fragment),
                                                                 new ResourceLayoutElementDescription("InputSampler", ResourceKind.Sampler, ShaderStages.Fragment)));

            _disposables.Add(rl);

            VertexLayoutDescription positionLayoutDesc = new VertexLayoutDescription(
                new VertexElementDescription[]
            {
                new VertexElementDescription("Position", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float3),
            });

            VertexLayoutDescription texCoordLayoutDesc = new VertexLayoutDescription(
                new VertexElementDescription[]
            {
                new VertexElementDescription("UV", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2),
            });

            _pipeline = factory.CreateGraphicsPipeline(new GraphicsPipelineDescription(
                                                           BlendStateDescription.SingleOverrideBlend,
                                                           DepthStencilStateDescription.DepthOnlyLessEqual,
                                                           RasterizerStateDescription.CullNone,
                                                           PrimitiveTopology.TriangleList,
                                                           new ShaderSetDescription(new[] { positionLayoutDesc, texCoordLayoutDesc }, new Shader[] { shaders[0], shaders[1] }),
                                                           rl,
                                                           outputs));
            _disposables.Add(_pipeline);

            _wvpBuffer = factory.CreateBuffer(new BufferDescription(64 * 3, BufferUsage.UniformBuffer | BufferUsage.Dynamic));
            _disposables.Add(_wvpBuffer);

            _texture = new ImageSharpTexture(texturePath, true, true).CreateDeviceTexture(gd, factory);
            _view    = factory.CreateTextureView(_texture);
            _disposables.Add(_texture);
            _disposables.Add(_view);

            _rs = factory.CreateResourceSet(new ResourceSetDescription(rl, _wvpBuffer, _view, gd.Aniso4xSampler));
            _disposables.Add(_rs);

            AssimpContext ac    = new AssimpContext();
            Scene         scene = ac.ImportFile(meshPath);

            foreach (Mesh mesh in scene.Meshes)
            {
                DeviceBuffer positions = CreateDeviceBuffer(mesh.Vertices, BufferUsage.VertexBuffer);
                DeviceBuffer texCoords = CreateDeviceBuffer(
                    mesh.TextureCoordinateChannels[0].Select(v3 => new Vector2(v3.X, v3.Y)).ToArray(),
                    BufferUsage.VertexBuffer);
                DeviceBuffer indices = CreateDeviceBuffer(mesh.GetUnsignedIndices(), BufferUsage.IndexBuffer);

                _meshPieces.Add(new MeshPiece(positions, texCoords, indices));
            }
        }
示例#10
0
        public ScreenInfo Initialize(ComponentOptions componentOptions)
        {
            var options = componentOptions.To <DesktopDuplicationOptions>();
            var monitor = options.Monitor.Value;

            Adapter1 adapter;

            try
            {
                using (var factory = new Factory1())
                    adapter = GetBestAdapter(factory);
            }
            catch (SharpDXException e)
            {
                throw new InvalidOperationException("Could not find the specified graphics card adapter.", e);
            }

            Output output;

            using (adapter)
            {
                _captureDevice = new Device(adapter);

                try
                {
                    output = adapter.GetOutput(monitor);
                }
                catch (Exception e)
                {
                    throw new InvalidOperationException("Could not find the specified output device.", e);
                }
            }

            using (output)
                using (var output1 = output.QueryInterface <Output1>())
                {
                    _outputDesc  = output.Description;
                    _textureDesc = new Texture2DDescription
                    {
                        CpuAccessFlags    = CpuAccessFlags.Read,
                        BindFlags         = BindFlags.None,
                        Format            = Format.B8G8R8A8_UNorm,
                        Width             = GetWidth(_outputDesc.DesktopBounds),
                        Height            = GetHeight(_outputDesc.DesktopBounds),
                        OptionFlags       = ResourceOptionFlags.None,
                        MipLevels         = 1,
                        ArraySize         = 1,
                        SampleDescription = { Count = 1, Quality = 0 },
                        Usage             = ResourceUsage.Staging
                    };

                    try
                    {
                        _deskDupl = output1.DuplicateOutput(_captureDevice);
                    }
                    catch (SharpDXException ex) when(ex.ResultCode.Code == ResultCode.NotCurrentlyAvailable.Result.Code)
                    {
                        throw new InvalidOperationException(
                                  "There is already the maximum number of applications using the Desktop Duplication API running, please close one of the applications and try again.");
                    }

                    return(new ScreenInfo(_textureDesc.Width, _textureDesc.Height));
                }
        }
示例#11
0
 private static extern Result FMOD_System_RegisterOutput(IntPtr system, ref OutputDescription description,
                                                         out uint handle);
 public DuplicationInfo(OutputDescription desc, OutputDuplication duplication)
 {
     OutputDesc  = desc;
     Duplication = duplication;
 }
示例#13
0
        /// <summary>
        /// Duplicates the output of the specified monitor on the specified graphics adapter.
        /// </summary>
        /// <param name="whichGraphicsCardAdapter">The adapter which contains the desired outputs.</param>
        /// <param name="whichOutputDevice">The output device to duplicate (i.e. monitor). Begins with zero, which seems to correspond to the primary monitor.</param>
        public DesktopDuplicator(int whichGraphicsCardAdapter, int whichOutputDevice)
        {
            this.mWhichOutputDevice = whichOutputDevice;
            Adapter1 adapter = null;

            try
            {
                adapter = new Factory1().GetAdapter1(whichGraphicsCardAdapter);
            }
            catch (SharpDXException)
            {
                throw new DesktopDuplicationException("Could not find the specified graphics card adapter.");
            }
            this.mDevice = new Device(adapter);
            Output output = null;

            try
            {
                output = adapter.GetOutput(whichOutputDevice);
            }
            catch (SharpDXException)
            {
                throw new DesktopDuplicationException("Could not find the specified output device.");
            }
            var output1 = output.QueryInterface <Output1>();

            this.mOutputDesc  = output.Description;
            this.mTextureDesc = new Texture2DDescription()
            {
                CpuAccessFlags    = CpuAccessFlags.Read,
                BindFlags         = BindFlags.None,
                Format            = Format.B8G8R8A8_UNorm,
                Width             = this.mOutputDesc.DesktopBounds.Width,
                Height            = this.mOutputDesc.DesktopBounds.Height,
                OptionFlags       = ResourceOptionFlags.None,
                MipLevels         = 1,
                ArraySize         = 1,
                SampleDescription = { Count = 1, Quality = 0 },
                Usage             = ResourceUsage.Staging
            };

            try
            {
                this.mDeskDupl = output1.DuplicateOutput(mDevice);
            }
            catch (SharpDXException ex)
            {
                if (ex.ResultCode.Code == SharpDX.DXGI.ResultCode.NotCurrentlyAvailable.Result.Code)
                {
                    throw new DesktopDuplicationException("There is already the maximum number of applications using the Desktop Duplication API running, please close one of the applications and try again.");
                }
            }

            /*
             * var t = new Thread(() =>
             * {
             *  Action Allocate1K = () =>
             *  {
             *      for (var i = 0; i < 1500; i++)
             *      {
             *          var newBitmap =
             *          new System.Drawing.Bitmap(1920, 1200, PixelFormat.Format32bppRgb);
             *
             *          _allocatedBitmaps.Enqueue(newBitmap);
             *
             *          if (i % 10 == 0) Thread.Sleep(1);
             *      }
             *  };
             *
             *  while (true)
             *  {
             *      if (_allocatedBitmaps.Count < 500)
             *      {
             *          Allocate1K();
             *      }
             *      else
             *      {
             *          Thread.Sleep(1000);
             *      }
             *  }
             * });
             * t.Priority = ThreadPriority.Lowest;
             * t.Start();
             */
        }
示例#14
0
        /// <summary>
        /// Constructs a new ImGuiController.
        /// </summary>
        public ImGuiController(GraphicsDevice gd, OutputDescription outputDescription, int width, int height)
        {
            _gd           = gd;
            _windowWidth  = width;
            _windowHeight = height;

            Context = ImGui.CreateContext();
            ImGui.SetCurrentContext(Context);

            ImGui.GetIO().Fonts.AddFontDefault();

            var arial   = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "arial.ttf");
            var arialbd = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "arialbd.ttf");

            var cfg = new ImFontConfig
            {
                FontDataOwnedByAtlas = 1,
                OversampleH          = 5,
                OversampleV          = 1,
                PixelSnapH           = 0,
                GlyphMinAdvanceX     = 0,
                GlyphMaxAdvanceX     = float.MaxValue,
                RasterizerMultiply   = 1.2f
            };

            if (File.Exists(arial))
            {
                unsafe
                {
                    DefaultFont = ImGui.GetIO().Fonts.AddFontFromFileTTF(arial, 14, new ImFontConfigPtr(&cfg));
                    LargeFont   = ImGui.GetIO().Fonts.AddFontFromFileTTF(arial, 24, new ImFontConfigPtr(&cfg));
                }
            }
            else
            {
                DefaultFont = null;
                LargeFont   = null;
            }

            if (File.Exists(arialbd))
            {
                unsafe
                {
                    BoldFont = ImGui.GetIO().Fonts.AddFontFromFileTTF(arialbd, 14, new ImFontConfigPtr(&cfg));
                }
            }
            else
            {
                BoldFont = null;
            }

            var style = ImGui.GetStyle();

            style.WindowRounding   = 0;
            style.WindowPadding    = Vector2.Zero;
            style.WindowBorderSize = 0;
            style.AntiAliasedFill  = false;
            style.AntiAliasedLines = false;

            CreateDeviceResources(gd, outputDescription);

            SetPerFrameImGuiData(1f / 60f);

            ImGui.NewFrame();
            _frameBegun = true;
        }
        /// <summary>
        /// Duplicates the output of the specified monitor on the specified graphics adapter.
        /// </summary>
        /// <param name="whichGraphicsCardAdapter">The adapter which contains the desired outputs.</param>
        /// <param name="whichOutputDevice">The output device to duplicate (i.e. monitor). Begins with zero, which seems to correspond to the primary monitor.</param>
        public DesktopDuplicator(int whichGraphicsCardAdapter, int whichOutputDevice)
        {
            this.mWhichOutputDevice = whichOutputDevice;
            Adapter1 adapter = null;
            try
            {
                adapter = new Factory1().GetAdapter1(whichGraphicsCardAdapter);
            }
            catch (SharpDXException)
            {
                throw new DesktopDuplicationException("Could not find the specified graphics card adapter.");
            }
            this.mDevice = new Device(adapter);
            Output output = null;
            try
            {
                output = adapter.GetOutput(whichOutputDevice);
            }
            catch (SharpDXException)
            {
                throw new DesktopDuplicationException("Could not find the specified output device.");
            }
            var output1 = output.QueryInterface<Output1>();
            this.mOutputDesc = output.Description;
            this.mTextureDesc = new Texture2DDescription()
            {
                CpuAccessFlags = CpuAccessFlags.Read,
                BindFlags = BindFlags.None,
                Format = Format.B8G8R8A8_UNorm,
                Width = this.mOutputDesc.DesktopBounds.Width,
                Height = this.mOutputDesc.DesktopBounds.Height,
                OptionFlags = ResourceOptionFlags.None,
                MipLevels = 1,
                ArraySize = 1,
                SampleDescription = { Count = 1, Quality = 0 },
                Usage = ResourceUsage.Staging
            };

            try
            {
                this.mDeskDupl = output1.DuplicateOutput(mDevice);
            }
            catch (SharpDXException ex)
            {
                if (ex.ResultCode.Code == SharpDX.DXGI.ResultCode.NotCurrentlyAvailable.Result.Code)
                {
                    throw new DesktopDuplicationException("There is already the maximum number of applications using the Desktop Duplication API running, please close one of the applications and try again.");
                }
            }
        }
示例#16
0
        public VkPipeline(VkGraphicsDevice gd, ref PipelineDescription description)
        {
            _gd = gd;

            VkGraphicsPipelineCreateInfo pipelineCI = VkGraphicsPipelineCreateInfo.New();

            // Blend State
            VkPipelineColorBlendStateCreateInfo blendStateCI = VkPipelineColorBlendStateCreateInfo.New();
            int attachmentsCount = description.BlendState.AttachmentStates.Length;
            VkPipelineColorBlendAttachmentState *attachmentsPtr
                = stackalloc VkPipelineColorBlendAttachmentState[attachmentsCount];

            for (int i = 0; i < attachmentsCount; i++)
            {
                BlendAttachmentDescription          vdDesc          = description.BlendState.AttachmentStates[i];
                VkPipelineColorBlendAttachmentState attachmentState = new VkPipelineColorBlendAttachmentState();
                attachmentState.srcColorBlendFactor = VkFormats.VdToVkBlendFactor(vdDesc.SourceColorFactor);
                attachmentState.dstColorBlendFactor = VkFormats.VdToVkBlendFactor(vdDesc.DestinationColorFactor);
                attachmentState.colorBlendOp        = VkFormats.VdToVkBlendOp(vdDesc.ColorFunction);
                attachmentState.srcAlphaBlendFactor = VkFormats.VdToVkBlendFactor(vdDesc.SourceAlphaFactor);
                attachmentState.dstAlphaBlendFactor = VkFormats.VdToVkBlendFactor(vdDesc.DestinationAlphaFactor);
                attachmentState.alphaBlendOp        = VkFormats.VdToVkBlendOp(vdDesc.AlphaFunction);
                attachmentState.blendEnable         = vdDesc.BlendEnabled;
                attachmentState.colorWriteMask      = VkColorComponentFlags.R | VkColorComponentFlags.G | VkColorComponentFlags.B | VkColorComponentFlags.A;
                attachmentsPtr[i] = attachmentState;
            }

            blendStateCI.attachmentCount = (uint)attachmentsCount;
            blendStateCI.pAttachments    = attachmentsPtr;
            RgbaFloat blendFactor = description.BlendState.BlendFactor;

            blendStateCI.blendConstants_0 = blendFactor.R;
            blendStateCI.blendConstants_1 = blendFactor.G;
            blendStateCI.blendConstants_2 = blendFactor.B;
            blendStateCI.blendConstants_3 = blendFactor.A;

            pipelineCI.pColorBlendState = &blendStateCI;

            // Rasterizer State
            RasterizerStateDescription             rsDesc = description.RasterizerState;
            VkPipelineRasterizationStateCreateInfo rsCI   = VkPipelineRasterizationStateCreateInfo.New();

            rsCI.cullMode         = VkFormats.VdToVkCullMode(rsDesc.CullMode);
            rsCI.polygonMode      = VkFormats.VdToVkPolygonMode(rsDesc.FillMode);
            rsCI.depthClampEnable = !rsDesc.DepthClipEnabled;
            rsCI.frontFace        = VkFrontFace.Clockwise;
            rsCI.lineWidth        = 1f;

            pipelineCI.pRasterizationState = &rsCI;

            // Dynamic State
            VkPipelineDynamicStateCreateInfo dynamicStateCI = VkPipelineDynamicStateCreateInfo.New();
            VkDynamicState *dynamicStates = stackalloc VkDynamicState[2];

            dynamicStates[0] = VkDynamicState.Viewport;
            dynamicStates[1] = VkDynamicState.Scissor;
            dynamicStateCI.dynamicStateCount = 2;
            dynamicStateCI.pDynamicStates    = dynamicStates;

            pipelineCI.pDynamicState = &dynamicStateCI;

            // Depth Stencil State
            DepthStencilStateDescription          vdDssDesc = description.DepthStencilState;
            VkPipelineDepthStencilStateCreateInfo dssCI     = VkPipelineDepthStencilStateCreateInfo.New();

            dssCI.depthWriteEnable = vdDssDesc.DepthWriteEnabled;
            dssCI.depthTestEnable  = vdDssDesc.DepthTestEnabled;
            dssCI.depthCompareOp   = VkFormats.VdToVkCompareOp(vdDssDesc.ComparisonKind);

            pipelineCI.pDepthStencilState = &dssCI;

            // Multisample
            VkPipelineMultisampleStateCreateInfo multisampleCI = VkPipelineMultisampleStateCreateInfo.New();

            multisampleCI.rasterizationSamples = VkSampleCountFlags.Count1;

            pipelineCI.pMultisampleState = &multisampleCI;

            // Input Assembly
            VkPipelineInputAssemblyStateCreateInfo inputAssemblyCI = VkPipelineInputAssemblyStateCreateInfo.New();

            inputAssemblyCI.topology = VkFormats.VdToVkPrimitiveTopology(description.PrimitiveTopology);

            pipelineCI.pInputAssemblyState = &inputAssemblyCI;

            // Vertex Input State
            VkPipelineVertexInputStateCreateInfo vertexInputCI = VkPipelineVertexInputStateCreateInfo.New();

            VertexLayoutDescription[] inputDescriptions = description.ShaderSet.VertexLayouts;
            uint bindingCount   = (uint)inputDescriptions.Length;
            uint attributeCount = 0;

            for (int i = 0; i < inputDescriptions.Length; i++)
            {
                attributeCount += (uint)inputDescriptions[i].Elements.Length;
            }
            VkVertexInputBindingDescription *  bindingDescs   = stackalloc VkVertexInputBindingDescription[(int)bindingCount];
            VkVertexInputAttributeDescription *attributeDescs = stackalloc VkVertexInputAttributeDescription[(int)attributeCount];

            int targetIndex    = 0;
            int targetLocation = 0;

            for (int binding = 0; binding < inputDescriptions.Length; binding++)
            {
                VertexLayoutDescription inputDesc = inputDescriptions[binding];
                bindingDescs[targetIndex] = new VkVertexInputBindingDescription()
                {
                    binding   = (uint)binding,
                    inputRate = (inputDesc.Elements[0].InstanceStepRate != 0) ? VkVertexInputRate.Instance : VkVertexInputRate.Vertex,
                    stride    = inputDesc.Stride
                };

                uint currentOffset = 0;
                for (int location = 0; location < inputDesc.Elements.Length; location++)
                {
                    VertexElementDescription inputElement = inputDesc.Elements[location];

                    attributeDescs[targetIndex] = new VkVertexInputAttributeDescription()
                    {
                        format   = VkFormats.VdToVkVertexElementFormat(inputElement.Format),
                        binding  = (uint)binding,
                        location = (uint)(targetLocation + location),
                        offset   = currentOffset
                    };

                    targetIndex   += 1;
                    currentOffset += FormatHelpers.GetSizeInBytes(inputElement.Format);
                }

                targetLocation += inputDesc.Elements.Length;
            }

            vertexInputCI.vertexBindingDescriptionCount   = bindingCount;
            vertexInputCI.pVertexBindingDescriptions      = bindingDescs;
            vertexInputCI.vertexAttributeDescriptionCount = attributeCount;
            vertexInputCI.pVertexAttributeDescriptions    = attributeDescs;

            pipelineCI.pVertexInputState = &vertexInputCI;

            // Shader Stage
            ShaderStageDescription[] stageDescs = description.ShaderSet.ShaderStages;
            StackList <VkPipelineShaderStageCreateInfo> stages = new StackList <VkPipelineShaderStageCreateInfo>();

            foreach (ShaderStageDescription stageDesc in stageDescs)
            {
                VkShader vkShader = Util.AssertSubtype <Shader, VkShader>(stageDesc.Shader);
                VkPipelineShaderStageCreateInfo stageCI = VkPipelineShaderStageCreateInfo.New();
                stageCI.module = vkShader.ShaderModule;
                stageCI.stage  = VkFormats.VdToVkShaderStages(stageDesc.Stage);
                stageCI.pName  = CommonStrings.main; // Meh
                stages.Add(stageCI);
            }

            pipelineCI.stageCount = stages.Count;
            pipelineCI.pStages    = (VkPipelineShaderStageCreateInfo *)stages.Data;

            // ViewportState
            VkPipelineViewportStateCreateInfo viewportStateCI = VkPipelineViewportStateCreateInfo.New();

            viewportStateCI.viewportCount = 1;
            viewportStateCI.scissorCount  = 1;

            pipelineCI.pViewportState = &viewportStateCI;

            // Pipeline Layout
            ResourceLayout[]           resourceLayouts  = description.ResourceLayouts;
            VkPipelineLayoutCreateInfo pipelineLayoutCI = VkPipelineLayoutCreateInfo.New();

            pipelineLayoutCI.setLayoutCount = (uint)resourceLayouts.Length;
            VkDescriptorSetLayout *dsls = stackalloc VkDescriptorSetLayout[resourceLayouts.Length];

            for (int i = 0; i < resourceLayouts.Length; i++)
            {
                dsls[i] = Util.AssertSubtype <ResourceLayout, VkResourceLayout>(resourceLayouts[i]).DescriptorSetLayout;
            }
            pipelineLayoutCI.pSetLayouts = dsls;

            vkCreatePipelineLayout(_gd.Device, ref pipelineLayoutCI, null, out _pipelineLayout);
            pipelineCI.layout = _pipelineLayout;

            // Create fake RenderPass for compatibility.
            VkRenderPassCreateInfo renderPassCI = VkRenderPassCreateInfo.New();
            OutputDescription      outputDesc   = description.Outputs;

            if (outputDesc.ColorAttachments.Length > 1)
            {
                throw new NotImplementedException("Laziness");
            }

            VkAttachmentDescription colorAttachmentDesc = new VkAttachmentDescription();

            colorAttachmentDesc.format = outputDesc.ColorAttachments.Length > 0
                ? VkFormats.VdToVkPixelFormat(outputDesc.ColorAttachments[0].Format) : 0;
            colorAttachmentDesc.samples        = VkSampleCountFlags.Count1;
            colorAttachmentDesc.loadOp         = VkAttachmentLoadOp.Clear;
            colorAttachmentDesc.storeOp        = VkAttachmentStoreOp.Store;
            colorAttachmentDesc.stencilLoadOp  = VkAttachmentLoadOp.DontCare;
            colorAttachmentDesc.stencilStoreOp = VkAttachmentStoreOp.DontCare;
            colorAttachmentDesc.initialLayout  = VkImageLayout.Undefined;
            colorAttachmentDesc.finalLayout    = VkImageLayout.PresentSrcKHR;

            VkAttachmentReference colorAttachmentRef = new VkAttachmentReference();

            colorAttachmentRef.attachment = 0;
            colorAttachmentRef.layout     = VkImageLayout.ColorAttachmentOptimal;

            VkAttachmentDescription depthAttachmentDesc = new VkAttachmentDescription();
            VkAttachmentReference   depthAttachmentRef  = new VkAttachmentReference();

            if (outputDesc.DepthAttachment != null)
            {
                depthAttachmentDesc.format         = VkFormats.VdToVkPixelFormat(outputDesc.DepthAttachment.Value.Format, toDepthFormat: true);
                depthAttachmentDesc.samples        = VkSampleCountFlags.Count1;
                depthAttachmentDesc.loadOp         = VkAttachmentLoadOp.Clear;
                depthAttachmentDesc.storeOp        = VkAttachmentStoreOp.Store;
                depthAttachmentDesc.stencilLoadOp  = VkAttachmentLoadOp.DontCare;
                depthAttachmentDesc.stencilStoreOp = VkAttachmentStoreOp.DontCare;
                depthAttachmentDesc.initialLayout  = VkImageLayout.Undefined;
                depthAttachmentDesc.finalLayout    = VkImageLayout.DepthStencilAttachmentOptimal;

                depthAttachmentRef.attachment = outputDesc.ColorAttachments.Length == 0 ? 0u : 1u;
                depthAttachmentRef.layout     = VkImageLayout.DepthStencilAttachmentOptimal;
            }

            VkSubpassDescription subpass = new VkSubpassDescription();
            StackList <VkAttachmentDescription, Size512Bytes> attachments = new StackList <VkAttachmentDescription, Size512Bytes>();

            subpass.pipelineBindPoint = VkPipelineBindPoint.Graphics;
            if (outputDesc.ColorAttachments.Length > 0)
            {
                subpass.colorAttachmentCount = 1;
                subpass.pColorAttachments    = &colorAttachmentRef;
                attachments.Add(colorAttachmentDesc);
            }

            if (outputDesc.DepthAttachment != null)
            {
                subpass.pDepthStencilAttachment = &depthAttachmentRef;
                attachments.Add(depthAttachmentDesc);
            }

            VkSubpassDependency subpassDependency = new VkSubpassDependency();

            subpassDependency.srcSubpass    = SubpassExternal;
            subpassDependency.srcStageMask  = VkPipelineStageFlags.ColorAttachmentOutput;
            subpassDependency.dstStageMask  = VkPipelineStageFlags.ColorAttachmentOutput;
            subpassDependency.dstAccessMask = VkAccessFlags.ColorAttachmentRead | VkAccessFlags.ColorAttachmentWrite;
            if (outputDesc.DepthAttachment != null)
            {
                subpassDependency.dstAccessMask |= VkAccessFlags.DepthStencilAttachmentRead | VkAccessFlags.DepthStencilAttachmentWrite;
            }

            renderPassCI.attachmentCount = attachments.Count;
            renderPassCI.pAttachments    = (VkAttachmentDescription *)attachments.Data;
            renderPassCI.subpassCount    = 1;
            renderPassCI.pSubpasses      = &subpass;
            renderPassCI.dependencyCount = 1;
            renderPassCI.pDependencies   = &subpassDependency;

            VkResult creationResult = vkCreateRenderPass(_gd.Device, ref renderPassCI, null, out _renderPass);

            CheckResult(creationResult);

            pipelineCI.renderPass = _renderPass;

            VkResult result = vkCreateGraphicsPipelines(_gd.Device, VkPipelineCache.Null, 1, ref pipelineCI, null, out _devicePipeline);

            CheckResult(result);

            ResourceSetCount = (uint)description.ResourceLayouts.Length;
        }
        //set appropriate source and destination rects for move rects
        private void SetMoveRect(ref Rectangle srcRect, ref Rectangle destRect, OutputDescription desktopDescription,
                                 OutputDuplicateMoveRectangle moveRect, int texWidth, int texHeight)
        {
            switch (desktopDescription.Rotation)
            {
            case DisplayModeRotation.Unspecified:
            case DisplayModeRotation.Identity:
            {
                srcRect.Left  = moveRect.SourcePoint.X;
                srcRect.Top   = moveRect.SourcePoint.Y;
                srcRect.Right = moveRect.SourcePoint.X + moveRect.DestinationRect.Right -
                                moveRect.DestinationRect.Left;
                srcRect.Bottom = moveRect.SourcePoint.Y + moveRect.DestinationRect.Bottom -
                                 moveRect.DestinationRect.Top;

                destRect = moveRect.DestinationRect;
                break;
            }

            case DisplayModeRotation.Rotate90:
            {
                srcRect.Left =
                    texHeight -
                    (moveRect.SourcePoint.Y + moveRect.DestinationRect.Bottom - moveRect.DestinationRect.Top);
                srcRect.Top    = moveRect.SourcePoint.X;
                srcRect.Right  = texHeight - moveRect.SourcePoint.Y;
                srcRect.Bottom =
                    moveRect.SourcePoint.X + moveRect.DestinationRect.Right - moveRect.DestinationRect.Left;

                destRect.Left   = texHeight - moveRect.DestinationRect.Bottom;
                destRect.Top    = moveRect.DestinationRect.Left;
                destRect.Right  = texHeight - moveRect.DestinationRect.Top;
                destRect.Bottom = moveRect.DestinationRect.Right;

                break;
            }

            case DisplayModeRotation.Rotate180:
            {
                srcRect.Left = texHeight -
                               (moveRect.SourcePoint.X + moveRect.DestinationRect.Right -
                                moveRect.DestinationRect.Left);
                srcRect.Top = texHeight -
                              (moveRect.SourcePoint.Y + moveRect.DestinationRect.Bottom -
                               moveRect.DestinationRect.Top);
                srcRect.Right  = texWidth - moveRect.SourcePoint.X;
                srcRect.Bottom = texHeight - moveRect.SourcePoint.Y;

                destRect.Left   = texWidth - moveRect.DestinationRect.Right;
                destRect.Top    = texHeight - moveRect.DestinationRect.Bottom;
                destRect.Right  = texWidth - moveRect.DestinationRect.Left;
                destRect.Bottom = texHeight - moveRect.DestinationRect.Top;
                break;
            }

            case DisplayModeRotation.Rotate270:
            {
                srcRect.Left = moveRect.SourcePoint.X;
                srcRect.Top  = texWidth -
                               (moveRect.SourcePoint.X + moveRect.DestinationRect.Right -
                                moveRect.DestinationRect.Left);
                srcRect.Right = moveRect.SourcePoint.Y + moveRect.DestinationRect.Bottom -
                                moveRect.DestinationRect.Top;
                srcRect.Bottom = texWidth - moveRect.SourcePoint.X;

                destRect.Left   = moveRect.DestinationRect.Top;
                destRect.Top    = texWidth - moveRect.DestinationRect.Right;
                destRect.Right  = moveRect.DestinationRect.Bottom;
                destRect.Bottom = texWidth - moveRect.DestinationRect.Left;
                break;
            }

            default:
            {
                destRect = new Rectangle();
                srcRect  = new Rectangle();
                break;
            }
            }
        }
        //sets up vertices for dirty rects for rotated desktops
        private void SetDirtyVert(ref Vertex[] vertices, int startIndex, Rectangle dirty, OutputDescription deskDesc,
                                  Texture2DDescription fullDesc, Texture2DDescription thisDesc)
        {
            //todo
            int centerX = fullDesc.Width / 2;
            int centerY = fullDesc.Height / 2;

            int width  = deskDesc.DesktopBounds.Right - deskDesc.DesktopBounds.Left;
            int height = deskDesc.DesktopBounds.Bottom - deskDesc.DesktopBounds.Top;

            //rotation compensated destination rect
            Rectangle destDirty = dirty;

            //set appropricate coordinates compensated for rotation
            switch (deskDesc.Rotation)
            {
            case DisplayModeRotation.Rotate90:
            {
                destDirty.Left   = width - dirty.Bottom;
                destDirty.Top    = dirty.Left;
                destDirty.Right  = width - dirty.Top;
                destDirty.Bottom = dirty.Bottom;

                vertices[startIndex + 0].SetTexCoord(dirty.Right / (float)thisDesc.Width,
                                                     dirty.Bottom / (float)thisDesc.Height);
                vertices[startIndex + 1].SetTexCoord(dirty.Left / (float)thisDesc.Width,
                                                     dirty.Bottom / (float)thisDesc.Height);
                vertices[startIndex + 2].SetTexCoord(dirty.Right / (float)thisDesc.Width,
                                                     dirty.Top / (float)thisDesc.Height);
                vertices[startIndex + 5].SetTexCoord(dirty.Left / (float)thisDesc.Width,
                                                     dirty.Top / (float)thisDesc.Height);
                break;
            }

            case DisplayModeRotation.Rotate180:
            {
                destDirty.Left   = width - dirty.Right;
                destDirty.Top    = height - dirty.Bottom;
                destDirty.Right  = width - dirty.Left;
                destDirty.Bottom = height - dirty.Top;

                vertices[startIndex + 0].SetTexCoord(dirty.Right / (float)thisDesc.Width,
                                                     dirty.Top / (float)thisDesc.Height);
                vertices[startIndex + 1].SetTexCoord(dirty.Right / (float)thisDesc.Width,
                                                     dirty.Bottom / (float)thisDesc.Height);
                vertices[startIndex + 2].SetTexCoord(dirty.Left / (float)thisDesc.Width,
                                                     dirty.Top / (float)thisDesc.Height);
                vertices[startIndex + 5].SetTexCoord(dirty.Left / (float)thisDesc.Width,
                                                     dirty.Bottom / (float)thisDesc.Height);
                break;
            }

            case DisplayModeRotation.Rotate270:
            {
                destDirty.Left   = dirty.Top;
                destDirty.Top    = height - dirty.Right;
                destDirty.Right  = dirty.Bottom;
                destDirty.Bottom = height - dirty.Left;

                vertices[startIndex + 0].SetTexCoord(dirty.Left / (float)thisDesc.Width,
                                                     dirty.Top / (float)thisDesc.Height);
                vertices[startIndex + 1].SetTexCoord(dirty.Right / (float)thisDesc.Width,
                                                     dirty.Top / (float)thisDesc.Height);
                vertices[startIndex + 2].SetTexCoord(dirty.Left / (float)thisDesc.Width,
                                                     dirty.Bottom / (float)thisDesc.Height);
                vertices[startIndex + 5].SetTexCoord(dirty.Right / (float)thisDesc.Width,
                                                     dirty.Bottom / (float)thisDesc.Height);
                break;
            }

            default:
            {
                vertices[startIndex + 0].SetTexCoord(dirty.Left / (float)thisDesc.Width,
                                                     dirty.Bottom / (float)thisDesc.Height);
                vertices[startIndex + 1].SetTexCoord(dirty.Left / (float)thisDesc.Width,
                                                     dirty.Top / (float)thisDesc.Height);
                vertices[startIndex + 2].SetTexCoord(dirty.Right / (float)thisDesc.Width,
                                                     dirty.Bottom / (float)thisDesc.Height);
                vertices[startIndex + 5].SetTexCoord(dirty.Right / (float)thisDesc.Width,
                                                     dirty.Top / (float)thisDesc.Height);
                break;
            }
            }

            //set positions
            vertices[startIndex + 0].SetPos((destDirty.Left + deskDesc.DesktopBounds.Left - centerX) / (float)centerX,
                                            -1 * (destDirty.Bottom + deskDesc.DesktopBounds.Top - centerY) / (float)centerY, 0f);
            vertices[startIndex + 1].SetPos((destDirty.Left + deskDesc.DesktopBounds.Left - centerX),
                                            -1 * (destDirty.Top + deskDesc.DesktopBounds.Top - centerY) / (float)centerY, 0f);
            vertices[startIndex + 2].SetPos((destDirty.Right + deskDesc.DesktopBounds.Left - centerX) / (float)centerX,
                                            -1 * (destDirty.Bottom + deskDesc.DesktopBounds.Top - centerY) / (float)centerY, 0f);
            vertices[startIndex + 3].SetPos(vertices[startIndex + 2].Pos_X, vertices[startIndex + 2].Pos_Y, 0f);
            vertices[startIndex + 4].SetPos(vertices[startIndex + 1].Pos_X, vertices[startIndex + 1].Pos_Y, 0f);
            vertices[startIndex + 5].SetPos((destDirty.Right + deskDesc.DesktopBounds.Left - centerX) / (float)centerX,
                                            -1 * (destDirty.Top + deskDesc.DesktopBounds.Top - centerY) / (float)centerY, 0f);

            vertices[startIndex + 3].SetTexCoord(vertices[startIndex + 2].TexCoord_X,
                                                 vertices[startIndex + 2].TexCoord_Y);
            vertices[startIndex + 4].SetTexCoord(vertices[startIndex + 1].TexCoord_X,
                                                 vertices[startIndex + 1].TexCoord_Y);
        }
示例#19
0
        public void Initialize(int monitor)
        {
            const int graphicsCardAdapter = 0;
            Adapter1  adapter;

            try
            {
                adapter = new Factory1().GetAdapter1(graphicsCardAdapter);
            }
            catch (SharpDXException)
            {
                throw new DesktopDuplicationException("Could not find the specified graphics card adapter.");
            }

            Output output;

            using (adapter)
            {
                _device = new Device(adapter);

                try
                {
                    output = adapter.GetOutput(monitor);
                }
                catch (SharpDXException)
                {
                    throw new DesktopDuplicationException("Could not find the specified output device.");
                }
            }

            using (output)
                using (var output1 = output.QueryInterface <Output1>())
                {
                    _outputDesc  = output.Description;
                    _textureDesc = new Texture2DDescription
                    {
                        CpuAccessFlags    = CpuAccessFlags.Read,
                        BindFlags         = BindFlags.None,
                        Format            = Format.B8G8R8A8_UNorm,
                        Width             = _outputDesc.DesktopBounds.GetWidth(),
                        Height            = _outputDesc.DesktopBounds.GetHeight(),
                        OptionFlags       = ResourceOptionFlags.None,
                        MipLevels         = 1,
                        ArraySize         = 1,
                        SampleDescription = { Count = 1, Quality = 0 },
                        Usage             = ResourceUsage.Staging
                    };

                    try
                    {
                        _deskDupl = output1.DuplicateOutput(_device);
                    }
                    catch (SharpDXException ex)
                    {
                        if (ex.ResultCode.Code == SharpDX.DXGI.ResultCode.NotCurrentlyAvailable.Result.Code)
                        {
                            throw new DesktopDuplicationException(
                                      "There is already the maximum number of applications using the Desktop Duplication API running, please close one of the applications and try again.");
                        }
                    }
                }

            _currentMonitor = monitor;
            _screenHelper   = new ScreenHelper();
        }
示例#20
0
 public void CreateDeviceResources(GraphicsDevice gd, OutputDescription outputDescription)
 => CreateDeviceResources(gd, outputDescription, _colorSpaceHandling);
示例#21
0
        public MTLPipeline(ref GraphicsPipelineDescription description, MTLGraphicsDevice gd)
            : base(ref description)
        {
            PrimitiveType        = MTLFormats.VdToMTLPrimitiveTopology(description.PrimitiveTopology);
            ResourceLayouts      = new MTLResourceLayout[description.ResourceLayouts.Length];
            NonVertexBufferCount = 0;
            for (int i = 0; i < ResourceLayouts.Length; i++)
            {
                ResourceLayouts[i]    = Util.AssertSubtype <ResourceLayout, MTLResourceLayout>(description.ResourceLayouts[i]);
                NonVertexBufferCount += ResourceLayouts[i].BufferCount;
            }
            ResourceBindingModel = description.ResourceBindingModel ?? gd.ResourceBindingModel;

            CullMode           = MTLFormats.VdToMTLCullMode(description.RasterizerState.CullMode);
            FrontFace          = MTLFormats.VdVoMTLFrontFace(description.RasterizerState.FrontFace);
            FillMode           = MTLFormats.VdToMTLFillMode(description.RasterizerState.FillMode);
            ScissorTestEnabled = description.RasterizerState.ScissorTestEnabled;

            MTLRenderPipelineDescriptor mtlDesc = MTLRenderPipelineDescriptor.New();

            foreach (Shader shader in description.ShaderSet.Shaders)
            {
                MTLShader   mtlShader = Util.AssertSubtype <Shader, MTLShader>(shader);
                MTLFunction specializedFunction;

                if (mtlShader.HasFunctionConstants)
                {
                    // Need to create specialized MTLFunction.
                    MTLFunctionConstantValues constantValues = CreateConstantValues(description.ShaderSet.Specializations);
                    specializedFunction = mtlShader.Library.newFunctionWithNameConstantValues(mtlShader.EntryPoint, constantValues);
                    AddSpecializedFunction(specializedFunction);
                    ObjectiveCRuntime.release(constantValues.NativePtr);

                    Debug.Assert(specializedFunction.NativePtr != IntPtr.Zero, "Failed to create specialized MTLFunction");
                }
                else
                {
                    specializedFunction = mtlShader.Function;
                }

                if (shader.Stage == ShaderStages.Vertex)
                {
                    mtlDesc.vertexFunction = specializedFunction;
                }
                else if (shader.Stage == ShaderStages.Fragment)
                {
                    mtlDesc.fragmentFunction = specializedFunction;
                }
            }

            // Vertex layouts
            VertexLayoutDescription[] vdVertexLayouts  = description.ShaderSet.VertexLayouts;
            MTLVertexDescriptor       vertexDescriptor = mtlDesc.vertexDescriptor;

            for (uint i = 0; i < vdVertexLayouts.Length; i++)
            {
                uint layoutIndex = ResourceBindingModel == ResourceBindingModel.Improved
                    ? NonVertexBufferCount + i
                    : i;
                MTLVertexBufferLayoutDescriptor mtlLayout = vertexDescriptor.layouts[layoutIndex];
                mtlLayout.stride = (UIntPtr)vdVertexLayouts[i].Stride;
                uint stepRate = vdVertexLayouts[i].InstanceStepRate;
                mtlLayout.stepFunction = stepRate == 0 ? MTLVertexStepFunction.PerVertex : MTLVertexStepFunction.PerInstance;
                mtlLayout.stepRate     = (UIntPtr)Math.Max(1, stepRate);
            }

            uint element = 0;

            for (uint i = 0; i < vdVertexLayouts.Length; i++)
            {
                uint offset = 0;
                VertexLayoutDescription vdDesc = vdVertexLayouts[i];
                for (uint j = 0; j < vdDesc.Elements.Length; j++)
                {
                    VertexElementDescription     elementDesc  = vdDesc.Elements[j];
                    MTLVertexAttributeDescriptor mtlAttribute = vertexDescriptor.attributes[element];
                    mtlAttribute.bufferIndex = (UIntPtr)(ResourceBindingModel == ResourceBindingModel.Improved
                        ? NonVertexBufferCount + i
                        : i);
                    mtlAttribute.format = MTLFormats.VdToMTLVertexFormat(elementDesc.Format);
                    mtlAttribute.offset = elementDesc.Offset != 0 ? (UIntPtr)elementDesc.Offset : (UIntPtr)offset;
                    offset  += FormatHelpers.GetSizeInBytes(elementDesc.Format);
                    element += 1;
                }
            }

            VertexBufferCount = (uint)vdVertexLayouts.Length;

            // Outputs
            OutputDescription     outputs        = description.Outputs;
            BlendStateDescription blendStateDesc = description.BlendState;

            BlendColor = blendStateDesc.BlendFactor;

            if (outputs.SampleCount != TextureSampleCount.Count1)
            {
                mtlDesc.sampleCount = (UIntPtr)FormatHelpers.GetSampleCountUInt32(outputs.SampleCount);
            }

            if (outputs.DepthAttachment != null)
            {
                PixelFormat    depthFormat    = outputs.DepthAttachment.Value.Format;
                MTLPixelFormat mtlDepthFormat = MTLFormats.VdToMTLPixelFormat(depthFormat, true);
                mtlDesc.depthAttachmentPixelFormat = mtlDepthFormat;
                if ((FormatHelpers.IsStencilFormat(depthFormat)))
                {
                    HasStencil = true;
                    mtlDesc.stencilAttachmentPixelFormat = mtlDepthFormat;
                }
            }
            for (uint i = 0; i < outputs.ColorAttachments.Length; i++)
            {
                BlendAttachmentDescription attachmentBlendDesc       = blendStateDesc.AttachmentStates[i];
                MTLRenderPipelineColorAttachmentDescriptor colorDesc = mtlDesc.colorAttachments[i];
                colorDesc.pixelFormat                 = MTLFormats.VdToMTLPixelFormat(outputs.ColorAttachments[i].Format, false);
                colorDesc.blendingEnabled             = attachmentBlendDesc.BlendEnabled;
                colorDesc.alphaBlendOperation         = MTLFormats.VdToMTLBlendOp(attachmentBlendDesc.AlphaFunction);
                colorDesc.sourceAlphaBlendFactor      = MTLFormats.VdToMTLBlendFactor(attachmentBlendDesc.SourceAlphaFactor);
                colorDesc.destinationAlphaBlendFactor = MTLFormats.VdToMTLBlendFactor(attachmentBlendDesc.DestinationAlphaFactor);

                colorDesc.rgbBlendOperation         = MTLFormats.VdToMTLBlendOp(attachmentBlendDesc.ColorFunction);
                colorDesc.sourceRGBBlendFactor      = MTLFormats.VdToMTLBlendFactor(attachmentBlendDesc.SourceColorFactor);
                colorDesc.destinationRGBBlendFactor = MTLFormats.VdToMTLBlendFactor(attachmentBlendDesc.DestinationColorFactor);
            }

            RenderPipelineState = gd.Device.newRenderPipelineStateWithDescriptor(mtlDesc);
            ObjectiveCRuntime.release(mtlDesc.NativePtr);

            if (outputs.DepthAttachment != null)
            {
                MTLDepthStencilDescriptor depthDescriptor = MTLUtil.AllocInit <MTLDepthStencilDescriptor>(
                    nameof(MTLDepthStencilDescriptor));
                depthDescriptor.depthCompareFunction = MTLFormats.VdToMTLCompareFunction(
                    description.DepthStencilState.DepthComparison);
                depthDescriptor.depthWriteEnabled = description.DepthStencilState.DepthWriteEnabled;

                bool stencilEnabled = description.DepthStencilState.StencilTestEnabled;
                if (stencilEnabled)
                {
                    StencilReference = description.DepthStencilState.StencilReference;

                    StencilBehaviorDescription vdFrontDesc = description.DepthStencilState.StencilFront;
                    MTLStencilDescriptor       front       = MTLUtil.AllocInit <MTLStencilDescriptor>(nameof(MTLStencilDescriptor));
                    front.readMask                   = stencilEnabled ? description.DepthStencilState.StencilReadMask : 0u;
                    front.writeMask                  = stencilEnabled ? description.DepthStencilState.StencilWriteMask : 0u;
                    front.depthFailureOperation      = MTLFormats.VdToMTLStencilOperation(vdFrontDesc.DepthFail);
                    front.stencilFailureOperation    = MTLFormats.VdToMTLStencilOperation(vdFrontDesc.Fail);
                    front.depthStencilPassOperation  = MTLFormats.VdToMTLStencilOperation(vdFrontDesc.Pass);
                    front.stencilCompareFunction     = MTLFormats.VdToMTLCompareFunction(vdFrontDesc.Comparison);
                    depthDescriptor.frontFaceStencil = front;

                    StencilBehaviorDescription vdBackDesc = description.DepthStencilState.StencilBack;
                    MTLStencilDescriptor       back       = MTLUtil.AllocInit <MTLStencilDescriptor>(nameof(MTLStencilDescriptor));
                    back.readMask                   = stencilEnabled ? description.DepthStencilState.StencilReadMask : 0u;
                    back.writeMask                  = stencilEnabled ? description.DepthStencilState.StencilWriteMask : 0u;
                    back.depthFailureOperation      = MTLFormats.VdToMTLStencilOperation(vdBackDesc.DepthFail);
                    back.stencilFailureOperation    = MTLFormats.VdToMTLStencilOperation(vdBackDesc.Fail);
                    back.depthStencilPassOperation  = MTLFormats.VdToMTLStencilOperation(vdBackDesc.Pass);
                    back.stencilCompareFunction     = MTLFormats.VdToMTLCompareFunction(vdBackDesc.Comparison);
                    depthDescriptor.backFaceStencil = back;

                    ObjectiveCRuntime.release(front.NativePtr);
                    ObjectiveCRuntime.release(back.NativePtr);
                }

                DepthStencilState = gd.Device.newDepthStencilStateWithDescriptor(depthDescriptor);
                ObjectiveCRuntime.release(depthDescriptor.NativePtr);
            }

            DepthClipMode = description.DepthStencilState.DepthTestEnabled ? MTLDepthClipMode.Clip : MTLDepthClipMode.Clamp;
        }
示例#22
0
 /// <summary>
 /// Constructs a new ImGuiRenderer.
 /// </summary>
 /// <param name="gd">The GraphicsDevice used to create and update resources.</param>
 /// <param name="outputDescription">The output format.</param>
 /// <param name="width">The initial width of the rendering target. Can be resized.</param>
 /// <param name="height">The initial height of the rendering target. Can be resized.</param>
 public ImGuiRenderer(GraphicsDevice gd, OutputDescription outputDescription, int width, int height)
     : this(gd, outputDescription, width, height, ColorSpaceHandling.Legacy)
 {
 }
示例#23
0
        /// <summary>
        /// Initializes a new instance of the <see cref="GraphicsAdapter" /> class.
        /// </summary>
        /// <param name="adapterOrdinal">The adapter ordinal.</param>
        private GraphicsAdapter(int adapterOrdinal)
        {
            this.adapterOrdinal = adapterOrdinal;
            adapter = ToDispose(Factory.GetAdapter1(adapterOrdinal));
            Description = adapter.Description1;
            outputs = adapter.Outputs;
            SupportedDisplayModes = new DisplayMode[0];

            // Enumerate outputs if any.
            if (outputs != null && outputs.Length > 0)
            {
                outputDescription = outputs[0].Description;
                SupportedDisplayModes = GetSupportedDisplayModes();
                foreach (var output in outputs)
                {
                    ToDispose(output);
                }

                foreach (var supportedDisplayMode in SupportedDisplayModes)
                {
                    if (supportedDisplayMode.Width == outputDescription.DesktopBounds.Width
                        && supportedDisplayMode.Height == outputDescription.DesktopBounds.Height
                        && supportedDisplayMode.Format == Format.R8G8B8A8_UNorm)
                    {
                        // Stupid DXGI, there is no way to get the DXGI.Format, nor the refresh rate.
                        CurrentDisplayMode = new DisplayMode(Format.R8G8B8A8_UNorm, outputDescription.DesktopBounds.Width, outputDescription.DesktopBounds.Height, supportedDisplayMode.RefreshRate);
                        break;
                    }
                }

                if (CurrentDisplayMode == null)
                {
                    foreach (var supportedDisplayMode in SupportedDisplayModes)
                    {
                        if (supportedDisplayMode.Width == outputDescription.DesktopBounds.Width
                            && supportedDisplayMode.Height == outputDescription.DesktopBounds.Height
                            && supportedDisplayMode.Format == Format.B8G8R8A8_UNorm)
                        {
                            // Stupid DXGI, there is no way to get the DXGI.Format, nor the refresh rate.
                            CurrentDisplayMode = new DisplayMode(Format.B8G8R8A8_UNorm, outputDescription.DesktopBounds.Width, outputDescription.DesktopBounds.Height, supportedDisplayMode.RefreshRate);
                            break;
                        }
                    }
                }
            }
        }
示例#24
0
        /// <summary>
        /// Constructs a new ImGuiController.
        /// </summary>
        public unsafe ImGuiView(GraphicsDevice gd, Sdl2Window window, OutputDescription outputDescription, int width, int height)
        {
            _gd           = gd;
            _window       = window;
            _windowWidth  = width;
            _windowHeight = height;

            IntPtr context = ImGui.CreateContext();

            ImGui.SetCurrentContext(context);
            ImGuiIOPtr io = ImGui.GetIO();

            io.ConfigFlags |= ImGuiConfigFlags.DockingEnable;
            io.ConfigFlags |= ImGuiConfigFlags.ViewportsEnable;

            ImGuiPlatformIOPtr platformIO   = ImGui.GetPlatformIO();
            ImGuiViewportPtr   mainViewport = platformIO.MainViewport;

            mainViewport.PlatformHandle = window.Handle;
            _mainViewportWindow         = new VeldridImGuiWindow(gd, mainViewport, _window);

            _createWindow       = CreateWindow;
            _destroyWindow      = DestroyWindow;
            _getWindowPos       = GetWindowPos;
            _showWindow         = ShowWindow;
            _setWindowPos       = SetWindowPos;
            _setWindowSize      = SetWindowSize;
            _getWindowSize      = GetWindowSize;
            _setWindowFocus     = SetWindowFocus;
            _getWindowFocus     = GetWindowFocus;
            _getWindowMinimized = GetWindowMinimized;
            _setWindowTitle     = SetWindowTitle;

            platformIO.Platform_CreateWindow       = Marshal.GetFunctionPointerForDelegate(_createWindow);
            platformIO.Platform_DestroyWindow      = Marshal.GetFunctionPointerForDelegate(_destroyWindow);
            platformIO.Platform_ShowWindow         = Marshal.GetFunctionPointerForDelegate(_showWindow);
            platformIO.Platform_SetWindowPos       = Marshal.GetFunctionPointerForDelegate(_setWindowPos);
            platformIO.Platform_SetWindowSize      = Marshal.GetFunctionPointerForDelegate(_setWindowSize);
            platformIO.Platform_SetWindowFocus     = Marshal.GetFunctionPointerForDelegate(_setWindowFocus);
            platformIO.Platform_GetWindowFocus     = Marshal.GetFunctionPointerForDelegate(_getWindowFocus);
            platformIO.Platform_GetWindowMinimized = Marshal.GetFunctionPointerForDelegate(_getWindowMinimized);
            platformIO.Platform_SetWindowTitle     = Marshal.GetFunctionPointerForDelegate(_setWindowTitle);

            ImGuiNative.ImGuiPlatformIO_Set_Platform_GetWindowPos(platformIO.NativePtr, Marshal.GetFunctionPointerForDelegate(_getWindowPos));
            ImGuiNative.ImGuiPlatformIO_Set_Platform_GetWindowSize(platformIO.NativePtr, Marshal.GetFunctionPointerForDelegate(_getWindowSize));

            unsafe
            {
                io.NativePtr->BackendPlatformName = (byte *)new FixedAsciiString("Veldrid.SDL2 Backend").DataPtr;
            }
            io.BackendFlags |= ImGuiBackendFlags.HasMouseCursors;
            io.BackendFlags |= ImGuiBackendFlags.HasSetMousePos;
            io.BackendFlags |= ImGuiBackendFlags.PlatformHasViewports;
            io.BackendFlags |= ImGuiBackendFlags.RendererHasViewports;

            io.Fonts.AddFontDefault();

            // Create general resources
            _gd = gd;
            ResourceFactory factory = gd.ResourceFactory;

            _vertexBuffer      = factory.CreateBuffer(new BufferDescription(10000, BufferUsage.VertexBuffer | BufferUsage.Dynamic));
            _vertexBuffer.Name = "ImGui.NET Vertex Buffer";
            _indexBuffer       = factory.CreateBuffer(new BufferDescription(2000, BufferUsage.IndexBuffer | BufferUsage.Dynamic));
            _indexBuffer.Name  = "ImGui.NET Index Buffer";


            byte *pixels;
            int   fwidth, fheight, bytesPerPixel;

            io.Fonts.GetTexDataAsRGBA32(out pixels, out fwidth, out fheight, out bytesPerPixel);
            // Store our identifier
            io.Fonts.SetTexID(_fontAtlasID);

            _fontTexture = gd.ResourceFactory.CreateTexture(TextureDescription.Texture2D(
                                                                (uint)fwidth,
                                                                (uint)fheight,
                                                                1,
                                                                1,
                                                                PixelFormat.R8_G8_B8_A8_UNorm,
                                                                TextureUsage.Sampled));
            _fontTexture.Name = "ImGui.NET Font Texture";
            gd.UpdateTexture(
                _fontTexture,
                (IntPtr)pixels,
                (uint)(bytesPerPixel * fwidth * fheight),
                0,
                0,
                0,
                (uint)fwidth,
                (uint)fheight,
                1,
                0,
                0);
            _fontTextureView = gd.ResourceFactory.CreateTextureView(_fontTexture);

            io.Fonts.ClearTexData();


            _projMatrixBuffer      = factory.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer | BufferUsage.Dynamic));
            _projMatrixBuffer.Name = "ImGui.NET Projection Buffer";

            byte[] vertexShaderBytes   = LoadEmbeddedShaderCode(gd.ResourceFactory, "imgui-vertex", ShaderStages.Vertex);
            byte[] fragmentShaderBytes = LoadEmbeddedShaderCode(gd.ResourceFactory, "imgui-frag", ShaderStages.Fragment);
            _vertexShader   = factory.CreateShader(new ShaderDescription(ShaderStages.Vertex, vertexShaderBytes, "main"));
            _fragmentShader = factory.CreateShader(new ShaderDescription(ShaderStages.Fragment, fragmentShaderBytes, "main"));

            VertexLayoutDescription[] vertexLayouts = new VertexLayoutDescription[]
            {
                new VertexLayoutDescription(
                    new VertexElementDescription("in_position", VertexElementSemantic.Position, VertexElementFormat.Float2),
                    new VertexElementDescription("in_texCoord", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2),
                    new VertexElementDescription("in_color", VertexElementSemantic.Color, VertexElementFormat.Byte4_Norm))
            };

            _layout = factory.CreateResourceLayout(new ResourceLayoutDescription(
                                                       new ResourceLayoutElementDescription("ProjectionMatrixBuffer", ResourceKind.UniformBuffer, ShaderStages.Vertex),
                                                       new ResourceLayoutElementDescription("MainSampler", ResourceKind.Sampler, ShaderStages.Fragment)));
            _textureLayout = factory.CreateResourceLayout(new ResourceLayoutDescription(
                                                              new ResourceLayoutElementDescription("MainTexture", ResourceKind.TextureReadOnly, ShaderStages.Fragment)));

            GraphicsPipelineDescription pd = new GraphicsPipelineDescription(
                BlendStateDescription.SingleAlphaBlend,
                new DepthStencilStateDescription(false, false, ComparisonKind.Always),
                new RasterizerStateDescription(FaceCullMode.None, PolygonFillMode.Solid, FrontFace.Clockwise, false, true),
                PrimitiveTopology.TriangleList,
                new ShaderSetDescription(vertexLayouts, new[] { _vertexShader, _fragmentShader }),
                new ResourceLayout[] { _layout, _textureLayout },
                outputDescription);

            _pipeline = factory.CreateGraphicsPipeline(ref pd);

            _mainResourceSet = factory.CreateResourceSet(new ResourceSetDescription(_layout,
                                                                                    _projMatrixBuffer,
                                                                                    gd.PointSampler));

            _fontTextureResourceSet = factory.CreateResourceSet(new ResourceSetDescription(_textureLayout, _fontTextureView));


            SetKeyMappings();

            SetPerFrameImGuiData(1f / 60f, width, height);
            UpdateMonitors();

            ImGui.NewFrame();
            _frameBegun = true;
        }
示例#25
0
        /// <summary>
        /// Constructs a new ImGuiController.
        /// </summary>
        public unsafe ImGuiController(GraphicsDevice gd, Sdl2Window window, OutputDescription outputDescription, int width, int height)
        {
            _gd           = gd;
            _window       = window;
            _windowWidth  = width;
            _windowHeight = height;

            IntPtr context = ImGui.CreateContext();

            ImGui.SetCurrentContext(context);
            ImGuiIOPtr io = ImGui.GetIO();

            io.ConfigFlags |= ImGuiConfigFlags.DockingEnable;
            io.ConfigFlags |= ImGuiConfigFlags.ViewportsEnable;

            ImGuiPlatformIOPtr platformIO   = ImGui.GetPlatformIO();
            ImGuiViewportPtr   mainViewport = platformIO.MainViewport;

            mainViewport.PlatformHandle = window.Handle;
            _mainViewportWindow         = new VeldridImGuiWindow(gd, mainViewport, _window);

            _createWindow       = CreateWindow;
            _destroyWindow      = DestroyWindow;
            _getWindowPos       = GetWindowPos;
            _showWindow         = ShowWindow;
            _setWindowPos       = SetWindowPos;
            _setWindowSize      = SetWindowSize;
            _getWindowSize      = GetWindowSize;
            _setWindowFocus     = SetWindowFocus;
            _getWindowFocus     = GetWindowFocus;
            _getWindowMinimized = GetWindowMinimized;
            _setWindowTitle     = SetWindowTitle;

            platformIO.Platform_CreateWindow       = Marshal.GetFunctionPointerForDelegate(_createWindow);
            platformIO.Platform_DestroyWindow      = Marshal.GetFunctionPointerForDelegate(_destroyWindow);
            platformIO.Platform_ShowWindow         = Marshal.GetFunctionPointerForDelegate(_showWindow);
            platformIO.Platform_SetWindowPos       = Marshal.GetFunctionPointerForDelegate(_setWindowPos);
            platformIO.Platform_SetWindowSize      = Marshal.GetFunctionPointerForDelegate(_setWindowSize);
            platformIO.Platform_SetWindowFocus     = Marshal.GetFunctionPointerForDelegate(_setWindowFocus);
            platformIO.Platform_GetWindowFocus     = Marshal.GetFunctionPointerForDelegate(_getWindowFocus);
            platformIO.Platform_GetWindowMinimized = Marshal.GetFunctionPointerForDelegate(_getWindowMinimized);
            platformIO.Platform_SetWindowTitle     = Marshal.GetFunctionPointerForDelegate(_setWindowTitle);

            ImGuiNative.ImGuiPlatformIO_Set_Platform_GetWindowPos(platformIO.NativePtr, Marshal.GetFunctionPointerForDelegate(_getWindowPos));
            ImGuiNative.ImGuiPlatformIO_Set_Platform_GetWindowSize(platformIO.NativePtr, Marshal.GetFunctionPointerForDelegate(_getWindowSize));

            unsafe
            {
                io.NativePtr->BackendPlatformName = (byte *)new FixedAsciiString("Veldrid.SDL2 Backend").DataPtr;
            }
            io.BackendFlags |= ImGuiBackendFlags.HasMouseCursors;
            io.BackendFlags |= ImGuiBackendFlags.HasSetMousePos;
            io.BackendFlags |= ImGuiBackendFlags.PlatformHasViewports;
            io.BackendFlags |= ImGuiBackendFlags.RendererHasViewports;

            io.Fonts.AddFontDefault();

            CreateDeviceResources(gd, outputDescription);
            SetKeyMappings();

            SetPerFrameImGuiData(1f / 60f);
            UpdateMonitors();

            ImGui.NewFrame();
            _frameBegun = true;
        }
示例#26
0
 public async Task CleanOutputAsync(OutputDescription testOutput)
 {
     await Task.Run(() => CleanOutput(testOutput));
 }
示例#27
0
        public DesktopDuplicator(Rectangle Rect, bool IncludeCursor, int Monitor, int Adapter = 0)
        {
            _rect          = Rect;
            _includeCursor = IncludeCursor;

            Adapter1 adapter;

            try
            {
                adapter = new Factory1().GetAdapter1(Adapter);
            }
            catch (SharpDXException e)
            {
                throw new Exception("Could not find the specified graphics card adapter.", e);
            }

            _device = new Device(adapter);

            Output output;

            try
            {
                output = adapter.GetOutput(Monitor);
            }
            catch (SharpDXException e)
            {
                throw new Exception("Could not find the specified output device.", e);
            }

            var output1 = output.QueryInterface <Output1>();

            _outputDesc = output.Description;

            _textureDesc = new Texture2DDescription
            {
                CpuAccessFlags    = CpuAccessFlags.Read,
                BindFlags         = BindFlags.None,
                Format            = Format.B8G8R8A8_UNorm,
                Width             = _rect.Width,
                Height            = _rect.Height,
                OptionFlags       = ResourceOptionFlags.None,
                MipLevels         = 1,
                ArraySize         = 1,
                SampleDescription = { Count = 1, Quality = 0 },
                Usage             = ResourceUsage.Staging
            };

            try
            {
                _deskDupl = output1.DuplicateOutput(_device);
            }
            catch (SharpDXException e) when(e.Descriptor == SharpDX.DXGI.ResultCode.NotCurrentlyAvailable)
            {
                throw new Exception("There is already the maximum number of applications using the Desktop Duplication API running, please close one of the applications and try again.", e);
            }
            catch (SharpDXException e) when(e.Descriptor == SharpDX.DXGI.ResultCode.Unsupported)
            {
                throw new NotSupportedException("Desktop Duplication is not supported on this system.\nIf you have multiple graphic cards, try running Captura on integrated graphics.", e);
            }

            _desktopImageTexture = new Texture2D(_device, _textureDesc);
        }
示例#28
0
        public DXGIManager(CaptureSource captureSource)
        {
            _captureSource = captureSource;
            _factory       = new Factory4();
            _outputs       = new List <DXGIOutputDuplication>();

            foreach (Adapter adapter in _factory.Adapters)
            {
                List <Output> outputs = new List <Output>();

                foreach (Output output in adapter.Outputs)
                {
                    OutputDescription desc = output.Description;
                    if (desc.IsAttachedToDesktop == false)
                    {
                        continue;
                    }

                    outputs.Add(output);
                }

                if (outputs.Count == 0)
                {
                    continue;
                }

                SharpDX.Direct3D11.Device device = new SharpDX.Direct3D11.Device(adapter);

                try
                {
                    foreach (Output output in outputs)
                    {
                        using (Output1 output1 = output.QueryInterface <Output1>())
                        {
                            OutputDuplication outputDuplication = output1.DuplicateOutput(device);

                            if (outputDuplication == null)
                            {
                                continue;
                            }

                            _outputs.Add(
                                new DXGIOutputDuplication(adapter, device, outputDuplication, output1.Description));
                        }
                    }
                }
                catch (SharpDXException e)
                {
                    // desktop이 바뀐 후 복원되었을 때 곧바로 output1.DuplicateOutput을 호출하는 경우
                    // 일부 output에서 E_ACCESS_DENIED가 발생함.
                    if (e.ResultCode == DXGIError.E_ACCESS_DENIED)
                    {
                        Dispose();
                    }
                }
            }

            if (this.Initialized == true)
            {
                CalcOutputRect();
            }
        }
示例#29
0
        public ScreenDublicator()
        {
            Adapter adapter = null;
            Output output = null;
            Output1 output1 = null;
            try
            { 
                //Адаптер
                
                adapter = new Factory1().GetAdapter1(this.ADAPTER);
            
                //Устройство

                this._device = new Device(adapter);
                output = adapter.GetOutput(this.MONITOR);
            
                //Выход

                output1 = output.QueryInterface<Output1>();
                this._outputDesc = output.Description;
                this._width = this._outputDesc.DesktopBounds.Right - this._outputDesc.DesktopBounds.Left;
                this._height = this._outputDesc.DesktopBounds.Bottom - this._outputDesc.DesktopBounds.Top;
                this._textureDesc = new Texture2DDescription()
                {
                    CpuAccessFlags = CpuAccessFlags.Read,
                    BindFlags = BindFlags.None,
                    Format = Format.B8G8R8A8_UNorm,
                    Width = this._width,
                    Height = this._height,
                    OptionFlags = ResourceOptionFlags.None,
                    MipLevels = 1,
                    ArraySize = 1,
                    SampleDescription = { Count = 1, Quality = 0 },
                    Usage = ResourceUsage.Staging
                };
                this._outputDublication = output1.DuplicateOutput(this._device);

                //Текстура

                this._desktopTexture = new Texture2D(this._device, this._textureDesc);
            }
            catch(SharpDXException sdxex)
            {
                if (sdxex.ResultCode.Code == SharpDX.DXGI.ResultCode.NotCurrentlyAvailable.Result.Code)
                {
                    throw new ScreenDublicatorException("Достигнут предел приложений, работающих с API)");
                }
                else
                {
                    string message = String.Format("Не удалось создать дублирующий выход");
                    Debug.WriteLine(message + "\n{0}\n{1}", sdxex.Message, sdxex.StackTrace);
                    throw new ScreenDublicatorException(message);
                }
            }
            catch(Exception ex)
            {
                string message = String.Format("Ошибка при инициализации объекта\n{0}\n{1}", ex.Message, ex.StackTrace);
                throw new ScreenDublicatorException(message);
            }
            finally
            {
                if(adapter != null) { adapter.Dispose(); }
                if(output != null) { output.Dispose(); }
                if(output1 != null) { output1.Dispose(); }
            }
        }
示例#30
0
        /// <summary>
        ///     Duplicates the output of the specified monitor on the specified graphics adapter.
        /// </summary>
        /// <param name="whichGraphicsCardAdapter">The adapter which contains the desired outputs.</param>
        /// <param name="whichOutputDevice">
        ///     The output device to duplicate (i.e. monitor). Begins with zero, which seems to
        ///     correspond to the primary monitor.
        /// </param>
        public DesktopDuplicator()
        {
            Adapter1 adapter;

            try
            {
                adapter = GetBestAdapter(out int bestAdapaterIndex);
                if (adapter == null)
                {
                    throw new SharpDXException();
                }
                Console.WriteLine($"Using the {adapter.Description.Description} for screen share.");
            }
            catch (SharpDXException)
            {
                ScreenData.CanUseGpuAcceleration = false;
                throw new DesktopDuplicationException("Could not find the specified graphics card adapter.");
            }
            DeviceCreationFlags flags = DeviceCreationFlags.BgraSupport;

            _mDevice = new Device(adapter, flags, FeatureLevel.Level_11_0);
            Output output;

            try
            {
                output = adapter.GetOutput(0);
            }
            catch (SharpDXException)
            {
                ScreenData.CanUseGpuAcceleration = false;
                throw new DesktopDuplicationException("Could not find the specified output device.");
            }
            var output1 = output.QueryInterface <Output1>();

            _mOutputDesc  = output.Description;
            _mTextureDesc = new Texture2DDescription
            {
                CpuAccessFlags    = CpuAccessFlags.Read,
                BindFlags         = BindFlags.None,
                Format            = Format.B8G8R8A8_UNorm,
                Width             = ((Rectangle)_mOutputDesc.DesktopBounds).Width,
                Height            = ((Rectangle)_mOutputDesc.DesktopBounds).Height,
                OptionFlags       = ResourceOptionFlags.None,
                MipLevels         = 1,
                ArraySize         = 1,
                SampleDescription = { Count = 1, Quality = 0 },
                Usage             = ResourceUsage.Staging
            };

            try
            {
                _mDeskDupl = output1.DuplicateOutput(_mDevice);
            }
            catch (SharpDXException ex)
            {
                if (ex.ResultCode.Code == ResultCode.NotCurrentlyAvailable.Result.Code)
                {
                    throw new DesktopDuplicationException(
                              "There is already the maximum number of applications using the Desktop Duplication API running, please close one of the applications and try again.");
                }
            }
        }
示例#31
0
        public Pipeline CreateDistortionGradientShiftPipeline(ResourceLayout[] resourceLayouts, ShaderSetDescription shaderSetDescription)
        {
            var outputDescription = new OutputDescription(null, new OutputAttachmentDescription(PixelFormat.R32_G32_Float));

            return(CreateAPipeline(resourceLayouts, shaderSetDescription, outputDescription, BlendStateDescription.SingleOverrideBlend, false));
        }
示例#32
0
        public VkPipeline(VkGraphicsDevice gd, ref GraphicsPipelineDescription description)
            : base(ref description)
        {
            _gd = gd;
            IsComputePipeline = false;
            RefCount          = new ResourceRefCount(DisposeCore);

            VkGraphicsPipelineCreateInfo pipelineCI = VkGraphicsPipelineCreateInfo.New();

            // Blend State
            VkPipelineColorBlendStateCreateInfo blendStateCI = VkPipelineColorBlendStateCreateInfo.New();
            int attachmentsCount = description.BlendState.AttachmentStates.Length;
            VkPipelineColorBlendAttachmentState *attachmentsPtr
                = stackalloc VkPipelineColorBlendAttachmentState[attachmentsCount];

            for (int i = 0; i < attachmentsCount; i++)
            {
                BlendAttachmentDescription          vdDesc          = description.BlendState.AttachmentStates[i];
                VkPipelineColorBlendAttachmentState attachmentState = new VkPipelineColorBlendAttachmentState();
                attachmentState.srcColorBlendFactor = VkFormats.VdToVkBlendFactor(vdDesc.SourceColorFactor);
                attachmentState.dstColorBlendFactor = VkFormats.VdToVkBlendFactor(vdDesc.DestinationColorFactor);
                attachmentState.colorBlendOp        = VkFormats.VdToVkBlendOp(vdDesc.ColorFunction);
                attachmentState.srcAlphaBlendFactor = VkFormats.VdToVkBlendFactor(vdDesc.SourceAlphaFactor);
                attachmentState.dstAlphaBlendFactor = VkFormats.VdToVkBlendFactor(vdDesc.DestinationAlphaFactor);
                attachmentState.alphaBlendOp        = VkFormats.VdToVkBlendOp(vdDesc.AlphaFunction);
                attachmentState.blendEnable         = vdDesc.BlendEnabled;
                attachmentState.colorWriteMask      = VkColorComponentFlags.R | VkColorComponentFlags.G | VkColorComponentFlags.B | VkColorComponentFlags.A;
                attachmentsPtr[i] = attachmentState;
            }

            blendStateCI.attachmentCount = (uint)attachmentsCount;
            blendStateCI.pAttachments    = attachmentsPtr;
            RgbaFloat blendFactor = description.BlendState.BlendFactor;

            blendStateCI.blendConstants_0 = blendFactor.R;
            blendStateCI.blendConstants_1 = blendFactor.G;
            blendStateCI.blendConstants_2 = blendFactor.B;
            blendStateCI.blendConstants_3 = blendFactor.A;

            pipelineCI.pColorBlendState = &blendStateCI;

            // Rasterizer State
            RasterizerStateDescription             rsDesc = description.RasterizerState;
            VkPipelineRasterizationStateCreateInfo rsCI   = VkPipelineRasterizationStateCreateInfo.New();

            rsCI.cullMode         = VkFormats.VdToVkCullMode(rsDesc.CullMode);
            rsCI.polygonMode      = VkFormats.VdToVkPolygonMode(rsDesc.FillMode);
            rsCI.depthClampEnable = !rsDesc.DepthClipEnabled;
            rsCI.frontFace        = rsDesc.FrontFace == FrontFace.Clockwise ? VkFrontFace.Clockwise : VkFrontFace.CounterClockwise;
            rsCI.lineWidth        = 1f;

            pipelineCI.pRasterizationState = &rsCI;

            ScissorTestEnabled = rsDesc.ScissorTestEnabled;

            // Dynamic State
            VkPipelineDynamicStateCreateInfo dynamicStateCI = VkPipelineDynamicStateCreateInfo.New();
            VkDynamicState *dynamicStates = stackalloc VkDynamicState[2];

            dynamicStates[0] = VkDynamicState.Viewport;
            dynamicStates[1] = VkDynamicState.Scissor;
            dynamicStateCI.dynamicStateCount = 2;
            dynamicStateCI.pDynamicStates    = dynamicStates;

            pipelineCI.pDynamicState = &dynamicStateCI;

            // Depth Stencil State
            DepthStencilStateDescription          vdDssDesc = description.DepthStencilState;
            VkPipelineDepthStencilStateCreateInfo dssCI     = VkPipelineDepthStencilStateCreateInfo.New();

            dssCI.depthWriteEnable  = vdDssDesc.DepthWriteEnabled;
            dssCI.depthTestEnable   = vdDssDesc.DepthTestEnabled;
            dssCI.depthCompareOp    = VkFormats.VdToVkCompareOp(vdDssDesc.DepthComparison);
            dssCI.stencilTestEnable = vdDssDesc.StencilTestEnabled;

            dssCI.front.failOp      = VkFormats.VdToVkStencilOp(vdDssDesc.StencilFront.Fail);
            dssCI.front.passOp      = VkFormats.VdToVkStencilOp(vdDssDesc.StencilFront.Pass);
            dssCI.front.depthFailOp = VkFormats.VdToVkStencilOp(vdDssDesc.StencilFront.DepthFail);
            dssCI.front.compareOp   = VkFormats.VdToVkCompareOp(vdDssDesc.StencilFront.Comparison);
            dssCI.front.compareMask = vdDssDesc.StencilReadMask;
            dssCI.front.writeMask   = vdDssDesc.StencilWriteMask;
            dssCI.front.reference   = vdDssDesc.StencilReference;

            dssCI.back.failOp      = VkFormats.VdToVkStencilOp(vdDssDesc.StencilBack.Fail);
            dssCI.back.passOp      = VkFormats.VdToVkStencilOp(vdDssDesc.StencilBack.Pass);
            dssCI.back.depthFailOp = VkFormats.VdToVkStencilOp(vdDssDesc.StencilBack.DepthFail);
            dssCI.back.compareOp   = VkFormats.VdToVkCompareOp(vdDssDesc.StencilBack.Comparison);
            dssCI.back.compareMask = vdDssDesc.StencilReadMask;
            dssCI.back.writeMask   = vdDssDesc.StencilWriteMask;
            dssCI.back.reference   = vdDssDesc.StencilReference;

            pipelineCI.pDepthStencilState = &dssCI;

            // Multisample
            VkPipelineMultisampleStateCreateInfo multisampleCI = VkPipelineMultisampleStateCreateInfo.New();
            VkSampleCountFlags vkSampleCount = VkFormats.VdToVkSampleCount(description.Outputs.SampleCount);

            multisampleCI.rasterizationSamples  = vkSampleCount;
            multisampleCI.alphaToCoverageEnable = description.BlendState.AlphaToCoverageEnabled;

            pipelineCI.pMultisampleState = &multisampleCI;

            // Input Assembly
            VkPipelineInputAssemblyStateCreateInfo inputAssemblyCI = VkPipelineInputAssemblyStateCreateInfo.New();

            inputAssemblyCI.topology = VkFormats.VdToVkPrimitiveTopology(description.PrimitiveTopology);

            pipelineCI.pInputAssemblyState = &inputAssemblyCI;

            // Vertex Input State
            VkPipelineVertexInputStateCreateInfo vertexInputCI = VkPipelineVertexInputStateCreateInfo.New();

            VertexLayoutDescription[] inputDescriptions = description.ShaderSet.VertexLayouts;
            uint bindingCount   = (uint)inputDescriptions.Length;
            uint attributeCount = 0;

            for (int i = 0; i < inputDescriptions.Length; i++)
            {
                attributeCount += (uint)inputDescriptions[i].Elements.Length;
            }
            VkVertexInputBindingDescription *  bindingDescs   = stackalloc VkVertexInputBindingDescription[(int)bindingCount];
            VkVertexInputAttributeDescription *attributeDescs = stackalloc VkVertexInputAttributeDescription[(int)attributeCount];

            int targetIndex    = 0;
            int targetLocation = 0;

            for (int binding = 0; binding < inputDescriptions.Length; binding++)
            {
                VertexLayoutDescription inputDesc = inputDescriptions[binding];
                bindingDescs[binding] = new VkVertexInputBindingDescription()
                {
                    binding   = (uint)binding,
                    inputRate = (inputDesc.InstanceStepRate != 0) ? VkVertexInputRate.Instance : VkVertexInputRate.Vertex,
                    stride    = inputDesc.Stride
                };

                uint currentOffset = 0;
                for (int location = 0; location < inputDesc.Elements.Length; location++)
                {
                    VertexElementDescription inputElement = inputDesc.Elements[location];

                    attributeDescs[targetIndex] = new VkVertexInputAttributeDescription()
                    {
                        format   = VkFormats.VdToVkVertexElementFormat(inputElement.Format),
                        binding  = (uint)binding,
                        location = (uint)(targetLocation + location),
                        offset   = inputElement.Offset != 0 ? inputElement.Offset : currentOffset
                    };

                    targetIndex   += 1;
                    currentOffset += FormatHelpers.GetSizeInBytes(inputElement.Format);
                }

                targetLocation += inputDesc.Elements.Length;
            }

            vertexInputCI.vertexBindingDescriptionCount   = bindingCount;
            vertexInputCI.pVertexBindingDescriptions      = bindingDescs;
            vertexInputCI.vertexAttributeDescriptionCount = attributeCount;
            vertexInputCI.pVertexAttributeDescriptions    = attributeDescs;

            pipelineCI.pVertexInputState = &vertexInputCI;

            // Shader Stage

            VkSpecializationInfo specializationInfo;

            SpecializationConstant[] specDescs = description.ShaderSet.Specializations;
            if (specDescs != null)
            {
                uint specDataSize = 0;
                foreach (SpecializationConstant spec in specDescs)
                {
                    specDataSize += VkFormats.GetSpecializationConstantSize(spec.Type);
                }
                byte *fullSpecData                   = stackalloc byte[(int)specDataSize];
                int   specializationCount            = specDescs.Length;
                VkSpecializationMapEntry *mapEntries = stackalloc VkSpecializationMapEntry[specializationCount];
                uint specOffset = 0;
                for (int i = 0; i < specializationCount; i++)
                {
                    ulong data     = specDescs[i].Data;
                    byte *srcData  = (byte *)&data;
                    uint  dataSize = VkFormats.GetSpecializationConstantSize(specDescs[i].Type);
                    Unsafe.CopyBlock(fullSpecData + specOffset, srcData, dataSize);
                    mapEntries[i].constantID = specDescs[i].ID;
                    mapEntries[i].offset     = specOffset;
                    mapEntries[i].size       = (UIntPtr)dataSize;
                    specOffset += dataSize;
                }
                specializationInfo.dataSize      = (UIntPtr)specDataSize;
                specializationInfo.pData         = fullSpecData;
                specializationInfo.mapEntryCount = (uint)specializationCount;
                specializationInfo.pMapEntries   = mapEntries;
            }

            Shader[] shaders = description.ShaderSet.Shaders;
            StackList <VkPipelineShaderStageCreateInfo> stages = new StackList <VkPipelineShaderStageCreateInfo>();

            foreach (Shader shader in shaders)
            {
                VkShader vkShader = Util.AssertSubtype <Shader, VkShader>(shader);
                VkPipelineShaderStageCreateInfo stageCI = VkPipelineShaderStageCreateInfo.New();
                stageCI.module = vkShader.ShaderModule;
                stageCI.stage  = VkFormats.VdToVkShaderStages(shader.Stage);
                // stageCI.pName = CommonStrings.main; // Meh
                stageCI.pName = new FixedUtf8String(shader.EntryPoint); // TODO: DONT ALLOCATE HERE
                stageCI.pSpecializationInfo = &specializationInfo;
                stages.Add(stageCI);
            }

            pipelineCI.stageCount = stages.Count;
            pipelineCI.pStages    = (VkPipelineShaderStageCreateInfo *)stages.Data;

            // ViewportState
            VkPipelineViewportStateCreateInfo viewportStateCI = VkPipelineViewportStateCreateInfo.New();

            viewportStateCI.viewportCount = 1;
            viewportStateCI.scissorCount  = 1;

            pipelineCI.pViewportState = &viewportStateCI;

            // Pipeline Layout
            ResourceLayout[]           resourceLayouts  = description.ResourceLayouts;
            VkPipelineLayoutCreateInfo pipelineLayoutCI = VkPipelineLayoutCreateInfo.New();

            pipelineLayoutCI.setLayoutCount = (uint)resourceLayouts.Length;
            VkDescriptorSetLayout *dsls = stackalloc VkDescriptorSetLayout[resourceLayouts.Length];

            for (int i = 0; i < resourceLayouts.Length; i++)
            {
                dsls[i] = Util.AssertSubtype <ResourceLayout, VkResourceLayout>(resourceLayouts[i]).DescriptorSetLayout;
            }
            pipelineLayoutCI.pSetLayouts = dsls;

            vkCreatePipelineLayout(_gd.Device, ref pipelineLayoutCI, null, out _pipelineLayout);
            pipelineCI.layout = _pipelineLayout;

            // Create fake RenderPass for compatibility.

            VkRenderPassCreateInfo renderPassCI = VkRenderPassCreateInfo.New();
            OutputDescription      outputDesc   = description.Outputs;
            StackList <VkAttachmentDescription, Size512Bytes> attachments = new StackList <VkAttachmentDescription, Size512Bytes>();

            // TODO: A huge portion of this next part is duplicated in VkFramebuffer.cs.

            StackList <VkAttachmentDescription> colorAttachmentDescs = new StackList <VkAttachmentDescription>();
            StackList <VkAttachmentReference>   colorAttachmentRefs  = new StackList <VkAttachmentReference>();

            for (uint i = 0; i < outputDesc.ColorAttachments.Length; i++)
            {
                colorAttachmentDescs[i].format         = VkFormats.VdToVkPixelFormat(outputDesc.ColorAttachments[i].Format);
                colorAttachmentDescs[i].samples        = vkSampleCount;
                colorAttachmentDescs[i].loadOp         = VkAttachmentLoadOp.DontCare;
                colorAttachmentDescs[i].storeOp        = VkAttachmentStoreOp.Store;
                colorAttachmentDescs[i].stencilLoadOp  = VkAttachmentLoadOp.DontCare;
                colorAttachmentDescs[i].stencilStoreOp = VkAttachmentStoreOp.DontCare;
                colorAttachmentDescs[i].initialLayout  = VkImageLayout.Undefined;
                colorAttachmentDescs[i].finalLayout    = VkImageLayout.ShaderReadOnlyOptimal;
                attachments.Add(colorAttachmentDescs[i]);

                colorAttachmentRefs[i].attachment = i;
                colorAttachmentRefs[i].layout     = VkImageLayout.ColorAttachmentOptimal;
            }

            VkAttachmentDescription depthAttachmentDesc = new VkAttachmentDescription();
            VkAttachmentReference   depthAttachmentRef  = new VkAttachmentReference();

            if (outputDesc.DepthAttachment != null)
            {
                PixelFormat depthFormat = outputDesc.DepthAttachment.Value.Format;
                bool        hasStencil  = FormatHelpers.IsStencilFormat(depthFormat);
                depthAttachmentDesc.format         = VkFormats.VdToVkPixelFormat(outputDesc.DepthAttachment.Value.Format, toDepthFormat: true);
                depthAttachmentDesc.samples        = vkSampleCount;
                depthAttachmentDesc.loadOp         = VkAttachmentLoadOp.DontCare;
                depthAttachmentDesc.storeOp        = VkAttachmentStoreOp.Store;
                depthAttachmentDesc.stencilLoadOp  = VkAttachmentLoadOp.DontCare;
                depthAttachmentDesc.stencilStoreOp = hasStencil ? VkAttachmentStoreOp.Store : VkAttachmentStoreOp.DontCare;
                depthAttachmentDesc.initialLayout  = VkImageLayout.Undefined;
                depthAttachmentDesc.finalLayout    = VkImageLayout.DepthStencilAttachmentOptimal;

                depthAttachmentRef.attachment = (uint)outputDesc.ColorAttachments.Length;
                depthAttachmentRef.layout     = VkImageLayout.DepthStencilAttachmentOptimal;
            }

            VkSubpassDescription subpass = new VkSubpassDescription();

            subpass.pipelineBindPoint    = VkPipelineBindPoint.Graphics;
            subpass.colorAttachmentCount = (uint)outputDesc.ColorAttachments.Length;
            subpass.pColorAttachments    = (VkAttachmentReference *)colorAttachmentRefs.Data;
            for (int i = 0; i < colorAttachmentDescs.Count; i++)
            {
                attachments.Add(colorAttachmentDescs[i]);
            }

            if (outputDesc.DepthAttachment != null)
            {
                subpass.pDepthStencilAttachment = &depthAttachmentRef;
                attachments.Add(depthAttachmentDesc);
            }

            VkSubpassDependency subpassDependency = new VkSubpassDependency();

            subpassDependency.srcSubpass    = SubpassExternal;
            subpassDependency.srcStageMask  = VkPipelineStageFlags.ColorAttachmentOutput;
            subpassDependency.dstStageMask  = VkPipelineStageFlags.ColorAttachmentOutput;
            subpassDependency.dstAccessMask = VkAccessFlags.ColorAttachmentRead | VkAccessFlags.ColorAttachmentWrite;

            renderPassCI.attachmentCount = attachments.Count;
            renderPassCI.pAttachments    = (VkAttachmentDescription *)attachments.Data;
            renderPassCI.subpassCount    = 1;
            renderPassCI.pSubpasses      = &subpass;
            renderPassCI.dependencyCount = 1;
            renderPassCI.pDependencies   = &subpassDependency;

            VkResult creationResult = vkCreateRenderPass(_gd.Device, ref renderPassCI, null, out _renderPass);

            CheckResult(creationResult);

            pipelineCI.renderPass = _renderPass;

            VkResult result = vkCreateGraphicsPipelines(_gd.Device, VkPipelineCache.Null, 1, ref pipelineCI, null, out _devicePipeline);

            CheckResult(result);

            ResourceSetCount    = (uint)description.ResourceLayouts.Length;
            DynamicOffsetsCount = 0;
            foreach (VkResourceLayout layout in description.ResourceLayouts)
            {
                DynamicOffsetsCount += layout.DynamicBufferCount;
            }
        }
示例#33
0
 public Pipeline CreateDistortionRenderPipeline(ResourceLayout[] resourceLayouts, ShaderSetDescription shaderSetDescription, OutputDescription outputDescription)
 {
     return(CreateNonDepthTestAlphaBlendPipeline(resourceLayouts, shaderSetDescription, outputDescription));
 }
示例#34
0
        public void CreateDeviceResources(GraphicsDevice gd, OutputDescription outputDescription)
        {
            _gd = gd;
            ResourceFactory factory = gd.ResourceFactory;

            _vertexBuffer      = factory.CreateBuffer(new BufferDescription(10000, BufferUsage.VertexBuffer | BufferUsage.Dynamic));
            _vertexBuffer.Name = "ImGui.NET Vertex Buffer";
            _indexBuffer       = factory.CreateBuffer(new BufferDescription(2000, BufferUsage.IndexBuffer | BufferUsage.Dynamic));
            _indexBuffer.Name  = "ImGui.NET Index Buffer";
            RecreateFontDeviceTexture(gd);

            _projMatrixBuffer      = factory.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer | BufferUsage.Dynamic));
            _projMatrixBuffer.Name = "ImGui.NET Projection Buffer";

            string fragment =
                @"#version 330 core

uniform sampler2D FontTexture;

in vec4 color;
in vec2 texCoord;

out vec4 outputColor;

void main()
{
    outputColor = color * texture(FontTexture, texCoord);
}
";
            string vertex =
                @"#version 330 core

uniform ProjectionMatrixBuffer
{
    mat4 projection_matrix;
};

in vec2 in_position;
in vec2 in_texCoord;
in vec4 in_color;

out vec4 color;
out vec2 texCoord;

void main()
{
    gl_Position = projection_matrix * vec4(in_position, 0, 1);
    color = in_color;
	texCoord = in_texCoord;
}";

            byte[] vertexShaderBytes   = System.Text.Encoding.UTF8.GetBytes(vertex);
            byte[] fragmentShaderBytes = System.Text.Encoding.UTF8.GetBytes(fragment);
            _vertexShader   = factory.CreateShader(new ShaderDescription(ShaderStages.Vertex, vertexShaderBytes, "VS"));
            _fragmentShader = factory.CreateShader(new ShaderDescription(ShaderStages.Fragment, fragmentShaderBytes, "FS"));

            VertexLayoutDescription[] vertexLayouts = new VertexLayoutDescription[]
            {
                new VertexLayoutDescription(
                    new VertexElementDescription("in_position", VertexElementSemantic.Position, VertexElementFormat.Float2),
                    new VertexElementDescription("in_texCoord", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2),
                    new VertexElementDescription("in_color", VertexElementSemantic.Color, VertexElementFormat.Byte4_Norm))
            };

            _layout = factory.CreateResourceLayout(new ResourceLayoutDescription(
                                                       new ResourceLayoutElementDescription("ProjectionMatrixBuffer", ResourceKind.UniformBuffer, ShaderStages.Vertex),
                                                       new ResourceLayoutElementDescription("MainSampler", ResourceKind.Sampler, ShaderStages.Fragment)));
            _textureLayout = factory.CreateResourceLayout(new ResourceLayoutDescription(
                                                              new ResourceLayoutElementDescription("MainTexture", ResourceKind.TextureReadOnly, ShaderStages.Fragment)));

            GraphicsPipelineDescription pd = new GraphicsPipelineDescription(
                BlendStateDescription.SingleAlphaBlend,
                new DepthStencilStateDescription(false, false, ComparisonKind.Always),
                new RasterizerStateDescription(FaceCullMode.None, PolygonFillMode.Solid, FrontFace.Clockwise, false, true),
                PrimitiveTopology.TriangleList,
                new ShaderSetDescription(vertexLayouts, new[] { _vertexShader, _fragmentShader }),
                new[] { _layout, _textureLayout },
                outputDescription);

            _pipeline = factory.CreateGraphicsPipeline(ref pd);

            _mainResourceSet = factory.CreateResourceSet(new ResourceSetDescription(_layout,
                                                                                    _projMatrixBuffer,
                                                                                    gd.PointSampler));

            _fontTextureResourceSet = factory.CreateResourceSet(new ResourceSetDescription(_textureLayout, _fontTextureView));
        }
示例#35
0
        public void CreateAllDrawingPipelines(ResourceLayout[] resourceLayouts, ShaderSetDescription shaderSetDescription, OutputDescription outputDescription)
        {
            _drawingPipelines = new Dictionary <BlendState, Pipeline>();

            var states = Enum.GetValues(typeof(BlendState));

            foreach (BlendState state in states)
            {
                _drawingPipelines.Add(state, CreateAPipeline(resourceLayouts, shaderSetDescription, outputDescription, _blendStateConverter.Convert(state), true));
            }
        }