public MyHardwareOcclusionQuery()
 {
     QueryDescription queryDesc;
     queryDesc.Flags = QueryFlags.None;
     queryDesc.Type = QueryType.Occlusion;
     m_query = new Query(MyRender11.Device, queryDesc);
 }
            public SwapBuffer(IntSize size, Vector dpi)
            {
                int width  = (int)size.Width;
                int height = (int)size.Height;

                _event = new Query(s_dxDevice, new QueryDescription {
                    Type = QueryType.Event
                });
                using (var texture = new Texture2D(s_dxDevice, new Texture2DDescription
                {
                    Width = width,
                    Height = height,
                    ArraySize = 1,
                    MipLevels = 1,
                    Format = Format.B8G8R8A8_UNorm,
                    Usage = ResourceUsage.Default,
                    SampleDescription = new SampleDescription(2, 0),
                    BindFlags = BindFlags.RenderTarget,
                }))
                    using (var surface = texture.QueryInterface <Surface>())

                    {
                        _resource = texture.QueryInterface <SharpDX.Direct3D11.Resource>();

                        Target = new RenderTarget(AvaloniaLocator.Current.GetService <SharpDX.Direct2D1.Factory>(), surface,
                                                  new RenderTargetProperties
                        {
                            DpiX        = (float)dpi.X,
                            DpiY        = (float)dpi.Y,
                            MinLevel    = FeatureLevel.Level_10,
                            PixelFormat = new PixelFormat(Format.B8G8R8A8_UNorm, AlphaMode.Premultiplied),
                        });
                    }
                using (var texture = new Texture2D(s_dxDevice, new Texture2DDescription
                {
                    Width = width,
                    Height = height,
                    ArraySize = 1,
                    MipLevels = 1,
                    Format = Format.B8G8R8A8_UNorm,
                    Usage = ResourceUsage.Default,
                    SampleDescription = new SampleDescription(1, 0),
                    BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource,
                    OptionFlags = ResourceOptionFlags.Shared,
                }))
                    using (var resource = texture.QueryInterface <SharpDX.DXGI.Resource>())
                    {
                        _sharedResource = texture.QueryInterface <SharpDX.Direct3D11.Resource>();
                        var handle = resource.SharedHandle;
                        using (var texture9 = new Texture(s_d3DDevice, texture.Description.Width,
                                                          texture.Description.Height, 1,
                                                          Usage.RenderTarget, SharpDX.Direct3D9.Format.A8R8G8B8, Pool.Default, ref handle))
                            Texture = texture9.GetSurfaceLevel(0);
                    }
                Size = size;
            }
Example #3
0
        public SyncQuery()
        {
            var desc = new QueryDescription
            {
                Type  = QueryType.Event,
                Flags = QueryFlags.None
            };

            query = new SharpDX.Direct3D11.Query(Device.Get().Handle, desc);
        }
Example #4
0
        private void PlatformConstruct()
        {
            //if (graphicsDevice._d3dDevice.FeatureLevel == SharpDX.Direct3D.FeatureLevel.Level_9_1)
            //    throw new NotSupportedException("The Reach profile does not support occlusion queries.");

            var queryDescription = new QueryDescription
            {
                Flags = QueryFlags.None,
                Type = QueryType.Occlusion
            };
            _query = new Query(GraphicsDevice._d3dDevice, queryDescription);
        }
Example #5
0
        internal void LazyInit(QueryType type)
        {
            if(m_query == null)
            {
                Debug.Assert(!m_type.HasValue);

                m_type = type;

                var desc = new QueryDescription();
                desc.Type = type;
                m_query = new Query(MyRender11.Device, desc);
            }
        }
Example #6
0
        public GpuTimer()
        {
            startHandle = new SharpDX.Direct3D11.Query(Device.Get().Handle, new QueryDescription
            {
                Flags = QueryFlags.None,
                Type  = QueryType.Timestamp
            });

            endHandle = new SharpDX.Direct3D11.Query(Device.Get().Handle, new QueryDescription
            {
                Flags = QueryFlags.None,
                Type  = QueryType.Timestamp
            });

            disjointHandle = new SharpDX.Direct3D11.Query(Device.Get().Handle, new QueryDescription
            {
                Flags = QueryFlags.None,
                Type  = QueryType.TimestampDisjoint
            });
        }
Example #7
0
        public void Bind(Renderer renderer)
        {
            if (renderer.ActiveRenderTarget != _lastRenderTarget.Get(renderer))
            {
                _lastRenderTarget.Set(renderer, renderer.ActiveRenderTarget);
            }

            renderer.ActiveRenderTarget = this;

            SharpDX.Direct3D11.Buffer gpuBuffer = _gpuBuffer.Get(renderer);
            if (gpuBuffer == null)
            {
                BufferDescription bufferDesc = new BufferDescription();
                bufferDesc.Usage       = ResourceUsage.Default;
                bufferDesc.SizeInBytes = _size;
                bufferDesc.BindFlags   = BindFlags.StreamOutput;

                gpuBuffer = new SharpDX.Direct3D11.Buffer(renderer.Device, bufferDesc);
                _gpuBuffer.Set(renderer, gpuBuffer, _size);
            }

            Query query = _query.Get(renderer);

            if (query == null)
            {
                QueryDescription queryDesc = new QueryDescription();
                queryDesc.Flags = QueryFlags.None;
                queryDesc.Type  = QueryType.StreamOutputStatistics;
                query           = new SharpDX.Direct3D11.Query(renderer.Device, queryDesc);

                _query.Set(renderer, query);
            }

            NumPrimitivesWritten    = 0;
            PrimitivesStorageNeeded = 0;
            renderer.DeviceContext.Begin(query);

            renderer.DeviceContext.StreamOutput.SetTarget(gpuBuffer, 0);
        }
Example #8
0
        public void StartProfile(String name)
        {
            // set the name of the profiling
            Name = name;

            QueryDescription desc = new QueryDescription();
            desc.Flags = QueryFlags.None;
            desc.Type = QueryType.TimestampDisjoint;
            DisjointQuery = new Query(Engine.g_device, desc);

            desc.Flags = QueryFlags.None;
            desc.Type = QueryType.Timestamp;
            TimestampStartQuery = new Query(Engine.g_device, desc);
            TimestampEndQuery = new Query(Engine.g_device, desc);

            // Start a disjoint query first
            Engine.g_device.ImmediateContext.Begin(DisjointQuery);

            // Insert the start timestamp
            Engine.g_device.ImmediateContext.Begin(TimestampStartQuery);

            QueryStarted = true;
        }
Example #9
0
        /// <summary>
        /// Initializes a new instance of the <see cref="OcclusionQuery" /> class.
        /// </summary>
        public OcclusionQuery(GraphicsDevice graphicsDevice)
        {
            if (graphicsDevice.Features.Level == SharpDX.Direct3D.FeatureLevel.Level_9_1)
            {
                // Occlusion queries are not supported on Level_9_1: http://msdn.microsoft.com/en-us/library/windows/desktop/ff476150(v=vs.85).aspx
                throw new NotSupportedException(graphicsDevice.Features.Level + " does not support occlusion querying");
            }

            try
            {
                d3dQuery = ToDispose(
                    new Query(
                        graphicsDevice,
                        new QueryDescription
                        {
                            Type = QueryType.Occlusion,
                            Flags = QueryFlags.None
                        }));
            }
            catch
            {
                throw new NotSupportedException("This device does not support occlusion querying");
            }
        }
Example #10
0
        static void Main()
        {
            if (!SharpDevice.IsDirectX11Supported())
            {
                System.Windows.Forms.MessageBox.Show("DirectX11 Not Supported");
                return;
            }

            //render form
            RenderForm form = new RenderForm();
            form.Text = "Tutorial 17: Query";
            //frame rate counter
            SharpFPS fpsCounter = new SharpFPS();

            using (SharpDevice device = new SharpDevice(form))
            {

                //load model from wavefront obj file
                SharpMesh earth = SharpMesh.CreateFromObj(device, "../../../Models/planets/earth.obj");
                SharpMesh moon = SharpMesh.CreateFromObj(device, "../../../Models/planets/moon.obj");

                //init shader
                SharpShader shader = new SharpShader(device, "../../HLSL.txt",
                    new SharpShaderDescription() { VertexShaderFunction = "VS", PixelShaderFunction = "PS" },
                    new InputElement[] {
                        new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0),
                        new InputElement("NORMAL", 0, Format.R32G32B32_Float, 12, 0),
                        new InputElement("TEXCOORD", 0, Format.R32G32_Float, 24, 0)
                    });

                //init constant buffer
                Buffer11 buffer = shader.CreateBuffer<Data>();

                Query pipelineQuery = new Query(device.Device, new QueryDescription() { Flags = QueryFlags.None, Type = QueryType.PipelineStatistics });

                QueryDataPipelineStatistics stats = new QueryDataPipelineStatistics();

                //init frame counter
                fpsCounter.Reset();

                int lastX = 0;
                float currentAngle = 50;
                form.MouseMove += (sender, e) =>
                {
                    if (e.Button == MouseButtons.Left)
                    {
                        currentAngle += (lastX - e.X);
                    }
                    lastX = e.X;
                };

                //main loop
                RenderLoop.Run(form, () =>
                {
                    //Resizing
                    if (device.MustResize)
                    {
                        device.Resize();
                    }

                    //apply states
                    device.UpdateAllStates();

                    //clear color
                    device.Clear(Color.CornflowerBlue);

                    //apply shader
                    shader.Apply();

                    //apply constant buffer to shader
                    device.DeviceContext.VertexShader.SetConstantBuffer(0, buffer);
                    device.DeviceContext.PixelShader.SetConstantBuffer(0, buffer);

                    //set transformation matrix
                    float ratio = (float)form.ClientRectangle.Width / (float)form.ClientRectangle.Height;
                    Matrix projection = Matrix.PerspectiveFovLH(3.14F / 3.0F, ratio, 1F, 1000.0F);
                    Matrix view = Matrix.LookAtLH(new Vector3(0, 0, -250), new Vector3(), Vector3.UnitY);
                    Matrix world = Matrix.Translation(0, 0, 200) * Matrix.RotationY(MathUtil.DegreesToRadians(currentAngle));

                    //light direction
                    Vector3 lightDirection = new Vector3(0.5f, 0, -1);
                    lightDirection.Normalize();

                    Data sceneInformation = new Data()
                    {
                        world = world,
                        worldViewProjection = world * view * projection,
                        lightDirection = new Vector4(lightDirection, 1)
                    };

                    //write data inside constant buffer
                    device.UpdateData<Data>(buffer, sceneInformation);

                    //draw mesh
                    moon.Begin();
                    for (int i = 0; i < moon.SubSets.Count; i++)
                    {
                        device.DeviceContext.PixelShader.SetShaderResource(0, moon.SubSets[i].DiffuseMap);
                        moon.Draw(i);
                    }

                    //begin analizing
                    device.DeviceContext.Begin(pipelineQuery);

                    world = Matrix.RotationY(Environment.TickCount / 2000.0F);
                    sceneInformation = new Data()
                    {
                        world = world,
                        worldViewProjection = world * view * projection,
                        lightDirection = new Vector4(lightDirection, 1)
                    };

                    //write data inside constant buffer
                    device.UpdateData<Data>(buffer, sceneInformation);

                    //draw mesh
                    earth.Begin();
                    for (int i = 0; i < earth.SubSets.Count; i++)
                    {
                        device.DeviceContext.PixelShader.SetShaderResource(0, earth.SubSets[i].DiffuseMap);
                        earth.Draw(i);
                    }
                    //end analizing
                    device.DeviceContext.End(pipelineQuery);

                    //get result

                    while (!device.DeviceContext.GetData<QueryDataPipelineStatistics>(pipelineQuery, AsynchronousFlags.None, out stats))
                    {
                    }

                    //begin drawing text
                    device.Font.Begin();

                    //draw string
                    fpsCounter.Update();
                    device.Font.DrawString("Earth Stats : FPS: " + fpsCounter.FPS, 0, 0);

                    //print earth stats
                    device.Font.DrawString("Earth Stats : Use Mouse to Rotate Moon To Cover Earth ", 0, 30);
                    device.Font.DrawString(string.Format("Primitive Count: {0}", stats.IAPrimitiveCount), 0, 60);
                    device.Font.DrawString(string.Format("Vertex Count Count: {0}", stats.IAVerticeCount), 0, 90);
                    device.Font.DrawString(string.Format("Vertex Shader Execution: {0}", stats.VSInvocationCount), 0, 120);
                    device.Font.DrawString(string.Format("Pixel Shader Execution: {0}", stats.PSInvocationCount), 0, 150);

                    //flush text to view
                    device.Font.End();
                    //present
                    device.Present();

                });

                //release resource
                earth.Dispose();
                moon.Dispose();
                buffer.Dispose();
                pipelineQuery.Dispose();
            }
        }
Example #11
0
 public void Initialize(Device device)
 {
     queryTimeStampDisjoint = new Query(device, new QueryDescription() { Type = QueryType.TimestampDisjoint });
     queryTimeStampStart = new Query(device, new QueryDescription() { Type = QueryType.Timestamp });
     queryTimeStampEnd = new Query(device, new QueryDescription() { Type = QueryType.Timestamp });
 }
Example #12
0
        private void OnRendering()
        {
            if (needsResizing)
            {
                PerformResizing();
            }

            SetAllDeviceStates();
            Clear(Color.CornflowerBlue);

            UpdateViewProjectionBuffers();
            if (Light != null)
            {
                Light.SetLightBuffer();
            }

            var statisticsQuery = new Query(device, new QueryDescription()
            {
                Type = QueryType.PipelineStatistics
            });
            deviceContext.Begin(statisticsQuery);
            #if TEXT_RENDERER
            TextRenderer.BeginDraw();
            #endif
            foreach (var renderable in renderables)
            {
                renderable.Render(this);
            }
            deviceContext.End(statisticsQuery);
            QueryDataPipelineStatistics result;
            while (!deviceContext.GetData(statisticsQuery, out result)) { }
            #if TEXT_RENDERER
            TextRenderer.DrawText("VS Invocations: " + result.VSInvocationCount, new Vector2(0, 50));
            TextRenderer.DrawText("PS Invocations: " + result.PSInvocationCount, new Vector2(0, 75));
            TextRenderer.DrawText("Input Vertices: " + result.IAVerticeCount, new Vector2(0, 100));

            TextRenderer.EndDraw();
            #endif

            swapChain.Present(0, PresentFlags.None);
        }
Example #13
0
 /// <summary>
 /// true if the event is completed
 /// </summary>
 /// <param name="query"></param>
 public bool GetQueryEventData(SharpDX.Direct3D11.Query query)
 {
     return(context.GetData <int>(query, AsynchronousFlags.DoNotFlush) != 0);
 }
Example #14
0
 internal MyOcclusionQuery()
 {
     var desc = new QueryDescription();
     desc.Type = QueryType.Occlusion;
     m_query = new Query(MyRender11.Device, desc);
 }
Example #15
0
        /// <inheritdoc />
        internal override GraphicsPresenter CreateGraphicsPresenter(GraphicsDevice device, PresentationParameters parameters)
        {
            var backbufferDesc = RenderTarget2D.CreateDescription(device,
                                                              parameters.BackBufferWidth,
                                                              parameters.BackBufferHeight,
                                                              Graphics.PixelFormat.B8G8R8A8.UNorm);

            // mandatory to share the surface with D3D9
            backbufferDesc.OptionFlags |= ResourceOptionFlags.Shared;

            RemoveAndDispose(ref presenter);
            RemoveAndDispose(ref queryForCompletion);

            presenter = ToDispose(new RenderTargetGraphicsPresenter(device, backbufferDesc, parameters.DepthStencilFormat, false, true));
            // used to indicate if all drawing operations have completed
            queryForCompletion = ToDispose(new Query(presenter.GraphicsDevice, new QueryDescription { Type = QueryType.Event, Flags = QueryFlags.None }));

            // device context will be used to query drawing operations status
            deviceContext = ((Device)presenter.GraphicsDevice).ImmediateContext;

            if (!element.IsDisposed)
                element.SetBackbuffer(presenter.BackBuffer);

            return presenter;
        }
Example #16
0
 public void EndQuery(SharpDX.Direct3D11.Query query)
 {
     context.End(query);
 }
Example #17
0
        private void EnsureResources(Device device, Texture2DDescription description, Rectangle captureRegion,
            ScreenshotRequest request)
        {
            if (_device != null && request.Resize != null &&
                (_resizedRT == null ||
                 (_resizedRT.Device.NativePointer != _device.NativePointer ||
                  _resizedRT.Description.Width != request.Resize.Value.Width ||
                  _resizedRT.Description.Height != request.Resize.Value.Height)))
            {
                // Create/Recreate resources for resizing
                RemoveAndDispose(ref _resizedRT);
                RemoveAndDispose(ref _resizedRTV);
                RemoveAndDispose(ref _saQuad);

                _resizedRT = ToDispose(new Texture2D(_device, new Texture2DDescription
                {
                    Format = Format.R8G8B8A8_UNorm, // Supports BMP/PNG/etc
                    Height = request.Resize.Value.Height,
                    Width = request.Resize.Value.Width,
                    ArraySize = 1,
                    SampleDescription = new SampleDescription(1, 0),
                    BindFlags = BindFlags.RenderTarget,
                    MipLevels = 1,
                    Usage = ResourceUsage.Default,
                    OptionFlags = ResourceOptionFlags.None
                }));

                _resizedRTV = ToDispose(new RenderTargetView(_device, _resizedRT));

                _saQuad = ToDispose(new ScreenAlignedQuadRenderer());
                _saQuad.Initialize(new DeviceManager(_device));
            }

            // Check if _resolvedRT or _finalRT require creation
            if (_finalRT != null && _finalRT.Device.NativePointer == _device.NativePointer &&
                _finalRT.Description.Height == captureRegion.Height && _finalRT.Description.Width == captureRegion.Width &&
                _resolvedRT != null && _resolvedRT.Description.Height == description.Height &&
                _resolvedRT.Description.Width == description.Width &&
                _resolvedRT.Device.NativePointer == device.NativePointer &&
                _resolvedRT.Description.Format == description.Format
                )
            {
                return;
            }

            RemoveAndDispose(ref _query);
            RemoveAndDispose(ref _resolvedRT);
            RemoveAndDispose(ref _resolvedSharedSRV);
            RemoveAndDispose(ref _finalRT);
            RemoveAndDispose(ref _resolvedRTShared);

            _query = new Query(_device, new QueryDescription
            {
                Flags = QueryFlags.None,
                Type = QueryType.Event
            });
            _queryIssued = false;

            _resolvedRT = ToDispose(new Texture2D(device, new Texture2DDescription
            {
                CpuAccessFlags = CpuAccessFlags.None,
                Format = description.Format, // for multisampled backbuffer, this must be same format
                Height = description.Height,
                Usage = ResourceUsage.Default,
                Width = description.Width,
                ArraySize = 1,
                SampleDescription = new SampleDescription(1, 0), // Ensure single sample
                BindFlags = BindFlags.ShaderResource,
                MipLevels = 1,
                OptionFlags = ResourceOptionFlags.SharedKeyedmutex
            }));

            // Retrieve reference to the keyed mutex
            _resolvedRTKeyedMutex = ToDispose(_resolvedRT.QueryInterfaceOrNull<KeyedMutex>());

            using (var resource = _resolvedRT.QueryInterface<Resource>())
            {
                _resolvedRTShared = ToDispose(_device.OpenSharedResource<Texture2D>(resource.SharedHandle));
                _resolvedRTKeyedMutex_Dev2 = ToDispose(_resolvedRTShared.QueryInterfaceOrNull<KeyedMutex>());
            }

            // SRV for use if resizing
            _resolvedSharedSRV = ToDispose(new ShaderResourceView(_device, _resolvedRTShared));

            _finalRT = ToDispose(new Texture2D(_device, new Texture2DDescription
            {
                CpuAccessFlags = CpuAccessFlags.Read,
                Format = description.Format,
                Height = captureRegion.Height,
                Usage = ResourceUsage.Staging,
                Width = captureRegion.Width,
                ArraySize = 1,
                SampleDescription = new SampleDescription(1, 0),
                BindFlags = BindFlags.None,
                MipLevels = 1,
                OptionFlags = ResourceOptionFlags.None
            }));
            _finalRTMapped = false;
        }
Example #18
0
        private void PresentFrame11(bool renderToTexture)
        {
            // Update the screen
            if (!renderToTexture)
            {
                FadeFrame();
                NetControl.WaitForNetworkSync();
                RenderContext11.Present(Properties.Settings.Default.FrameSync);

                if (flush)
                {
                    RenderContext11.devContext.Flush();
                    var qd = new QueryDescription();

                    qd.Type = QueryType.Event;


                    query = new Query(RenderContext11.Device, qd);

                    RenderContext11.devContext.End(query);

                    var result = false;
                    var retVal = false;
                    while (!result && !retVal)
                    {
                        var ds = RenderContext11.devContext.GetData(query); 

                        result = ds.ReadBoolean();
                        ds.Close();
                        ds.Dispose();

                    }
                    query.Dispose();
                }
            }

        }