コード例 #1
0
        public override object this[string attribute]
        {
            get
            {
                switch (attribute.ToUpper())
                {
                case "D3DDEVICE":
                    return(D3DDevice);

                case "WINDOW":
                    return(this._windowHandle.Handle);

                case "ISTEXTURE":
                    return(false);

                case "D3DZBUFFER":
                    return(this._device.GetDepthBuffer(this));

                case "DDBACKBUFFER":
                {
                    var ret = new D3D9.Surface[8];
                    ret[0] = this._device.GetBackBuffer(this);
                    return(ret);
                }

                case "DDFRONTBUFFER":
                    return(this._device.GetBackBuffer(this));
                }
                return(new NotSupportedException("There is no D3D9 RenderWindow custom attribute named " + attribute));
            }
        }
コード例 #2
0
ファイル: RenderTarget2D.cs プロジェクト: TormentedEmu/OpenUO
        protected override void OnContextReset(DeviceContext context)
        {
            base.OnContextReset(context);

            if(RecreateOnReset)
                _surface = GetSurfaceLevel(0);
        }
コード例 #3
0
ファイル: D3D9RenderTexture.cs プロジェクト: axiom3d/axiom
        public override object this[string attribute]
        {
            get
            {
                switch (attribute.ToUpper())
                {
                case "DDBACKBUFFER":
                    var surface = new D3D9.Surface[Config.MaxMultipleRenderTargets];
                    if (fsaa > 0)
                    {
                        surface[0] = ((D3D9HardwarePixelBuffer)pixelBuffer).GetFSAASurface(D3D9RenderSystem.ActiveD3D9Device);
                    }
                    else
                    {
                        surface[0] = ((D3D9HardwarePixelBuffer)pixelBuffer).GetSurface(D3D9RenderSystem.ActiveD3D9Device);
                    }

                    return(surface);

                case "HWND":
                    return(null);

                case "BUFFER":
                    return((HardwarePixelBuffer)pixelBuffer);

                default:
                    return(null);
                }
            }
        }
コード例 #4
0
        public void ConstructRenderAndResource(double width, double height)
        {
            float dpiX, dpiY;

            this.GetDpi(out dpiX, out dpiY);
            D2D.RenderTargetProperties prop = new D2D.RenderTargetProperties(
                D2D.RenderTargetType.Default,
                new D2D.PixelFormat(DXGI.Format.B8G8R8A8_UNorm, D2D.AlphaMode.Premultiplied),
                dpiX,
                dpiY,
                D2D.RenderTargetUsage.None,
                D2D.FeatureLevel.Level_DEFAULT);

            D3D11.Texture2DDescription desc = new D3D11.Texture2DDescription();
            desc.Width             = (int)width;
            desc.Height            = (int)height;
            desc.MipLevels         = 1;
            desc.ArraySize         = 1;
            desc.Format            = DXGI.Format.B8G8R8A8_UNorm;
            desc.SampleDescription = new DXGI.SampleDescription(1, 0);
            desc.Usage             = D3D11.ResourceUsage.Default;
            desc.BindFlags         = D3D11.BindFlags.RenderTarget | D3D11.BindFlags.ShaderResource;
            desc.CpuAccessFlags    = D3D11.CpuAccessFlags.None;
            desc.OptionFlags       = D3D11.ResourceOptionFlags.Shared;
            this.d3d11Texture      = new D3D11.Texture2D(this.device, desc);

            this.surface = this.d3d11Texture.QueryInterface <DXGI.Surface>();

            DXGI.Resource resource = this.d3d11Texture.QueryInterface <DXGI.Resource>();
            IntPtr        handel   = resource.SharedHandle;

            D3D9.Texture texture = new D3D9.Texture(
                this.device9,
                this.d3d11Texture.Description.Width,
                this.d3d11Texture.Description.Height,
                1,
                D3D9.Usage.RenderTarget,
                D3D9.Format.A8R8G8B8,
                D3D9.Pool.Default,
                ref handel);
            this.surface9 = texture.GetSurfaceLevel(0);
            resource.Dispose();
            texture.Dispose();

            D2D.BitmapProperties bmpProp = new D2D.BitmapProperties();
            bmpProp.DpiX        = dpiX;
            bmpProp.DpiY        = dpiY;
            bmpProp.PixelFormat = new D2D.PixelFormat(DXGI.Format.B8G8R8A8_UNorm, D2D.AlphaMode.Premultiplied);
            this.bmpd2d         = new D2D.Bitmap(this.render, this.surface, bmpProp);
            this.cachedBitMap   = new D2D.Bitmap(this.render, new Size2((int)width, (int)height), bmpProp);
            this.hasCache       = false;

            this.render.Target = this.bmpd2d;

            this.renderSize = new Size(width, height);
        }
コード例 #5
0
ファイル: RenderTarget2D.cs プロジェクト: TormentedEmu/OpenUO
        protected override void OnContextLost(DeviceContext context)
        {
            base.OnContextLost(context);

            if (_surface != null)
            {
                _surface.Dispose();
                _surface = null;
            }
        }
コード例 #6
0
 public override void BeginRender()
 {
   // Remember current backbuffer and set internal surface as new render target.
   _backbuffer = GraphicsDevice.Device.GetRenderTarget(0);
   _renderTarget = ContentManager.Instance.GetRenderTarget(GLOBAL_RENDER_SURFACE_ASSET_KEY);
   _renderTarget.AllocateRenderTarget(GraphicsDevice.Width, GraphicsDevice.Height);
   _renderRect = new Rectangle(0, 0, GraphicsDevice.Width, GraphicsDevice.Height);
   GraphicsDevice.Device.SetRenderTarget(0, _renderTarget.Surface);
   GraphicsDevice.RenderPass = RenderPassType.SingleOrFirstPass;
   GraphicsDevice.Device.Clear(ClearFlags.Target, Color.Black, 1.0f, 0);
   GraphicsDevice.Device.BeginScene();
 }
コード例 #7
0
    /// <summary>
    /// Constructs a <see cref="TemporaryRenderTarget"/> instance.
    /// </summary>
    /// <param name="renderTargetIndex">Render target index</param>
    /// <param name="targetSurface">Target surface to render on</param>
    public TemporaryRenderTarget(int renderTargetIndex, Surface targetSurface)
    {
      // Select target index (0 by default)
      _renderTargetIndex = renderTargetIndex;

      // Remember old RenderTarget
      _backBuffer = _device.GetRenderTarget(_renderTargetIndex);

      // Get information of new Texture target
      _targetSurface = targetSurface;

      // Set new target
      _device.SetRenderTarget(_renderTargetIndex, _targetSurface);
    }
コード例 #8
0
        SharpDX.Rectangle getVideoDestRect(D3D.Surface backBuffer)
        {
            Rectangle screenRect = new Rectangle(0, 0, backBuffer.Description.Width, backBuffer.Description.Height);
            Rectangle videoRect  = calcOutputAspectRatio(new Rectangle(0, 0, videoWidth, videoHeight));

            Rectangle scaledVideo = Utils.stretchRectangle(videoRect, screenRect);

            Rectangle scaledCenteredVideo = Utils.centerRectangle(screenRect, scaledVideo);

            SharpDX.Rectangle scaledCenteredVideoDx = new SharpDX.Rectangle(scaledCenteredVideo.X,
                                                                            scaledCenteredVideo.Y, scaledCenteredVideo.Width, scaledCenteredVideo.Height);

            return(scaledCenteredVideoDx);
        }
コード例 #9
0
        /// <summary>
        /// Sets the render target of this D3DImage object.
        /// </summary>
        /// <param name="renderTarget">The render target to set.</param>
        public void SetRenderTarget(D3D11.Texture2D renderTarget)
        {
            if (this.m_d3dRenderTarget != null)
            {
                this.m_d3dRenderTarget = null;

                base.Lock();
                base.SetBackBuffer(D3DResourceType.IDirect3DSurface9, IntPtr.Zero);
                base.Unlock();
            }

            if (renderTarget == null)
            {
                return;
            }
            if (!IsShareable(renderTarget))
            {
                throw new ArgumentException("Texture must be created with ResourceOptionFlags.Shared");
            }

            D3D9.Format format = HigherD3DImageSource.TranslateFormat(renderTarget);
            if (format == D3D9.Format.Unknown)
            {
                throw new ArgumentException("Texture format is not compatible with OpenSharedResource");
            }

            IntPtr handle = GetSharedHandle(renderTarget);

            if (handle == IntPtr.Zero)
            {
                throw new ArgumentNullException("Handle");
            }

            //Map the texture to the D3DImage base class
            bool  tDisposed = renderTarget.IsDisposed;
            float tWidth    = renderTarget.Description.Width;
            float tHeight   = renderTarget.Description.Height;

            this.m_d3dRenderTarget = new D3D9.Texture(
                m_d3dDevice,
                renderTarget.Description.Width,
                renderTarget.Description.Height,
                1, D3D9.Usage.RenderTarget, format, D3D9.Pool.Default, ref handle);
            using (D3D9.Surface surface = this.m_d3dRenderTarget.GetSurfaceLevel(0))
            {
                base.Lock();
                base.SetBackBuffer(D3DResourceType.IDirect3DSurface9, surface.NativePointer);
                base.Unlock();
            }
        }
コード例 #10
0
ファイル: DX9ScreenCapture.cs プロジェクト: DarthAffe/CUE.NET
        public DX9ScreenCapture()
        {
            Width = (int)System.Windows.SystemParameters.PrimaryScreenWidth;
            Height = (int)System.Windows.SystemParameters.PrimaryScreenHeight;

            PresentParameters presentParams = new PresentParameters(Width, Height)
            {
                Windowed = true,
                SwapEffect = SwapEffect.Discard
            };

            _device = new Device(new Direct3D(), 0, DeviceType.Hardware, IntPtr.Zero, CreateFlags.SoftwareVertexProcessing, presentParams);
            _surface = Surface.CreateOffscreenPlain(_device, Width, Height, Format.A8R8G8B8, Pool.Scratch);
            _buffer = new byte[Width * Height * 4];
        }
コード例 #11
0
            protected override void dispose(bool disposeManagedResources)
            {
                if (!IsDisposed)
                {
                    if (disposeManagedResources)
                    {
                        this.Surface.SafeDispose();
                        this.Surface = null;

                        this.Volume.SafeDispose();
                        this.Volume = null;
                    }
                }

                base.dispose(disposeManagedResources);
            }
コード例 #12
0
            //---------------------------------------------------------------------------------------------------------
            /// <summary>
            /// Установка в качестве источника поверхности ренденинга текстуры Direct3D11
            /// </summary>
            /// <param name="render_target">Текстура Direct3D11</param>
            //---------------------------------------------------------------------------------------------------------
            public void SetRenderTarget(Direct3D11.Texture2D render_target)
            {
                // Если есть наша поверхность ренденинга то обнуляем ее
                if (mRenderTarget != null)
                {
                    mRenderTarget = null;

                    base.Lock();
                    base.SetBackBuffer(D3DResourceType.IDirect3DSurface9, IntPtr.Zero);
                    base.Unlock();
                }

                if (render_target == null)
                {
                    return;
                }

                if (!XDirect2DManager.IsShareable(render_target))
                {
                    throw new ArgumentException("Texture must be created with ResourceOptionFlags.Shared");
                }

                Direct3D9.Format format = XDirect2DManager.TranslateFormat(render_target);
                if (format == Direct3D9.Format.Unknown)
                {
                    throw new ArgumentException("Texture format is not compatible with OpenSharedResource");
                }

                IntPtr handle = XDirect2DManager.GetSharedHandle(render_target);

                if (handle == IntPtr.Zero)
                {
                    throw new ArgumentNullException("Handle");
                }

                // Создаем в текстура для ренденинга
                mRenderTarget = new Direct3D9.Texture(XDirect2DManager.D3DDevice, render_target.Description.Width,
                                                      render_target.Description.Height, 1, Direct3D9.Usage.RenderTarget, format, Direct3D9.Pool.Default, ref handle);

                // Получаем поверхность и обновляем представление
                using (Direct3D9.Surface surface = mRenderTarget.GetSurfaceLevel(0))
                {
                    base.Lock();
                    base.SetBackBuffer(D3DResourceType.IDirect3DSurface9, surface.NativePointer);
                    base.Unlock();
                }
            }
コード例 #13
0
ファイル: ScreenCaptor9.cs プロジェクト: Zulkir/RAVC
        public ScreenCaptor9(IHostStatistics statistics, IDevice device)
        {
            this.statistics = statistics;
            var resultFormatId = device.Adapter.GetSupportedFormats(FormatSupport.Texture2D).First(x => x.ExplicitFormat == ExplicitFormat.B8G8R8A8_UNORM).ID;
            texturePool = new TexturePool(device, resultFormatId, Usage.Dynamic, BindFlags.ShaderResource, MiscFlags.None);

            direct3D = new Direct3D();
            form = new Form();
            d3dDevice = new Device(direct3D, 0, DeviceType.Hardware, form.Handle, CreateFlags.SoftwareVertexProcessing, new PresentParameters
            {
                SwapEffect = SwapEffect.Discard,
                Windowed = true
            });

            d3dSurface1 = Surface.CreateOffscreenPlain(d3dDevice, 4096, 1440, Format.A8R8G8B8, Pool.Scratch);

            stopwatch = new Stopwatch();
        }
コード例 #14
0
        public void ProcessSample(Sample srcSample)
        {
            using (var srcBuffer = srcSample.ConvertToContiguousBuffer())
            {
                MediaFactory.GetService(srcBuffer, MediaServiceKeys.Buffer, IID.D3D9Surface, out var pSurf);

                using (SharpDX.Direct3D9.Surface srcSurf = new SharpDX.Direct3D9.Surface(pSurf))
                {
                    device.StretchRectangle(srcSurf, surface, SharpDX.Direct3D9.TextureFilter.Linear);

                    //var data = surface.LockRectangle(LockFlags.ReadOnly);

                    //TestTools.WriteFile(data.DataPointer, 3133440, @"d:\test.raw");

                    //surface.UnlockRectangle();
                }
            }
        }
コード例 #15
0
        void aquireResources()
        {
            if (videoWidth == 0 || videoHeight == 0)
            {
                throw new VideoPlayerException("Cannot instantiate D3D surface with a width or height of 0 pixels");
            }

            D3D.Format pixelFormat = makeFourCC('Y', 'V', '1', '2');

            offscreen = D3D.Surface.CreateOffscreenPlain(device,
                                                         videoWidth,
                                                         videoHeight,
                                                         pixelFormat,
                                                         D3D.Pool.Default);

            screenShot = D3D.Surface.CreateOffscreenPlain(device,
                                                          videoWidth,
                                                          videoHeight,
                                                          D3D.Format.A8R8G8B8,
                                                          D3D.Pool.Default);

            backBuffer = device.GetBackBuffer(0, 0);

            FontDescription fontDescription = new FontDescription();

            fontDescription.FaceName = "TimesNewRoman";
            fontDescription.Height   = 15;

            infoFont = new D3D.Font(device, fontDescription);

            fontDescription          = new FontDescription();
            fontDescription.FaceName = "Arial";

            videoDestRect = getVideoDestRect(backBuffer);

            fontDescription.Height = videoDestRect.Height / 14;

            fontDescription.Quality = FontQuality.Antialiased;

            subtitleShadowOffset = fontDescription.Height / 18;
            subtitleBottomMargin = videoDestRect.Height / 12;

            subtitleFont = new D3D.Font(device, fontDescription);
        }
コード例 #16
0
        private Bitmap GetDX9ScreenShot()
        {
            try
            {
                screenShot       = null;
                screenShot       = new System.Drawing.Bitmap(WIDTH, HEIGHT, pixelFormat);
                dx9ScreenSurface = SharpDX.Direct3D9.Surface.CreateOffscreenPlain(
                    dx9Device,
                    WIDTH,
                    HEIGHT,
                    SharpDX.Direct3D9.Format.A8R8G8B8,
                    Pool.SystemMemory);

                dx9Device.GetFrontBufferData(0, dx9ScreenSurface);

                dx9Map  = dx9ScreenSurface.LockRectangle(LockFlags.None);
                bmpData = screenShot.LockBits(boundsRect,
                                              System.Drawing.Imaging.ImageLockMode.WriteOnly, screenShot.PixelFormat);

                var sourcePtr = dx9Map.DataPointer;
                var destPtr   = bmpData.Scan0;
                for (int y = 0; y < HEIGHT; y++)
                {
                    // Copy a single line
                    Utilities.CopyMemory(destPtr, sourcePtr, ARGB_WIDTH);
                    // Advance pointers
                    sourcePtr = IntPtr.Add(sourcePtr, dx9Map.Pitch);
                    destPtr   = IntPtr.Add(destPtr, bmpData.Stride);
                }

                screenShot.UnlockBits(bmpData);
                dx9ScreenSurface.UnlockRectangle();
                dx9ScreenSurface.Dispose();
                bmpData = null;
                GC.Collect();
                return(screenShot);
            }
            catch (Exception ex)
            {
                LdpLog.Error("GetDX9ScreenShot error.\n" + ex.Message);
                return(screenShot = null);
            }
        }
コード例 #17
0
    private void InitTexture(BluRayAPI.OSDTexture item)
    {
      if (item.Width == 0 || item.Height == 0 || item.Texture == IntPtr.Zero)
      {
        FreeResources();
        return;
      }

      if (_combinedOsdTexture == null || _combinedOsdTexture.IsDisposed)
      {
        _combinedOsdTexture = new Texture(_device, _fullOsdSize.Width, _fullOsdSize.Height, 1, Usage.RenderTarget, FORMAT, Pool.Default);
        _combinedOsdSurface = _combinedOsdTexture.GetSurfaceLevel(0);

        _sprite = new Sprite(_device);

        Rectangle dstRect = new Rectangle(0, 0, _fullOsdSize.Width, _fullOsdSize.Height);
        _device.ColorFill(_combinedOsdSurface, dstRect, _transparentColor);
      }
    }
コード例 #18
0
        private Bitmap GetDX9ScreenShot()
        {
            try
            {
                screenShot = null;
                screenShot = new System.Drawing.Bitmap(WIDTH, HEIGHT, pixelFormat);
                dx9ScreenSurface = SharpDX.Direct3D9.Surface.CreateOffscreenPlain(
                dx9Device,
                WIDTH,
                HEIGHT,
                SharpDX.Direct3D9.Format.A8R8G8B8,
                Pool.SystemMemory);

                dx9Device.GetFrontBufferData(0, dx9ScreenSurface);

                dx9Map = dx9ScreenSurface.LockRectangle(LockFlags.None);
                bmpData = screenShot.LockBits(boundsRect,
                    System.Drawing.Imaging.ImageLockMode.WriteOnly, screenShot.PixelFormat);

                var sourcePtr = dx9Map.DataPointer;
                var destPtr = bmpData.Scan0;
                for (int y = 0; y < HEIGHT; y++)
                {
                    // Copy a single line
                    Utilities.CopyMemory(destPtr, sourcePtr, ARGB_WIDTH);
                    // Advance pointers
                    sourcePtr = IntPtr.Add(sourcePtr, dx9Map.Pitch);
                    destPtr = IntPtr.Add(destPtr, bmpData.Stride);
                }

                screenShot.UnlockBits(bmpData);
                dx9ScreenSurface.UnlockRectangle();
                dx9ScreenSurface.Dispose();
                bmpData = null;
                GC.Collect();
                return screenShot;
            }
            catch (Exception ex)
            {
                LdpLog.Error("GetDX9ScreenShot error.\n" + ex.Message);
                return screenShot = null;
            }
        }
コード例 #19
0
    public void Allocate(int width, int height, Format format, MultisampleType multisampleType, int multisampleQuality, bool lockable)
    {
      bool free;
      lock (_syncObj)
        free = width != _size.Width || height != _size.Height || format != _format;
      if (free)
        Free();
      lock (_syncObj)
      {
        if (_surface != null)
          return;

        _size.Width = width;
        _size.Height = height;
        _format = format;

        _surface = Surface.CreateRenderTarget(GraphicsDevice.Device, width, height, format, multisampleType, multisampleQuality, lockable);
      }
      AllocationChanged(AllocationSize);
      KeepAlive();
    }
コード例 #20
0
ファイル: RenderWindow.cs プロジェクト: tgjones/meshellator
        public IntPtr GetBackBufferComPointer()
        {
            if (_surfaceSettingsChanged)
            {
                if (_backBufferSurface != null)
                    _backBufferSurface.Dispose();
                _backBufferSurface = Surface.CreateRenderTarget(_device, Width, Height,
                    Format.X8R8G8B8, _multisampleType, 0, false);

                if (_depthStencilSurface != null)
                    _depthStencilSurface.Dispose();

                _depthStencilSurface = Surface.CreateDepthStencil(_device, Width, Height,
                    Format.D24S8, _multisampleType, 0, true);

                _surfaceSettingsChanged = false;
            }

            _device.SetRenderTarget(0, _backBufferSurface);
            _device.DepthStencilSurface = _depthStencilSurface;
            return _backBufferSurface.NativePointer;
        }
コード例 #21
0
        public override object this[string attribute]
        {
            [OgreVersion(1, 7, 2)]
            get
            {
                if (attribute.ToUpper() == "DDBACKBUFFER")
                {
                    var surfaces = new D3D9.Surface[Config.MaxMultipleRenderTargets];
                    // Transfer surfaces
                    for (var x = 0; x < Config.MaxMultipleRenderTargets; ++x)
                    {
                        if (this._renderTargets[x] != null)
                        {
                            surfaces[x] = this._renderTargets[x].GetSurface(D3D9RenderSystem.ActiveD3D9Device);
                        }
                    }
                    return(surfaces);
                }

                return(null);
            }
        }
コード例 #22
0
        private void Dispose()
        {
            // Unregister handlers
            UnregisterKeyBindings();

            SkinContext.DeviceSceneEnd -= UICapture;
            if (surfaceDestination != null)
            {
                surfaceDestination.Dispose();
                surfaceDestination = null;
            }

            messageQueue.MessageReceived -= OnMessageReceived;

            // Dispose of the AtmoLight Core
            coreObject.ChangeEffect(settings.MPExitEffect);

            coreObject.Dispose();

            // Unregister Log Handler
            Log.OnNewLog             -= new Log.NewLogHandler(OnNewLog);
            Core.OnNewConnectionLost -= new Core.NewConnectionLostHandler(OnNewConnectionLost);
            Core.OnNewVUMeter        -= new Core.NewVUMeterHander(OnNewVUMeter);
            AtmoLight.Configuration.OnOffButton.ButtonsChanged -=
                new Configuration.OnOffButton.ButtonsChangedHandler(ReregisterKeyBindings);
            AtmoLight.Configuration.ProfileButton.ButtonsChanged -=
                new Configuration.ProfileButton.ButtonsChangedHandler(ReregisterKeyBindings);
            SystemEvents.PowerModeChanged -= PowerModeChanged;

            if (settings.MonitorScreensaverState)
            {
                settings.MonitorScreensaverState = false;
            }

            UnregisterSettingsChangedHandler();
        }
コード例 #23
0
ファイル: GBuffer.cs プロジェクト: nydehi/openuo
 public void Begin()
 {
     _backBuffer = _device.GetRenderTarget(0);
 }
コード例 #24
0
		public override object this[ string attribute ]
		{
			[OgreVersion( 1, 7, 2 )]
			get
			{
				if ( attribute.ToUpper() == "DDBACKBUFFER" )
				{
					var surfaces = new D3D9.Surface[Config.MaxMultipleRenderTargets];
					// Transfer surfaces
					for ( var x = 0; x < Config.MaxMultipleRenderTargets; ++x )
					{
						if ( this._renderTargets[ x ] != null )
						{
							surfaces[ x ] = this._renderTargets[ x ].GetSurface( D3D9RenderSystem.ActiveD3D9Device );
						}
					}
					return surfaces;
				}

				return null;
			}
		}
コード例 #25
0
    protected void RenderToSurfaceInternal(Surface renderSurface, RenderContext renderContext)
    {
      // We do the following here:
      // 1. Set the transformation matrix to match the render surface's size
      // 2. Set the rendertarget to the given surface
      // 3. Clear the surface with an alpha value of 0
      // 4. Render the control (into the surface)
      // 5. Restore the rendertarget to the backbuffer
      // 6. Restore previous transformation matrix

      // Set transformation matrix
      Matrix? oldTransform = null;
      SurfaceDescription description = renderSurface.Description;

      if (description.Width != GraphicsDevice.Width || description.Height != GraphicsDevice.Height)
      {
        oldTransform = GraphicsDevice.FinalTransform;
        GraphicsDevice.SetCameraProjection(description.Width, description.Height);
      }

      // Render to given surface and restore it when we are done
      using (new TemporaryRenderTarget(renderSurface))
      {
        // Morpheus_xx, 2014-12-03: Performance optimization:
        // When using Effects or OpacityMask, the target texture is as big as the screen size.
        // Always clearing the whole area even for small controls is waste of resource.
        RectangleF bounds = renderContext.ClearOccupiedAreaOnly ? renderContext.OccupiedTransformedBounds : new RectangleF(0, 0, description.Width, description.Height);

        // Fill the background of the texture with an alpha value of 0
        GraphicsDevice.Device.Clear(ClearFlags.Target, ColorConverter.FromArgb(0, Color.Black), 1.0f, 0,
          new [] { new Rectangle(
              (int)Math.Floor(bounds.X),
              (int)Math.Floor(bounds.Y),
              (int)Math.Ceiling(bounds.Width),
              (int)Math.Ceiling(bounds.Height))});

        // Render the control into the given texture
        RenderOverride(renderContext);
        // Render opacity brush so that it modifies the alpha channel in the target
        RenderOpacityBrush(renderContext);
      }

      // Restore standard transformation matrix
      if (oldTransform.HasValue)
        GraphicsDevice.FinalTransform = oldTransform.Value;
    }
コード例 #26
0
ファイル: DXHookD3D9.cs プロジェクト: Soothsilver/megajewel
        private void CreateResources(Device device, int width, int height, Format format)
        {
            if (_resourcesInitialised) return;
            _resourcesInitialised = true;
            
            // Create offscreen surface to use as copy of render target data
            _renderTargetCopy = ToDispose(Surface.CreateOffscreenPlain(device, width, height, format, Pool.SystemMemory));
            
            // Create our resolved surface (resizing if necessary and to resolve any multi-sampling)
            _resolvedTarget = ToDispose(Surface.CreateRenderTarget(device, width, height, format, MultisampleType.None, 0, false));

            _query = ToDispose(new Query(device, QueryType.Event));
        }
コード例 #27
0
        private void SetupSurfaces(Device device)
        {
            try
            {
                this.surface = Surface.CreateOffscreenPlain(device, this.width, this.height, (Format)this.format, Pool.SystemMemory);
                var lockedRect = this.surface.LockRectangle(LockFlags.ReadOnly);
                this.pitch = lockedRect.Pitch;
                this.surface.UnlockRectangle();
                this.renderTarget = Surface.CreateRenderTarget(device, this.width, this.height, this.format, MultisampleType.None, 0, false);
                this.query = new Query(device, QueryType.Event);

                killThread = false;
                this.copyThread = new Thread(this.HandleCaptureRequestThread);
                this.copyThread.Start();

                this.retrieveThread = new Thread(this.RetrieveImageDataThread);
                this.retrieveThread.Start();

                this.surfacesSetup = true;
            }
            catch (Exception ex)
            {
                this.DebugMessage(ex.ToString());
                ClearData();
            }
        }
コード例 #28
0
			protected override void dispose( bool disposeManagedResources )
			{
				if ( !IsDisposed )
				{
					if ( disposeManagedResources )
					{
						this.Surface.SafeDispose();
						this.Surface = null;

						this.Volume.SafeDispose();
						this.Volume = null;
					}
				}

				base.dispose( disposeManagedResources );
			}
コード例 #29
0
        /// <summary>
        /// Reset the _renderTarget so that we are sure it will have the correct presentation parameters (required to support working across changes to windowed/fullscreen or resolution changes)
        /// </summary>
        /// <param name="devicePtr"></param>
        /// <param name="presentParameters"></param>
        /// <returns></returns>
        int ResetHook(IntPtr devicePtr, ref PresentParameters presentParameters)
        {
            Device device = (Device)devicePtr;
            try
            {

                lock (_lockRenderTarget)
                {
                    if (_renderTarget != null)
                    {
                        _renderTarget.Dispose();
                        _renderTarget = null;
                    }
                }
                // EasyHook has already repatched the original Reset so calling it here will not cause an endless recursion to this function
                device.Reset(presentParameters);
                return SharpDX.Result.Ok.Code;
            }
            catch (SharpDX.SharpDXException sde)
            {
                return sde.ResultCode.Code;
            }
            catch (Exception e)
            {
                DebugMessage(e.ToString());
                return SharpDX.Result.Ok.Code;
            }
        }
コード例 #30
0
        protected override void Dispose(bool disposing)
        {
            if (true)
            {
                try
                {
                    lock (_lockRenderTarget)
                    {
                        if (_renderTarget != null)
                        {
                            _renderTarget.Dispose();
                            _renderTarget = null;
                        }

                        Request = null;
                    }
                }
                catch
                {
                }
            }
            base.Dispose(disposing);
        }
コード例 #31
0
ファイル: VideoPlayer.cs プロジェクト: chekiI/MediaPortal-2
 /// <summary>
 /// PostProcessTexture allows video players to post process the video frame texture,
 /// i.e. for overlaying subtitles or OSD menus.
 /// </summary>
 /// <param name="targetTexture"></param>
 protected virtual void PostProcessTexture(Surface targetTexture)
 { }
コード例 #32
0
ファイル: D3D9Texture.cs プロジェクト: ryan-bunker/axiom3d
			protected override void dispose( bool disposeManagedResources )
			{
				if ( !IsDisposed )
				{
					if ( disposeManagedResources )
					{
						this.NormalTexture.SafeDispose();
						this.NormalTexture = null;

						this.CubeTexture.SafeDispose();
						this.CubeTexture = null;

						this.VolumeTexture.SafeDispose();
						this.VolumeTexture = null;

						this.BaseTexture.SafeDispose();
						this.BaseTexture = null;

						this.FSAASurface.SafeDispose();
						this.FSAASurface = null;
					}
				}

				base.dispose( disposeManagedResources );
			}
コード例 #33
0
        public void Bind(D3D9.Device dev, D3D9.Surface surface, D3D9.Surface fsaaSurface, bool writeGamma, int fsaa,
                         string srcName, D3D9.BaseTexture mipTex)
        {
            //Entering critical section
            LockDeviceAccess();

            var bufferResources = GetBufferResources(dev);
            var isNewBuffer     = false;

            if (bufferResources == null)
            {
                bufferResources = new BufferResources();
                this.mapDeviceToBufferResources.Add(dev, bufferResources);
                isNewBuffer = true;
            }

            bufferResources.MipTex      = mipTex;
            bufferResources.Surface     = surface;
            bufferResources.FsaaSurface = fsaaSurface;

            var desc = surface.Description;

            width  = desc.Width;
            height = desc.Height;
            depth  = 1;
            format = D3D9Helper.ConvertEnum(desc.Format);
            // Default
            rowPitch    = Width;
            slicePitch  = Height * Width;
            sizeInBytes = PixelUtil.GetMemorySize(Width, Height, Depth, Format);

            if (((int)usage & (int)TextureUsage.RenderTarget) != 0)
            {
                UpdateRenderTexture(writeGamma, fsaa, srcName);
            }

            if (isNewBuffer && this.ownerTexture.IsManuallyLoaded)
            {
                foreach (var it in this.mapDeviceToBufferResources)
                {
                    if (it.Value != bufferResources && it.Value.Surface != null && it.Key.TestCooperativeLevel().Success&&
                        dev.TestCooperativeLevel().Success)
                    {
                        var fullBufferBox = new BasicBox(0, 0, 0, Width, Height, Depth);
                        var dstBox        = new PixelBox(fullBufferBox, Format);

                        var data = new byte[sizeInBytes];
                        using (var d = BufferBase.Wrap(data))
                        {
                            dstBox.Data = d;
                            BlitToMemory(fullBufferBox, dstBox, it.Value, it.Key);
                            BlitFromMemory(dstBox, fullBufferBox, bufferResources);
                            Array.Clear(data, 0, sizeInBytes);
                        }
                        break;
                    }
                }
            }

            //Leaving critical section
            UnlockDeviceAccess();
        }
コード例 #34
0
        public void UICapture(object sender, EventArgs args)
        {
            if (!coreObject.IsConnected() || !coreObject.IsAtmoLightOn() || coreObject.GetCurrentEffect() != ContentEffect.MediaPortalLiveMode)
            {
                return;
            }

            // Low CPU setting.
            // Skip frame if LowCPUTime has not yet passed since last frame.
            if (settings.LowCPU)
            {
                if ((Win32API.GetTickCount() - lastFrame) < settings.LowCPUTime)
                {
                    return;
                }
                else
                {
                    lastFrame = Win32API.GetTickCount();
                }
            }

            Rectangle rectangleDestination = new Rectangle(0, 0, coreObject.GetCaptureWidth(), coreObject.GetCaptureHeight());

            try
            {
                if (surfaceDestination == null)
                {
                    surfaceDestination = SharpDX.Direct3D9.Surface.CreateRenderTarget(SkinContext.Device,
                                                                                      coreObject.GetCaptureWidth(), coreObject.GetCaptureHeight(), SharpDX.Direct3D9.Format.A8R8G8B8,
                                                                                      SharpDX.Direct3D9.MultisampleType.None, 0, true);
                }

                // Use the Player Surface if video is playing.
                // This results in lower time to calculate aswell as blackbar removal
                if (ServiceRegistration.Get <IPlayerContextManager>().IsVideoContextActive)
                {
                    player = ServiceRegistration.Get <IPlayerContextManager>().PrimaryPlayerContext.CurrentPlayer as ISharpDXVideoPlayer;

                    // player.Texture can be null even if VideoContext is active, e.g. at the start of a video
                    if (player.Texture != null)
                    {
                        surfaceSource = player.Texture.GetSurfaceLevel(0);
                    }
                }
                else
                {
                    surfaceSource = SkinContext.Device.GetRenderTarget(0);
                }

                if (surfaceSource == null)
                {
                    return;
                }

                surfaceSource.Device.StretchRectangle(surfaceSource, null, surfaceDestination, rectangleDestination, SharpDX.Direct3D9.TextureFilter.None);
                DataStream stream = SharpDX.Direct3D9.Surface.ToStream(surfaceDestination, SharpDX.Direct3D9.ImageFileFormat.Bmp);

                coreObject.CalculateBitmap(stream);

                stream.Close();
                stream.Dispose();
            }
            catch (Exception ex)
            {
                surfaceDestination.Dispose();
                surfaceDestination = null;
                Log.Error("Error in UICapture.");
                Log.Error("Exception: {0}", ex.Message);
            }
        }
コード例 #35
0
        private void ClearData()
        {
            this.DebugMessage("ClearData called");

            if (this.copyThread != null)
            {
                this.killThread = true;
                this.copyEvent.Set();

                if (!this.copyThread.Join(500))
                {
                    this.copyThread.Abort();
                }

                this.copyEvent.Reset();
                this.copyThread = null;
            }

            if (this.retrieveThread != null)
            {
                this.killThread = true;
                this.copyReadySignal.Set();

                if (this.retrieveThread.Join(500))
                {
                    this.retrieveThread.Abort();
                }

                this.copyReadySignal.Reset();
                this.retrieveThread = null;
            }

            // currentDevice = null;
            if (this.Request != null)
            {
                this.Request.Dispose();
                this.Request = null;
            }

            this.width = 0;
            this.height = 0;
            this.pitch = 0;
            if (this.surfaceLocked)
            {
                lock (this.surfaceLock)
                {
                    this.surface.UnlockRectangle();
                    this.surfaceLocked = false;
                }
            }

            if (this.surface != null)
            {
                this.surface.Dispose();
                this.surface = null;
            }
            if (this.renderTarget != null)
            {
                this.renderTarget.Dispose();
                this.renderTarget = null;
            }
            if (this.query != null)
            {
                this.query.Dispose();
                this.query = null;
                this.queryIssued = false;
            }
            this.hooksStarted = false;
            this.surfacesSetup = false;
        }
コード例 #36
0
ファイル: MainWindow.xaml.cs プロジェクト: lindexi/lindexi_gd
        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            var hr = Direct3DCreate9Ex(D3D_SDK_VERSION, out var direct3D9Ex);

            m_d3dEx = direct3D9Ex;

            var adapterMonitor = direct3D9Ex.GetAdapterMonitor(0);

            m_hWnd = GetDesktopWindow();

            var param = new D3DPRESENT_PARAMETERS
            {
                Windowed = 1,
                Flags    = ((short)D3DPRESENTFLAG.D3DPRESENTFLAG_VIDEO),

                /*
                 * D3DFMT_R8G8B8:表示一个24位像素,从左开始,8位分配给红色,8位分配给绿色,8位分配给蓝色。
                 *
                 * D3DFMT_X8R8G8B8:表示一个32位像素,从左开始,8位不用,8位分配给红色,8位分配给绿色,8位分配给蓝色。
                 *
                 * D3DFMT_A8R8G8B8:表示一个32位像素,从左开始,8位为ALPHA通道,8位分配给红色,8位分配给绿色,8位分配给蓝色。
                 *
                 * D3DFMT_A16B16G16R16F:表示一个64位浮点像素,从左开始,16位为ALPHA通道,16位分配给蓝色,16位分配给绿色,16位分配给红色。
                 *
                 * D3DFMT_A32B32G32R32F:表示一个128位浮点像素,从左开始,32位为ALPHA通道,32位分配给蓝色,32位分配给绿色,32位分配给红色。
                 */
                //BackBufferFormat = D3DFORMAT.D3DFMT_X8R8G8B8,

                //SwapEffect = D3DSWAPEFFECT.D3DSWAPEFFECT_COPY
                SwapEffect = D3DSWAPEFFECT.D3DSWAPEFFECT_DISCARD,

                hDeviceWindow        = GetDesktopWindow(), // 添加
                PresentationInterval = (int)D3D9.PresentInterval.Default,
            };

            /* The COM pointer to our D3D Device */
            IntPtr dev;

            m_d3dEx.CreateDeviceEx(0, D3DDEVTYPE.D3DDEVTYPE_HAL, m_hWnd,
                                   Direct3D.CreateFlags.D3DCREATE_HARDWARE_VERTEXPROCESSING | Direct3D.CreateFlags.D3DCREATE_MULTITHREADED
                                   | Direct3D.CreateFlags.D3DCREATE_FPU_PRESERVE,
                                   ref param, IntPtr.Zero, out dev);

            m_device = (IDirect3DDevice9)Marshal.GetObjectForIUnknown(dev);
            // 只是减少引用计数而已,现在换成 m_device 了
            Marshal.Release(dev);

            hr = m_device.TestCooperativeLevel();
            var pDevice = dev;

            D3D11.Texture2D d3d11Texture2D = CreateRenderTarget();
            //SetRenderTarget(d3d11Texture2D);

            var format = TranslateFormat(TranslateFormat(d3d11Texture2D));

            var dxgiResource  = d3d11Texture2D.QueryInterface <DXGI.Resource>();
            var pSharedHandle = dxgiResource.SharedHandle;

            hr = m_device.CreateTexture(ImageWidth,
                                        ImageHeight,
                                        1,
                                        1,
                                        format,
                                        0,
                                        out m_privateTexture,
                                        ref pSharedHandle);

            hr = m_privateTexture.GetSurfaceLevel(0, out m_privateSurface);

            var backBuffer = Marshal.GetIUnknownForObject(m_privateSurface);

            var surface        = new D3D9.Surface(backBuffer);
            var queryInterface = surface.QueryInterface <D3D9.Surface>();
            //// 只是减少引用计数而已
            //Marshal.Release(backBuffer);

            //hr = m_device.SetTexture(0, m_privateTexture);

            var texturePtr = Marshal.GetIUnknownForObject(m_privateTexture);

            //Marshal.Release(texturePtr);

            //var byteList = new byte[32 * 10];
            //for (int i = 0; i < byteList.Length; i++)
            //{
            //    byteList[i] = (byte)i;
            //}

            //unsafe
            //{
            //    fixed (void* p = byteList)
            //    {
            //        Buffer.MemoryCopy(p, (void*) texturePtr,0,320);
            //    }
            //}

            //var d2dFactory = new SharpDX.Direct2D1.Factory();

            //Texture2D backBufferTexture2D = new Texture2D(texturePtr);
            //var d2dRenderTarget = new RenderTarget(d2dFactory, new SharpDX.DXGI.Surface(backBuffer),
            //    new RenderTargetProperties(new SharpDX.Direct2D1.PixelFormat(Format.Unknown,AlphaMode.Premultiplied)));

            //d2dRenderTarget.BeginDraw();
            //d2dRenderTarget.Clear(new RawColor4(1,0,0.5f,1));
            //d2dRenderTarget.EndDraw();

            D3DImage.Lock();
            D3DImage.SetBackBuffer(D3DResourceType.IDirect3DSurface9, backBuffer, true);
            D3DImage.Unlock();

            Render();

            string s             = "123";
            var    stringBuilder = new StringBuilder(s);

            stringBuilder.Replace("%", "%25").Replace("#", "%23");
            stringBuilder.Insert(0, "123");
            stringBuilder.Insert("123".Length, "#");
        }
コード例 #37
0
        /// <summary>
        /// Implementation of capturing from the render target of the Direct3D9 Device (or DeviceEx)
        /// </summary>
        /// <param name="device"></param>
        void DoCaptureRenderTarget(Device device, string hook)
        {
            this.Frame();

            try
            {
                    #region Screenshot Request
                // Single frame capture request
                if (this.Request != null)
                {
                    DateTime start = DateTime.Now;
                    try
                    {

                        using (Surface renderTargetTemp = device.GetRenderTarget(0))
                        {
                            int width, height;

                            // TODO: If resizing the captured image is required it can be adjusted here
                            //if (renderTargetTemp.Description.Width > 1280)
                            //{
                            //    width = 1280;
                            //    height = (int)Math.Round((renderTargetTemp.Description.Height * (1280.0 / renderTargetTemp.Description.Width)));
                            //}
                            //else
                            {
                                width = renderTargetTemp.Description.Width;
                                height = renderTargetTemp.Description.Height;
                            }

                            // First ensure we have a Surface to the render target data into
                            if (_renderTarget == null)
                            {
                                // Create offscreen surface to use as copy of render target data
                                using (SwapChain sc = device.GetSwapChain(0))
                                {
                                    _renderTarget = Surface.CreateOffscreenPlain(device, width, height, sc.PresentParameters.BackBufferFormat, Pool.SystemMemory);
                                }
                            }

                            // Create our resolved surface (resizing if necessary and to resolve any multi-sampling)
                            using (Surface resolvedSurface = Surface.CreateRenderTarget(device, width, height, renderTargetTemp.Description.Format, MultisampleType.None, 0, false))
                            {
                                // Resize from Render Surface to resolvedSurface
                                device.StretchRectangle(renderTargetTemp, resolvedSurface, TextureFilter.None);

                                // Get Render Data
                                device.GetRenderTargetData(resolvedSurface, _renderTarget);
                            }
                        }

                        if (Request != null)
                            ProcessRequest();
                    }
                    finally
                    {
                        // We have completed the request - mark it as null so we do not continue to try to capture the same request
                        // Note: If you are after high frame rates, consider implementing buffers here to capture more frequently
                        //         and send back to the host application as needed. The IPC overhead significantly slows down 
                        //         the whole process if sending frame by frame.
                        Request = null;
                    }
                    DateTime end = DateTime.Now;
                    this.DebugMessage(hook + ": Capture time: " + (end - start).ToString());
                }

                #endregion

                if (this.Config.ShowOverlay)
                {
                    #region Draw frame rate

                    // TODO: font needs to be created and then reused, not created each frame!
                    using (SharpDX.Direct3D9.Font font = new SharpDX.Direct3D9.Font(device, new FontDescription()
                                    {
                                        Height = 16,
                                        FaceName = "Arial",
                                        Italic = false,
                                        Width = 0,
                                        MipLevels = 1,
                                        CharacterSet = FontCharacterSet.Default,
                                        OutputPrecision = FontPrecision.Default,
                                        Quality = FontQuality.Antialiased,
                                        PitchAndFamily = FontPitchAndFamily.Default | FontPitchAndFamily.DontCare,
                                        Weight = FontWeight.Bold
                                    }))
                    {

                        if (this.FPS.GetFPS() >= 1)
                        {
                            font.DrawText(null, String.Format("{0:N0} fps", this.FPS.GetFPS()), 5, 5, SharpDX.Color.Red);
                        }

                        if (this.TextDisplay != null && this.TextDisplay.Display)
                        {
                            font.DrawText(null, this.TextDisplay.Text, 5, 25, new SharpDX.ColorBGRA(255, 0, 0, (byte)Math.Round((Math.Abs(1.0f - TextDisplay.Remaining) * 255f))));
                        }
                    }

                    #endregion
                }
            }
            catch (Exception e)
            {
                DebugMessage(e.ToString());
            }
        }
コード例 #38
0
ファイル: Plugin.cs プロジェクト: chli/AtmoLight
    public void UICapture(object sender, EventArgs args)
    {
      if (!coreObject.IsConnected() || !coreObject.IsAtmoLightOn() || coreObject.GetCurrentEffect() != ContentEffect.MediaPortalLiveMode)
      {
        return;
      }

      // Low CPU setting.
      // Skip frame if LowCPUTime has not yet passed since last frame.
      if (settings.LowCPU)
      {
        if ((Win32API.GetTickCount() - lastFrame) < settings.LowCPUTime)
        {
          return;
        }
        else
        {
          lastFrame = Win32API.GetTickCount();
        }
      }

      Rectangle rectangleDestination = new Rectangle(0, 0, coreObject.GetCaptureWidth(), coreObject.GetCaptureHeight());
      try
      {
        if (surfaceDestination == null)
        {
          surfaceDestination = SharpDX.Direct3D9.Surface.CreateRenderTarget(SkinContext.Device,
            coreObject.GetCaptureWidth(), coreObject.GetCaptureHeight(), SharpDX.Direct3D9.Format.A8R8G8B8,
            SharpDX.Direct3D9.MultisampleType.None, 0, true);
        }

        // Use the Player Surface if video is playing.
        // This results in lower time to calculate aswell as blackbar removal
        if (ServiceRegistration.Get<IPlayerContextManager>().IsVideoContextActive)
        {
          player = ServiceRegistration.Get<IPlayerContextManager>().PrimaryPlayerContext.CurrentPlayer as ISharpDXVideoPlayer;

          // player.Texture can be null even if VideoContext is active, e.g. at the start of a video
          if (player.Texture != null)
          {
            surfaceSource = player.Texture.GetSurfaceLevel(0);
          }
        }
        else
        {
          surfaceSource = SkinContext.Device.GetRenderTarget(0);
        }

        if (surfaceSource == null)
        {
          return;
        }

        surfaceSource.Device.StretchRectangle(surfaceSource, null, surfaceDestination, rectangleDestination, SharpDX.Direct3D9.TextureFilter.None);
        DataStream stream = SharpDX.Direct3D9.Surface.ToStream(surfaceDestination, SharpDX.Direct3D9.ImageFileFormat.Bmp);

        coreObject.CalculateBitmap(stream);

        stream.Close();
        stream.Dispose();
      }
      catch (Exception ex)
      {
        surfaceDestination.Dispose();
        surfaceDestination = null;
        Log.Error("Error in UICapture.");
        Log.Error("Exception: {0}", ex.Message);
      }
    }
コード例 #39
0
ファイル: Device.cs プロジェクト: lavajoe/ClassicalSharp
 public void GetRenderTargetData(Surface renderTarget, Surface destSurface)
 {
     int res = Interop.Calli(comPointer, renderTarget.comPointer, destSurface.comPointer,(*(IntPtr**)comPointer)[32]);
     if( res < 0 ) { throw new SharpDXException( res ); }
 }
コード例 #40
0
ファイル: Plugin.cs プロジェクト: chli/AtmoLight
    private void Dispose()
    {
      // Unregister handlers
      UnregisterKeyBindings();

      SkinContext.DeviceSceneEnd -= UICapture;
      if (surfaceDestination != null)
      {
        surfaceDestination.Dispose();
        surfaceDestination = null;
      }

      messageQueue.MessageReceived -= OnMessageReceived;

      // Dispose of the AtmoLight Core
      coreObject.ChangeEffect(settings.MPExitEffect);

      coreObject.Dispose();

      // Unregister Log Handler
      Log.OnNewLog -= new Log.NewLogHandler(OnNewLog);
      Core.OnNewConnectionLost -= new Core.NewConnectionLostHandler(OnNewConnectionLost);
      Core.OnNewVUMeter -= new Core.NewVUMeterHander(OnNewVUMeter);
      AtmoLight.Configuration.OnOffButton.ButtonsChanged -=
        new Configuration.OnOffButton.ButtonsChangedHandler(ReregisterKeyBindings);
      AtmoLight.Configuration.ProfileButton.ButtonsChanged -=
        new Configuration.ProfileButton.ButtonsChangedHandler(ReregisterKeyBindings);
      SystemEvents.PowerModeChanged -= PowerModeChanged;

      if (settings.MonitorScreensaverState)
      {
        settings.MonitorScreensaverState = false;
      }

      UnregisterSettingsChangedHandler();
    }
コード例 #41
0
 /// <summary>
 /// Render subtitles on video texture if enabled and available.
 /// </summary>
 protected override void PostProcessTexture(Surface targetSurface)
 {
   _subtitleRenderer.DrawOverlay(targetSurface);
 }
コード例 #42
0
 private void FreeResources()
 {
   // _combinedOsdSurface does not need an explicit Dispose, it's done on Texture dispose:
   // When SlimDx.Configuration.DetectDoubleDispose is set to true, an ObjectDisposedException will be thrown!
   _combinedOsdSurface = null;
   FilterGraphTools.TryDispose(ref _combinedOsdTexture);
   FilterGraphTools.TryDispose(ref _sprite);
 }
コード例 #43
0
ファイル: DXHookD3D9.cs プロジェクト: Soothsilver/megajewel
 private SharpDX.DataRectangle LockRenderTarget(Surface _renderTargetCopy, out SharpDX.Rectangle rect)
 {
     if (_requestCopy.RegionToCapture.Height > 0 && _requestCopy.RegionToCapture.Width > 0)
     {
         rect = new SharpDX.Rectangle(_requestCopy.RegionToCapture.Left, _requestCopy.RegionToCapture.Top, _requestCopy.RegionToCapture.Width, _requestCopy.RegionToCapture.Height);
     }
     else
     {
         rect = new SharpDX.Rectangle(0, 0, _renderTargetCopy.Description.Width, _renderTargetCopy.Description.Height);
     }
     return _renderTargetCopy.LockRectangle(rect, LockFlags.ReadOnly);
 }
コード例 #44
0
ファイル: D3D9Device.cs プロジェクト: ryan-bunker/axiom3d
			protected override void dispose( bool disposeManagedResources )
			{
				if ( !IsDisposed )
				{
					if ( disposeManagedResources )
					{
						this.SwapChain.SafeDispose();
						this.SwapChain = null;

						this.BackBuffer.SafeDispose();
						this.BackBuffer = null;

						this.DepthBuffer.SafeDispose();
						this.DepthBuffer = null;
					}
				}

				base.dispose( disposeManagedResources );
			}
コード例 #45
0
		public override object this[ string attribute ]
		{
			get
			{
				switch ( attribute.ToUpper() )
				{
					case "D3DDEVICE":
						return D3DDevice;

					case "WINDOW":
						return this._windowHandle.Handle;

					case "ISTEXTURE":
						return false;

					case "D3DZBUFFER":
						return this._device.GetDepthBuffer( this );

					case "DDBACKBUFFER":
					{
						var ret = new D3D9.Surface[8];
						ret[ 0 ] = this._device.GetBackBuffer( this );
						return ret;
					}

					case "DDFRONTBUFFER":
						return this._device.GetBackBuffer( this );
				}
				return new NotSupportedException( "There is no D3D9 RenderWindow custom attribute named " + attribute );
			}
		}
コード例 #46
0
        public void createScreenShot(String screenShotName, double positionSeconds, String videoLocation, int offsetSeconds)
        {
            lock (renderLock)
            {
                if (device == null)
                {
                    return;
                }

                int width  = offscreen.Description.Width;
                int height = offscreen.Description.Height;

                Rectangle sourceSize = new Rectangle(0, 0, width, height);
                Rectangle destSize   = calcOutputAspectRatio(sourceSize);

                if (screenShot.Description.Width != destSize.Width ||
                    screenShot.Description.Height != destSize.Height)
                {
                    Utils.removeAndDispose(ref screenShot);

                    screenShot = D3D.Surface.CreateRenderTarget(device,
                                                                destSize.Width,
                                                                destSize.Height,
                                                                D3D.Format.A8R8G8B8,
                                                                MultisampleType.None,
                                                                0,
                                                                true);
                }

                SharpDX.Rectangle sourceSizeDX = new SharpDX.Rectangle(0, 0, sourceSize.Width, sourceSize.Height);
                SharpDX.Rectangle destSizeDX   = new SharpDX.Rectangle(0, 0, destSize.Width, destSize.Height);

                device.StretchRectangle(offscreen, sourceSizeDX,
                                        screenShot, destSizeDX, D3D.TextureFilter.Linear);

                SharpDX.DataRectangle stream = screenShot.LockRectangle(destSizeDX, D3D.LockFlags.ReadOnly);
                try
                {
                    JpegBitmapEncoder encoder  = new JpegBitmapEncoder();
                    BitmapMetadata    metaData = new BitmapMetadata("jpg");

                    UriBuilder uri = new UriBuilder(new Uri(videoLocation).AbsoluteUri);

                    int seconds = (int)Math.Floor(Math.Max(positionSeconds + offsetSeconds, 0));

                    TimeSpan time       = new TimeSpan(0, 0, seconds);
                    String   timeString = "";

                    if (time.Days > 0)
                    {
                        timeString += time.Days + "d";
                    }

                    if (time.Hours > 0)
                    {
                        timeString += time.Hours + "h";
                    }

                    if (time.Minutes > 0)
                    {
                        timeString += time.Minutes + "m";
                    }

                    timeString += time.Seconds + "s";

                    uri.Query = "t=" + timeString;

                    metaData.ApplicationName = "MediaViewer v1.0";
                    metaData.Title           = uri.ToString();
                    metaData.DateTaken       = DateTime.Now.ToString("R");

                    BitmapSource image = System.Windows.Media.Imaging.BitmapSource.Create(
                        destSize.Width,
                        destSize.Height,
                        96,
                        96,
                        System.Windows.Media.PixelFormats.Bgra32,
                        null,
                        stream.DataPointer,
                        height * stream.Pitch,
                        stream.Pitch
                        );

                    float scale = ImageUtils.resizeRectangle(destSize.Width, destSize.Height, Constants.MAX_THUMBNAIL_WIDTH, Constants.MAX_THUMBNAIL_HEIGHT);

                    TransformedBitmap thumbnail = new TransformedBitmap(image, new System.Windows.Media.ScaleTransform(scale, scale));

                    encoder.Frames.Add(BitmapFrame.Create(image, thumbnail, metaData, null));

                    FileStream outputFile = new FileStream(screenShotName, FileMode.Create);
                    //encoder.QualityLevel = asyncState.JpegQuality;
                    encoder.Save(outputFile);

                    outputFile.Close();

                    System.Media.SystemSounds.Exclamation.Play();
                }
                catch (Exception e)
                {
                    throw new VideoPlayerException("Error creating screenshot: " + e.Message, e);
                }
                finally
                {
                    screenShot.UnlockRectangle();
                }
            }
        }