Esempio n. 1
0
        protected override void OnInit(object sender, EventArgs e)
        {
            //OdysseyUI.RemoveHooks(Global.FormOwner);

            ImageLoadInformation imageLoadInfo = new ImageLoadInformation()
            {
                BindFlags = BindFlags.None,
                CpuAccessFlags = CpuAccessFlags.Read,
                FilterFlags = FilterFlags.None,
                Format = SlimDX.DXGI.Format.R8G8B8A8_UNorm,
                MipFilterFlags = FilterFlags.None,
                OptionFlags = ResourceOptionFlags.None,
                Usage = ResourceUsage.Staging,
                MipLevels = 1
            };

            // Make texture 3D
            Texture2D sourceTexture = Texture2D.FromFile(Game.Context.Device, "medusa.jpg", imageLoadInfo);
            stereoTexture = Stereo.Make3D(sourceTexture);
            backBuffer = Game.Context.GetBackBuffer();

            stereoSourceBox = new ResourceRegion
                                  {
                                      Front = 0,
                                      Back = 1,
                                      Top = 0,
                                      Bottom = Game.Context.Settings.ScreenHeight,
                                      Left = 0,
                                      Right = Game.Context.Settings.ScreenWidth
                                  };
        }
Esempio n. 2
0
        protected StereoRenderer(IDeviceContext deviceContext)
            : base(deviceContext)
        {
            DeviceSettings settings = Game.Context.Settings;
            Camera = new StereoCamera();
            Camera.Reset();

            stereoSourceBox = new ResourceRegion
            {
                Front = 0,
                Back = 1,
                Top = 0,
                Bottom = settings.ScreenHeight,
                Left = 0,
                Right = settings.ScreenWidth
            };

            backBuffer = Game.Context.GetBackBuffer();
            cStereoRenderer = new RenderStereoTextureCommand(settings.ScreenWidth, settings.ScreenHeight, this);
        }
Esempio n. 3
0
        public IBitmapFrame Capture()
        {
            SharpDX.DXGI.Resource desktopResource;

            try
            {
                _deskDupl.AcquireNextFrame(Timeout, out _frameInfo, out desktopResource);
            }
            catch (SharpDXException e) when(e.Descriptor == SharpDX.DXGI.ResultCode.WaitTimeout)
            {
                return(RepeatFrame.Instance);
            }
            catch (SharpDXException e) when(e.ResultCode.Failure)
            {
                throw new Exception("Failed to acquire next frame.", e);
            }

            using (desktopResource)
            {
                using (var tempTexture = desktopResource.QueryInterface <Texture2D>())
                {
                    var resourceRegion = new ResourceRegion(_rect.Left, _rect.Top, 0, _rect.Right, _rect.Bottom, 1);

                    _device.ImmediateContext.CopySubresourceRegion(tempTexture, 0, resourceRegion, _desktopImageTexture, 0);
                }
            }

            ReleaseFrame();

            var mapSource = _device.ImmediateContext.MapSubresource(_desktopImageTexture, 0, MapMode.Read, MapFlags.None);

            try
            {
                return(new OneTimeFrame(ProcessFrame(mapSource.DataPointer, mapSource.RowPitch)));
            }
            finally
            {
                _device.ImmediateContext.UnmapSubresource(_desktopImageTexture, 0);
            }
        }
Esempio n. 4
0
        public unsafe override void SetData(IntPtr data, int dataSizeInBytes, int destinationOffsetInBytes)
        {
            if (dataSizeInBytes == 0)
            {
                return;
            }

            EnsureBufferSize(dataSizeInBytes + destinationOffsetInBytes);

            if (_resourceUsage == ResourceUsage.Dynamic)
            {
                DataBox db = Device.ImmediateContext.MapSubresource(Buffer, 0, MapMode.WriteNoOverwrite, MapFlags.None);
                {
                    SharpDX.Utilities.CopyMemory(
                        new IntPtr((byte *)db.DataPointer.ToPointer() + destinationOffsetInBytes),
                        new IntPtr((byte *)data),
                        dataSizeInBytes);
                }
                Device.ImmediateContext.UnmapSubresource(Buffer, 0);
            }
            else
            {
                ResourceRegion?subregion = null;
                if ((_bindFlags & BindFlags.ConstantBuffer) != BindFlags.ConstantBuffer)
                {
                    // For a shader-constant buffer; set pDstBox to null. It is not possible to use
                    // this method to partially update a shader-constant buffer

                    subregion = new ResourceRegion()
                    {
                        Left   = destinationOffsetInBytes,
                        Right  = dataSizeInBytes + destinationOffsetInBytes,
                        Bottom = 1,
                        Back   = 1
                    };
                }

                Device.ImmediateContext.UpdateSubresource(Buffer, 0, subregion, data, 0, 0);
            }
        }
Esempio n. 5
0
        protected override void CopyTextureCore(
            Texture source,
            uint srcX, uint srcY, uint srcZ,
            uint srcMipLevel,
            uint srcBaseArrayLayer,
            Texture destination,
            uint dstX, uint dstY, uint dstZ,
            uint dstMipLevel,
            uint dstBaseArrayLayer,
            uint width, uint height, uint depth,
            uint layerCount)
        {
            D3D11Texture srcD3D11Texture = Util.AssertSubtype <Texture, D3D11Texture>(source);
            D3D11Texture dstD3D11Texture = Util.AssertSubtype <Texture, D3D11Texture>(destination);

            ResourceRegion region = new ResourceRegion(
                (int)srcX,
                (int)srcY,
                (int)srcZ,
                (int)(srcX + width),
                (int)(srcY + height),
                (int)(srcZ + depth));

            for (uint i = 0; i < layerCount; i++)
            {
                int srcSubresource = D3D11Util.ComputeSubresource(srcMipLevel, source.MipLevels, srcBaseArrayLayer + i);
                int dstSubresource = D3D11Util.ComputeSubresource(dstMipLevel, destination.MipLevels, dstBaseArrayLayer + i);

                _context.CopySubresourceRegion(
                    srcD3D11Texture.DeviceTexture,
                    srcSubresource,
                    region,
                    dstD3D11Texture.DeviceTexture,
                    dstSubresource,
                    (int)dstX,
                    (int)dstY,
                    (int)dstZ);
            }
        }
        public void Update(DX11RenderContext context)
        {
            for (int i = 0; i < this.FOutGeom.SliceCount; i++)
            {
                if (this.FInEnabled[i])
                {
                    if (this.FInVCnt.IsChanged || this.FInICnt.IsChanged || this.FOutGeom[i].Contains(context) == false)
                    {
                        if (this.FOutGeom[i].Contains(context))
                        {
                            this.FOutGeom[i].Dispose(context);
                        }

                        this.FOutGeom[i][context] = new DX11NullGeometry(context);
                        DX11NullIndirectDrawer ind = new DX11NullIndirectDrawer();
                        ind.Update(context, this.FInVCnt[i], this.FInICnt[i]);
                        this.FOutGeom[i][context].AssignDrawer(ind);
                    }

                    DX11NullIndirectDrawer drawer = (DX11NullIndirectDrawer)this.FOutGeom[i][context].Drawer;

                    var argBuffer = drawer.IndirectArgs.Buffer;

                    if (this.FInI.IsConnected)
                    {
                        int            instOffset = this.FInInstOffset[i];
                        ResourceRegion region     = new ResourceRegion(instOffset, 0, 0, instOffset + 4, 1, 1);
                        context.CurrentDeviceContext.CopySubresourceRegion(this.FInI[i][context].Buffer, 0, region, argBuffer, 0, 4, 0, 0);
                    }

                    if (this.FInV.IsConnected)
                    {
                        int            vOffset = this.FInVtxOffset[i];
                        ResourceRegion region  = new ResourceRegion(vOffset, 0, 0, vOffset + 4, 1, 1);
                        context.CurrentDeviceContext.CopySubresourceRegion(this.FInV[i][context].Buffer, 0, region, argBuffer, 0, 0, 0, 0);
                    }
                }
            }
        }
Esempio n. 7
0
            public void UpdateColorImage(DeviceContext deviceContext, byte[] colorImage)
            {
                DataStream dataStream;

                deviceContext.MapSubresource(colorImageStagingTexture, 0,
                                             MapMode.WriteDiscard, SharpDX.Direct3D11.MapFlags.None, out dataStream);
                dataStream.WriteRange <byte>(colorImage, 0, Kinect2Calibration.colorImageWidth * Kinect2Calibration.colorImageHeight * 4);
                deviceContext.UnmapSubresource(colorImageStagingTexture, 0);

                var resourceRegion = new ResourceRegion()
                {
                    Left   = 0,
                    Top    = 0,
                    Right  = Kinect2Calibration.colorImageWidth,
                    Bottom = Kinect2Calibration.colorImageHeight,
                    Front  = 0,
                    Back   = 1,
                };

                deviceContext.CopySubresourceRegion(colorImageStagingTexture, 0, resourceRegion, colorImageTexture, 0);
                deviceContext.GenerateMips(colorImageTextureRV);
            }
Esempio n. 8
0
 // Method to marshal from native to managed struct
 internal unsafe void __MarshalFrom(ref __Native @ref)
 {
     this.SourceRegionPointer      = @ref.SourceRegionPointer;
     this.DestinationRegionPointer = @ref.DestinationRegionPointer;
     this.FirstSourceMip           = @ref.FirstSourceMip;
     this.FirstDestinationMip      = @ref.FirstDestinationMip;
     this.MipCount                = @ref.MipCount;
     this.FirstSourceElement      = @ref.FirstSourceElement;
     this.FirstDestinationElement = @ref.FirstDestinationElement;
     this.ElementCount            = @ref.ElementCount;
     this.Filter       = @ref.Filter;
     this.MipFilter    = @ref.MipFilter;
     this.SourceRegion = new ResourceRegion();
     if (@ref.SourceRegionPointer != IntPtr.Zero)
     {
         Utilities.Read <ResourceRegion>(@ref.SourceRegionPointer, ref this.SourceRegion);
     }
     this.DestinationRegion = new ResourceRegion();
     if (@ref.DestinationRegionPointer != IntPtr.Zero)
     {
         Utilities.Read <ResourceRegion>(@ref.DestinationRegionPointer, ref this.DestinationRegion);
     }
 }
Esempio n. 9
0
        private void PlatformSetData <T>(int level,
                                         int left, int top, int right, int bottom, int front, int back,
                                         T[] data, int startIndex, int elementCount, int width, int height, int depth)
        {
            var elementSizeInByte = Marshal.SizeOf(typeof(T));
            var dataHandle        = GCHandle.Alloc(data, GCHandleType.Pinned);
            var dataPtr           = (IntPtr)(dataHandle.AddrOfPinnedObject().ToInt64() + startIndex * elementSizeInByte);

            int rowPitch   = GetPitch(width);
            int slicePitch = rowPitch * height; // For 3D texture: Size of 2D image.
            var box        = new DataBox(dataPtr, rowPitch, slicePitch);

            int subresourceIndex = level;

            var region = new ResourceRegion(left, top, front, right, bottom, back);

            var d3dContext = GraphicsDevice._d3dContext;

            lock (d3dContext)
                d3dContext.UpdateSubresource(box, GetTexture(), subresourceIndex, region);

            dataHandle.Free();
        }
Esempio n. 10
0
        internal unsafe void UpdateGeneric(List <MyInstanceData> instanceData, int capacity)
        {
            var instancesNum = instanceData.Count;

            if (m_capacity < instancesNum && VertexBuffer != VertexBufferId.NULL)
            {
                MyHwBuffers.Destroy(VertexBuffer);
                VertexBuffer = VertexBufferId.NULL;
            }
            if (m_capacity < instancesNum)
            {
                m_capacity   = Math.Max(instancesNum, capacity);
                VertexBuffer = MyHwBuffers.CreateVertexBuffer(m_capacity, sizeof(MyVertexFormatGenericInstance), null, m_debugName + " instances buffer");
            }

            fixed(MyInstanceData *dataPtr = instanceData.ToArray())
            {
                DataBox        srcBox    = new DataBox(new IntPtr(dataPtr));
                ResourceRegion dstRegion = new ResourceRegion(0, 0, 0, sizeof(MyVertexFormatGenericInstance) * instancesNum, 1, 1);

                MyRender11.ImmediateContext.UpdateSubresource(srcBox, VertexBuffer.Buffer, 0, dstRegion);
            }
        }
Esempio n. 11
0
        public void SetData <T> (int level,
                                 int left, int top, int right, int bottom, int front, int back,
                                 T[] data, int startIndex, int elementCount) where T : struct
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }
#if !PORTABLE
            var elementSizeInByte = Marshal.SizeOf(typeof(T));
            var dataHandle        = GCHandle.Alloc(data, GCHandleType.Pinned);
            var dataPtr           = (IntPtr)(dataHandle.AddrOfPinnedObject().ToInt64() + startIndex * elementSizeInByte);
            int width             = right - left;
            int height            = bottom - top;
            int depth             = back - front;

#if OPENGL
            GL.BindTexture(glTarget, glTexture);
            GraphicsExtensions.CheckGLError();
            GL.TexSubImage3D(glTarget, level, left, top, front, width, height, depth, glFormat, glType, dataPtr);
            GraphicsExtensions.CheckGLError();
#elif DIRECTX
            int rowPitch   = GetPitch(width);
            int slicePitch = rowPitch * height; // For 3D texture: Size of 2D image.
            var box        = new DataBox(dataPtr, rowPitch, slicePitch);

            int subresourceIndex = level;

            var region = new ResourceRegion(left, top, front, right, bottom, back);

            var d3dContext = GraphicsDevice._d3dContext;
            lock (d3dContext)
                d3dContext.UpdateSubresource(box, GetTexture(), subresourceIndex, region);
#endif
            dataHandle.Free();
#endif
        }
        public void Update(IPluginIO pin, DX11RenderContext context)
        {
            for (int i = 0; i < this.FOutGeom.SliceCount; i++)
            {
                DX11VertexGeometry geom = (DX11VertexGeometry)this.FInGeom[i][context].ShallowCopy();

                if (this.FInEnabled[i])
                {
                    if (this.FInGeom.IsChanged || this.FInCnt.IsChanged)
                    {
                        DX11VertexIndirectDrawer ind = new DX11VertexIndirectDrawer();
                        geom.AssignDrawer(ind);

                        ind.Update(context, this.FInCnt[i]);
                    }

                    DX11VertexIndirectDrawer drawer = (DX11VertexIndirectDrawer)geom.Drawer;
                    var argBuffer = drawer.IndirectArgs.Buffer;

                    if (this.FInI.PluginIO.IsConnected)
                    {
                        int            instOffset = this.FInInstOffset[i];
                        ResourceRegion region     = new ResourceRegion(instOffset, 0, 0, instOffset + 4, 1, 1);
                        context.CurrentDeviceContext.CopySubresourceRegion(this.FInI[i][context].Buffer, 0, region, argBuffer, 0, 4, 0, 0);
                    }

                    if (this.FInV.PluginIO.IsConnected)
                    {
                        int            vOffset = this.FInVtxOffset[i];
                        ResourceRegion region  = new ResourceRegion(vOffset, 0, 0, vOffset + 4, 1, 1);
                        context.CurrentDeviceContext.CopySubresourceRegion(this.FInV[i][context].Buffer, 0, region, argBuffer, 0, 0, 0, 0);
                    }

                    this.FOutGeom[i][context] = geom;
                }
            }
        }
Esempio n. 13
0
        /// <summary>
        /// Copies the content an array of data on CPU memory to this buffer into GPU memory.
        /// </summary>
        /// <param name="buffer">The buffer to update.</param>
        /// <param name="device">The <see cref="SharpDX.Direct3D11.Device"/>.</param>
        /// <param name="fromData">A data pointer.</param>
        /// <param name="offsetInBytes">The offset in bytes to write to.</param>
        /// <param name="mode">Buffer data behavior.</param>
        /// <exception cref="System.ArgumentException"></exception>
        /// <msdn-id>ff476457</msdn-id>
        ///   <unmanaged>HRESULT ID3D11DeviceContext::Map([In] ID3D11Resource* pResource,[In] unsigned int Subresource,[In] D3D11_MAP MapType,[In] D3D11_MAP_FLAG MapFlags,[Out] D3D11_MAPPED_SUBRESOURCE* pMappedResource)</unmanaged>
        ///   <unmanaged-short>ID3D11DeviceContext::Map</unmanaged-short>
        /// <remarks>
        /// See the unmanaged documentation about Map/UnMap for usage and restrictions.
        /// </remarks>
        public static unsafe void SetData(this Buffer buffer, SharpDX.Direct3D11.Device device, DataPointer fromData, int offsetInBytes = 0, MapMode mode = MapMode.WriteDiscard)
        {
            // Check size validity of data to copy to
            if ((fromData.Size + offsetInBytes) > buffer.Description.SizeInBytes)
            {
                throw new ArgumentException("Size of data to upload + offset is larger than size of buffer");
            }

            var deviceContext = (SharpDX.Direct3D11.DeviceContext)device.ImmediateContext;

            // If this bufefer is declared as default usage, we can only use UpdateSubresource, which is not optimal but better than nothing
            if (buffer.Description.Usage == ResourceUsage.Default)
            {
                // Setup the dest region inside the buffer
                if ((buffer.Description.BindFlags & BindFlags.ConstantBuffer) != 0)
                {
                    deviceContext.UpdateSubresource(new DataBox(fromData.Pointer, 0, 0), buffer);
                }
                else
                {
                    var destRegion = new ResourceRegion(offsetInBytes, 0, 0, offsetInBytes + fromData.Size, 1, 1);
                    deviceContext.UpdateSubresource(new DataBox(fromData.Pointer, 0, 0), buffer, 0, destRegion);
                }
            }
            else
            {
                try
                {
                    var box = deviceContext.MapSubresource(buffer, 0, mode, SharpDX.Direct3D11.MapFlags.None);
                    Utilities.CopyMemory((IntPtr)((byte *)box.DataPointer + offsetInBytes), fromData.Pointer, fromData.Size);
                }
                finally
                {
                    deviceContext.UnmapSubresource(buffer, 0);
                }
            }
        }
Esempio n. 14
0
        private unsafe void PlatformSetData <T>(
            CubeMapFace face, int level, Rectangle rect, ReadOnlySpan <T> data)
            where T : unmanaged
        {
            var subresourceIndex = CalculateSubresourceIndex(face, level);
            int pitch            = GetPitch(rect.Width);
            var region           = new ResourceRegion
            {
                Top    = rect.Top,
                Front  = 0,
                Back   = 1,
                Bottom = rect.Bottom,
                Left   = rect.Left,
                Right  = rect.Right
            };

            var d3dContext = GraphicsDevice._d3dContext;

            lock (d3dContext)
            {
                var     texture     = GetTexture();
                ref var mutableData = ref MemoryMarshal.GetReference(data);
                d3dContext.UpdateSubresource(ref mutableData, texture, subresourceIndex, pitch, 0, region);
            }
Esempio n. 15
0
        public unsafe override void UpdateBuffer(DeviceBuffer buffer, uint bufferOffsetInBytes, IntPtr source, uint sizeInBytes)
        {
            D3D11Buffer d3dBuffer = Util.AssertSubtype <DeviceBuffer, D3D11Buffer>(buffer);

            if (sizeInBytes == 0)
            {
                return;
            }

            bool isDynamic = (buffer.Usage & BufferUsage.Dynamic) == BufferUsage.Dynamic;
            bool isStaging = (buffer.Usage & BufferUsage.Staging) == BufferUsage.Staging;
            bool useMap    = isDynamic || isStaging;

            if (!useMap)
            {
                ResourceRegion?subregion = null;
                if ((d3dBuffer.Buffer.Description.BindFlags & BindFlags.ConstantBuffer) != BindFlags.ConstantBuffer)
                {
                    // For a shader-constant buffer; set pDstBox to null. It is not possible to use
                    // this method to partially update a shader-constant buffer

                    subregion = new ResourceRegion()
                    {
                        Left   = (int)bufferOffsetInBytes,
                        Right  = (int)(sizeInBytes + bufferOffsetInBytes),
                        Bottom = 1,
                        Back   = 1
                    };
                }

                if (bufferOffsetInBytes == 0)
                {
                    _context.UpdateSubresource(d3dBuffer.Buffer, 0, subregion, source, 0, 0);
                }
                else
                {
                    _context1.UpdateSubresource1(d3dBuffer.Buffer, 0, subregion, source, 0, 0, 0);
                }
            }
            else
            {
                bool updateFullBuffer = bufferOffsetInBytes == 0 && sizeInBytes == buffer.SizeInBytes;
                if (updateFullBuffer && isDynamic)
                {
                    SharpDX.DataBox db = _context.MapSubresource(
                        d3dBuffer.Buffer,
                        0,
                        SharpDX.Direct3D11.MapMode.WriteDiscard,
                        MapFlags.None);
                    if (sizeInBytes < 1024)
                    {
                        Unsafe.CopyBlock(db.DataPointer.ToPointer(), source.ToPointer(), sizeInBytes);
                    }
                    else
                    {
                        System.Buffer.MemoryCopy(source.ToPointer(), db.DataPointer.ToPointer(), buffer.SizeInBytes, sizeInBytes);
                    }
                    _context.UnmapSubresource(d3dBuffer.Buffer, 0);
                }
                else
                {
                    D3D11Buffer staging = GetFreeStagingBuffer(sizeInBytes);
                    _gd.UpdateBuffer(staging, 0, source, sizeInBytes);
                    CopyBuffer(staging, 0, buffer, bufferOffsetInBytes, sizeInBytes);
                    _submittedStagingBuffers.Add(staging);
                }
            }
        }
Esempio n. 16
0
 public void Render(DX11RenderContext context, DX11RenderSettings settings)
 {
     if (this.FEnabled[0])
     {
         if (this.FLayerIn.IsConnected)
         {
             var spreadmax = Math.Max(FSrcSem.SliceCount, FDstSem.SliceCount);
             for (int i = 0; i < spreadmax; i++)
             {
                 RWStructuredBufferRenderSemantic srcccrs = null;
                 foreach (var rsem in settings.CustomSemantics)
                 {
                     if (rsem.Semantic == FSrcSem[i])
                     {
                         if (rsem is RWStructuredBufferRenderSemantic)
                         {
                             srcccrs = rsem as RWStructuredBufferRenderSemantic;
                             break;
                         }
                     }
                 }
                 IDX11RWResource dstccrs = null;
                 foreach (var rsem in settings.CustomSemantics)
                 {
                     if (rsem.Semantic == FDstSem[i])
                     {
                         if (rsem is RWStructuredBufferRenderSemantic)
                         {
                             var t = rsem as RWStructuredBufferRenderSemantic;
                             dstccrs = t.Data;
                             break;
                         }
                     }
                 }
                 if ((srcccrs != null) && (dstccrs != null))
                 {
                     var srcbuf = srcccrs.Data as DX11RWStructuredBuffer;
                     if (srcbuf != null)
                     {
                         UnorderedAccessView uav = srcbuf.UAV;
                         Buffer dstbuf           = null;
                         if (dstccrs is DX11RWStructuredBuffer)
                         {
                             var t = dstccrs as DX11RWStructuredBuffer;
                             dstbuf = t.Buffer;
                         }
                         if (dstbuf != null)
                         {
                             if (FCopyRegion[i])
                             {
                                 var region = new ResourceRegion(FSrcFrom[i], 0, 0, FSrcTo[i], 1, 1);
                                 context.CurrentDeviceContext.CopySubresourceRegion(srcbuf.Buffer, 0, region, dstbuf, 0, FDstFrom[i], 0, 0);
                             }
                             else
                             {
                                 context.CurrentDeviceContext.CopyResource(srcbuf.Buffer, dstbuf);
                             }
                         }
                     }
                 }
             }
             FLayerIn[0][context].Render(context, settings);
         }
     }
 }
Esempio n. 17
0
        public static Texture2D Make3D(Texture2D leftTexture, Texture2D rightTexture)
        {
            SlimDX.Direct3D11.Device device = Game.Context.Device;
            Size screenSize = Game.Context.Settings.ScreenSize;
            Texture2DDescription stagingDesc = new Texture2DDescription()
            {
                ArraySize = 1,
                Width = 2 * screenSize.Width,
                Height = screenSize.Height + 1,
                BindFlags = BindFlags.None,
                CpuAccessFlags = CpuAccessFlags.Write,
                Format = Format.R8G8B8A8_UNorm,
                OptionFlags = ResourceOptionFlags.None,
                Usage = ResourceUsage.Staging,
                MipLevels = 1,
                SampleDescription = new SampleDescription(1, 0)
            };
            if (staging == null)
                staging = new Texture2D(device, stagingDesc);
            ResourceRegion stereoSrcBoxLeft = new ResourceRegion
            {
                Front = 0,
                Back = 1,
                Top = 0,
                Bottom = screenSize.Height,
                Left = 0,
                Right = screenSize.Width
            };
            ResourceRegion stereoSrcBoxRight = new ResourceRegion
            {
                Front = 0,
                Back = 1,
                Top = 0,
                Bottom = screenSize.Height,
                Left = screenSize.Width,
                Right = 2*screenSize.Width
            };
            device.ImmediateContext.CopySubresourceRegion(leftTexture, 0, stereoSrcBoxLeft, staging, 0, 0, 0, 0);
            device.ImmediateContext.CopySubresourceRegion(rightTexture, 0, stereoSrcBoxLeft, staging, 0, screenSize.Width, 0, 0);
            DataBox box = device.ImmediateContext.MapSubresource(staging, 0, MapMode.Write, SlimDX.Direct3D11.MapFlags.None);

            box.Data.Seek(box.RowPitch * screenSize.Height, System.IO.SeekOrigin.Begin);
            box.Data.Write(nvHeader.ToByteArray(), 0, data.Length);
            device.ImmediateContext.UnmapSubresource(staging, 0);

            // Create the final stereoized texture
            Texture2DDescription finalDesc = new Texture2DDescription()
            {
                ArraySize = 1,
                Width = 2 * screenSize.Width,
                Height = screenSize.Height + 1,
                BindFlags = BindFlags.ShaderResource,
                CpuAccessFlags = CpuAccessFlags.Write,
                Format = SlimDX.DXGI.Format.R8G8B8A8_UNorm,
                OptionFlags = ResourceOptionFlags.None,
                Usage = ResourceUsage.Dynamic,
                MipLevels = 1,
                SampleDescription = new SampleDescription(1, 0),
            };

            // Copy the staging texture on a new texture to be used as a shader resource
            Texture2D final = new Texture2D(device, finalDesc);
            device.ImmediateContext.CopyResource(staging, final);
            //staging.Dispose();
            return final;
        }
Esempio n. 18
0
        protected internal void GetCursor(Texture2D screenTexture, OutputDuplicateFrameInformation info, FrameInfo frame)
        {
            //Prepare buffer array to hold the cursor shape.
            if (CursorShapeBuffer == null || info.PointerShapeBufferSize > CursorShapeBuffer.Length)
            {
                CursorShapeBuffer = new byte[info.PointerShapeBufferSize];
            }

            //If there's a cursor shape available to be captured.
            if (info.PointerShapeBufferSize > 0)
            {
                //Pin the buffer in order to pass the address as parameter later.
                var pinnedBuffer        = GCHandle.Alloc(CursorShapeBuffer, GCHandleType.Pinned);
                var cursorBufferAddress = pinnedBuffer.AddrOfPinnedObject();

                //Load the cursor shape into the buffer.
                DuplicatedOutput.GetFramePointerShape(info.PointerShapeBufferSize, cursorBufferAddress, out _, out CursorShapeInfo);

                //If the cursor is monochrome, it will return the cursor shape twice, one is the mask.
                if (CursorShapeInfo.Type == 1)
                {
                    CursorShapeInfo.Height /= 2;
                }

                //The buffer must be unpinned, to free resources.
                pinnedBuffer.Free();
            }

            //Store the current cursor position, if it was moved.
            if (info.LastMouseUpdateTime != 0)
            {
                PreviousPosition = info.PointerPosition;
            }

            //TODO: In a future version, don't merge the cursor image in here, let the editor do that.
            //Saves the position of the cursor, so the editor can add the mouse clicks overlay later.
            frame.CursorX = PreviousPosition.Position.X - Left;
            frame.CursorY = PreviousPosition.Position.Y - Top;

            //If the method is supposed to simply the get the cursor shape no shape was loaded before, there's nothing else to do.
            //if (CursorShapeBuffer?.Length == 0 || (info.LastPresentTime == 0 && info.LastMouseUpdateTime == 0) || !info.PointerPosition.Visible)
            if (screenTexture == null || CursorShapeBuffer?.Length == 0)// || !info.PointerPosition.Visible)
            {
                return;
            }

            //Don't let it bleed beyond the top-left corner.
            var left    = Math.Max(frame.CursorX, 0);
            var top     = Math.Max(frame.CursorY, 0);
            var offsetX = Math.Abs(Math.Min(0, frame.CursorX));
            var offsetY = Math.Abs(Math.Min(0, frame.CursorY));

            //Adjust the offset, so it's possible to add the highlight correctly later.
            frame.CursorX += CursorShapeInfo.HotSpot.X;
            frame.CursorY += CursorShapeInfo.HotSpot.Y;

            if (CursorShapeInfo.Width - offsetX < 0 || CursorShapeInfo.Height - offsetY < 0)
            {
                return;
            }

            //The staging texture must be able to hold all pixels.
            if (CursorStagingTexture == null || CursorStagingTexture.Description.Width < CursorShapeInfo.Width - offsetX || CursorStagingTexture.Description.Height < CursorShapeInfo.Height - offsetY)
            {
                //In order to change the size of the texture, I need to instantiate it again with the new size.
                CursorStagingTexture?.Dispose();
                CursorStagingTexture = new Texture2D(Device, new Texture2DDescription
                {
                    ArraySize         = 1,
                    BindFlags         = BindFlags.None,
                    CpuAccessFlags    = CpuAccessFlags.Write,
                    Height            = CursorShapeInfo.Height - offsetY,
                    Format            = Format.B8G8R8A8_UNorm,
                    Width             = CursorShapeInfo.Width - offsetX,
                    MipLevels         = 1,
                    OptionFlags       = ResourceOptionFlags.None,
                    SampleDescription = new SampleDescription(1, 0),
                    Usage             = ResourceUsage.Staging
                });
            }

            //The region where the cursor is located is copied to the staging texture to act as the background when dealing with masks and transparency.
            var region = new ResourceRegion
            {
                Left   = left,
                Top    = top,
                Front  = 0,
                Right  = left + CursorStagingTexture.Description.Width,
                Bottom = top + CursorStagingTexture.Description.Height,
                Back   = 1
            };

            //Copy from the screen the region in which the cursor is located.
            Device.ImmediateContext.CopySubresourceRegion(screenTexture, 0, region, CursorStagingTexture, 0);

            //Get cursor details and draw it to the staging texture.
            DrawCursorShape(CursorStagingTexture, CursorShapeInfo, CursorShapeBuffer, offsetX, offsetY);

            //Copy back the cursor texture to the screen texture.
            Device.ImmediateContext.CopySubresourceRegion(CursorStagingTexture, 0, null, screenTexture, 0, left, top);
        }
Esempio n. 19
0
        protected unsafe override void UpdateBufferCore(DeviceBuffer buffer, uint bufferOffsetInBytes, IntPtr source, uint sizeInBytes)
        {
            D3D11Buffer d3dBuffer = Util.AssertSubtype <DeviceBuffer, D3D11Buffer>(buffer);

            if (sizeInBytes == 0)
            {
                return;
            }

            bool isDynamic            = (buffer.Usage & BufferUsage.Dynamic) == BufferUsage.Dynamic;
            bool isStaging            = (buffer.Usage & BufferUsage.Staging) == BufferUsage.Staging;
            bool isUniformBuffer      = (buffer.Usage & BufferUsage.UniformBuffer) == BufferUsage.UniformBuffer;
            bool updateFullBuffer     = bufferOffsetInBytes == 0 && sizeInBytes == buffer.SizeInBytes;
            bool useUpdateSubresource = (!isDynamic && !isStaging) && (!isUniformBuffer || updateFullBuffer);
            bool useMap = (isDynamic && updateFullBuffer) || isStaging;

            if (useUpdateSubresource)
            {
                ResourceRegion?subregion = new ResourceRegion()
                {
                    Left   = (int)bufferOffsetInBytes,
                    Right  = (int)(sizeInBytes + bufferOffsetInBytes),
                    Bottom = 1,
                    Back   = 1
                };

                if (isUniformBuffer)
                {
                    subregion = null;
                }

                lock (_immediateContextLock)
                {
                    _immediateContext.UpdateSubresource(d3dBuffer.Buffer, 0, subregion, source, 0, 0);
                }
            }
            else if (useMap)
            {
                MappedResource mr = MapCore(buffer, MapMode.Write, 0);
                if (sizeInBytes < 1024)
                {
                    Unsafe.CopyBlock((byte *)mr.Data + bufferOffsetInBytes, source.ToPointer(), sizeInBytes);
                }
                else
                {
                    System.Buffer.MemoryCopy(
                        source.ToPointer(),
                        (byte *)mr.Data + bufferOffsetInBytes,
                        buffer.SizeInBytes,
                        sizeInBytes);
                }
                UnmapCore(buffer, 0);
            }
            else
            {
                D3D11Buffer staging = GetFreeStagingBuffer(sizeInBytes);
                UpdateBuffer(staging, 0, source, sizeInBytes);
                ResourceRegion sourceRegion = new ResourceRegion(0, 0, 0, (int)sizeInBytes, 1, 1);
                lock (_immediateContextLock)
                {
                    _immediateContext.CopySubresourceRegion(
                        staging.Buffer, 0, sourceRegion,
                        d3dBuffer.Buffer, 0,
                        (int)bufferOffsetInBytes, 0, 0);
                }

                lock (_stagingResourcesLock)
                {
                    _availableStagingBuffers.Add(staging);
                }
            }
        }
Esempio n. 20
0
        void RenderLoop()
        {
            while (true)
            {
                lock (renderLock)
                {
                    var deviceContext = device.ImmediateContext;

                    // render user view
                    deviceContext.ClearRenderTargetView(userViewRenderTargetView, Color4.Black);
                    deviceContext.ClearDepthStencilView(userViewDepthStencilView, DepthStencilClearFlags.Depth, 1, 0);

                    SharpDX.Vector3 headPosition = new SharpDX.Vector3(0f, 1.1f, -1.4f);  // may need to change this default

                    if (localHeadTrackingEnabled)
                    {
                        float distanceSquared = 0;
                        lock (headCameraSpacePointLock)
                        {
                            headPosition = new SharpDX.Vector3(headCameraSpacePoint.X, headCameraSpacePoint.Y, headCameraSpacePoint.Z);

                            float dx = handLeftCameraSpacePoint.X - handRightCameraSpacePoint.X;
                            float dy = handLeftCameraSpacePoint.Y - handRightCameraSpacePoint.Y;
                            float dz = handLeftCameraSpacePoint.Z - handRightCameraSpacePoint.Z;
                            distanceSquared = dx * dx + dy * dy + dz * dz;
                        }
                        var transform = SharpDX.Matrix.RotationY((float)Math.PI) * SharpDX.Matrix.Translation(-0.25f, 0.45f, 0);
                        headPosition = SharpDX.Vector3.TransformCoordinate(headPosition, transform);

                        if (trackingValid && (distanceSquared < 0.02f) && (alpha > 1))
                        {
                            alpha = 0;
                        }
                        //Console.WriteLine(distanceSquared);
                    }

                    var userView = GraphicsTransforms.LookAt(headPosition, headPosition + SharpDX.Vector3.UnitZ, SharpDX.Vector3.UnitY);
                    userView.Transpose();


                    //Console.WriteLine("headPosition = " + headPosition);


                    float aspect         = (float)userViewTextureWidth / (float)userViewTextureHeight;
                    var   userProjection = GraphicsTransforms.PerspectiveFov(55.0f / 180.0f * (float)Math.PI, aspect, 0.001f, 1000.0f);
                    userProjection.Transpose();

                    // smooth depth images
                    foreach (var camera in ensemble.cameras)
                    {
                        var cameraDeviceResource = cameraDeviceResources[camera];
                        if (cameraDeviceResource.depthImageChanged)
                        {
                            fromUIntPS.Render(deviceContext, cameraDeviceResource.depthImageTextureRV, cameraDeviceResource.floatDepthImageRenderTargetView);
                            for (int i = 0; i < 1; i++)
                            {
                                bilateralFilter.Render(deviceContext, cameraDeviceResource.floatDepthImageRV, cameraDeviceResource.floatDepthImageRenderTargetView2);
                                bilateralFilter.Render(deviceContext, cameraDeviceResource.floatDepthImageRV2, cameraDeviceResource.floatDepthImageRenderTargetView);
                            }
                            cameraDeviceResource.depthImageChanged = false;
                        }
                    }

                    // wobble effect
                    if (wobbleEffectEnabled)
                    {
                        foreach (var camera in ensemble.cameras)
                        {
                            var cameraDeviceResource = cameraDeviceResources[camera];

                            var world = new SharpDX.Matrix();
                            for (int i = 0; i < 4; i++)
                            {
                                for (int j = 0; j < 4; j++)
                                {
                                    world[i, j] = (float)camera.pose[i, j];
                                }
                            }
                            world.Transpose();

                            // view and projection matrix are post-multiply
                            var userWorldViewProjection = world * userView * userProjection;

                            depthAndColorShader.SetConstants(deviceContext, camera.calibration, userWorldViewProjection);
                            depthAndColorShader.Render(deviceContext, cameraDeviceResource.floatDepthImageRV, cameraDeviceResource.colorImageTextureRV, cameraDeviceResource.vertexBuffer, userViewRenderTargetView, userViewDepthStencilView, userViewViewport);
                        }
                    }

                    // 3d object
                    if (threeDObjectEnabled)
                    {
                        var world = SharpDX.Matrix.Scaling(1.0f) * SharpDX.Matrix.RotationY(90.0f / 180.0f * (float)Math.PI) *
                                    SharpDX.Matrix.RotationX(-40.0f / 180.0f * (float)Math.PI) * SharpDX.Matrix.Translation(0, 0.7f, 0.0f);

                        var pointLight = new PointLight();
                        pointLight.position = new Vector3(0, 2, 0);
                        pointLight.Ia       = new Vector3(0.1f, 0.1f, 0.1f);
                        meshShader.SetVertexShaderConstants(deviceContext, world, userView * userProjection, pointLight.position);
                        meshShader.Render(deviceContext, meshDeviceResources, pointLight, userViewRenderTargetView, userViewDepthStencilView, userViewViewport);
                    }

                    // wobble effect
                    if (wobbleEffectEnabled)
                    {
                        alpha += 0.05f;
                        if (alpha > 1)
                        {
                            radialWobbleShader.SetConstants(deviceContext, 0);
                        }
                        else
                        {
                            radialWobbleShader.SetConstants(deviceContext, alpha);
                        }
                        radialWobbleShader.Render(deviceContext, userViewSRV, filteredUserViewRenderTargetView);
                    }


                    // desktop duplication
                    if (desktopDuplicationEnabled)
                    {
                        var outputDuplicateFrameInformation = default(OutputDuplicateFrameInformation);
                        SharpDX.DXGI.Resource resource      = null;
                        outputDuplication.AcquireNextFrame(1000, out outputDuplicateFrameInformation, out resource);
                        var texture = resource.QueryInterface <Texture2D>();

                        var rect = new RECT();
                        GetWindowRect(windowPtr, out rect);

                        var sourceRegion = new ResourceRegion()
                        {
                            Left   = rect.Left + leftNudge,
                            Right  = rect.Right + rightNudge,
                            Top    = rect.Top + topNudge,
                            Bottom = rect.Bottom + bottomNudge,
                            Front  = 0,
                            Back   = 1,
                        };
                        deviceContext.CopySubresourceRegion(texture, 0, sourceRegion, desktopTexture, 0);
                        texture.Dispose();
                    }


                    // render user view to seperate form
                    passThroughShader.viewport = new Viewport(0, 0, userViewForm.Width, userViewForm.Height);
                    // TODO: clean this up by simply using a pointer to the userViewSRV
                    if (threeDObjectEnabled)
                    {
                        passThroughShader.Render(deviceContext, userViewSRV, userViewForm.renderTargetView);
                    }
                    if (wobbleEffectEnabled)
                    {
                        passThroughShader.Render(deviceContext, filteredUserViewSRV, userViewForm.renderTargetView);
                    }
                    if (desktopDuplicationEnabled)
                    {
                        passThroughShader.Render(deviceContext, desktopTextureSRV, userViewForm.renderTargetView);
                    }
                    userViewForm.swapChain.Present(0, PresentFlags.None);

                    // projection puts x and y in [-1,1]; adjust to obtain texture coordinates [0,1]
                    // TODO: put this in SetContants?
                    userProjection[0, 0] /= 2;
                    userProjection[1, 1] /= -2; // y points down
                    userProjection[2, 0] += 0.5f;
                    userProjection[2, 1] += 0.5f;

                    // projection mapping for each projector
                    foreach (var form in projectorForms)
                    {
                        deviceContext.ClearRenderTargetView(form.renderTargetView, Color4.Black);
                        deviceContext.ClearDepthStencilView(form.depthStencilView, DepthStencilClearFlags.Depth, 1, 0);

                        foreach (var camera in ensemble.cameras)
                        {
                            var cameraDeviceResource = cameraDeviceResources[camera];

                            var world = new SharpDX.Matrix();
                            for (int i = 0; i < 4; i++)
                            {
                                for (int j = 0; j < 4; j++)
                                {
                                    world[i, j] = (float)camera.pose[i, j];
                                }
                            }
                            world.Transpose();

                            var projectorWorldViewProjection = world * form.view * form.projection;
                            var userWorldViewProjection      = world * userView * userProjection;

                            projectiveTexturingShader.SetConstants(deviceContext, userWorldViewProjection, projectorWorldViewProjection);

                            // TODO: clean this up by simply using a pointer to the userViewSRV
                            if (wobbleEffectEnabled)
                            {
                                projectiveTexturingShader.Render(deviceContext, cameraDeviceResource.floatDepthImageRV, filteredUserViewSRV, cameraDeviceResource.vertexBuffer, form.renderTargetView, form.depthStencilView, form.viewport);
                            }
                            if (threeDObjectEnabled)
                            {
                                projectiveTexturingShader.Render(deviceContext, cameraDeviceResource.floatDepthImageRV, userViewSRV, cameraDeviceResource.vertexBuffer, form.renderTargetView, form.depthStencilView, form.viewport);
                            }
                            if (desktopDuplicationEnabled)
                            {
                                projectiveTexturingShader.Render(deviceContext, cameraDeviceResource.floatDepthImageRV, desktopTextureSRV, cameraDeviceResource.vertexBuffer, form.renderTargetView, form.depthStencilView, form.viewport);
                            }
                        }

                        form.swapChain.Present(1, PresentFlags.None);
                    }


                    if (desktopDuplicationEnabled)
                    {
                        outputDuplication.ReleaseFrame();
                    }


                    Console.WriteLine(stopwatch.ElapsedMilliseconds);
                    stopwatch.Restart();
                }
            }
        }
Esempio n. 21
0
        void RenderLoop()
        {
            while (true)
            {
                lock (renderLock)
                {
                    var deviceContext = device.ImmediateContext;

                    // render user view
                    deviceContext.ClearRenderTargetView(userViewRenderTargetView, Color4.Black);
                    deviceContext.ClearDepthStencilView(userViewDepthStencilView, DepthStencilClearFlags.Depth, 1, 0);

                    SharpDX.Vector3 headPosition = new SharpDX.Vector3(0f, 1.1f, -1.4f);  // may need to change this default

                    if (localHeadTrackingEnabled)
                    {
                        float distanceSquared = 0;
                        lock (headCameraSpacePointLock)
                        {
                            headPosition = new SharpDX.Vector3(headCameraSpacePoint.X, headCameraSpacePoint.Y, headCameraSpacePoint.Z);

                            float dx = handLeftCameraSpacePoint.X - handRightCameraSpacePoint.X;
                            float dy = handLeftCameraSpacePoint.Y - handRightCameraSpacePoint.Y;
                            float dz = handLeftCameraSpacePoint.Z - handRightCameraSpacePoint.Z;
                            distanceSquared = dx * dx + dy * dy + dz * dz;
                        }
                        var transform = SharpDX.Matrix.RotationY((float)Math.PI) * SharpDX.Matrix.Translation(0, 0.45f, 0);
                        headPosition = SharpDX.Vector3.TransformCoordinate(headPosition, transform);

                        if (trackingValid && (distanceSquared < 0.02f) && (alpha > 1))
                        {
                            alpha = 0;
                        }
                        //Console.WriteLine(distanceSquared);
                    }

                    var userView = GraphicsTransforms.LookAt(headPosition, headPosition + SharpDX.Vector3.UnitZ, SharpDX.Vector3.UnitY);
                    userView.Transpose();


                    //Console.WriteLine("headPosition = " + headPosition);


                    float aspect         = (float)userViewTextureWidth / (float)userViewTextureHeight;
                    var   userProjection = GraphicsTransforms.PerspectiveFov(55.0f / 180.0f * (float)Math.PI, aspect, 0.001f, 1000.0f);
                    userProjection.Transpose();

                    // smooth depth images
                    foreach (var camera in ensemble.cameras)
                    {
                        var cameraDeviceResource = cameraDeviceResources[camera];
                        if (cameraDeviceResource.depthImageChanged)
                        {
                            fromUIntPS.Render(deviceContext, cameraDeviceResource.depthImageTextureRV, cameraDeviceResource.floatDepthImageRenderTargetView);
                            for (int i = 0; i < 1; i++)
                            {
                                bilateralFilter.Render(deviceContext, cameraDeviceResource.floatDepthImageRV, cameraDeviceResource.floatDepthImageRenderTargetView2);
                                bilateralFilter.Render(deviceContext, cameraDeviceResource.floatDepthImageRV2, cameraDeviceResource.floatDepthImageRenderTargetView);
                            }
                            cameraDeviceResource.depthImageChanged = false;
                        }
                    }

                    // wobble effect
                    if (wobbleEffectEnabled)
                    {
                        foreach (var camera in ensemble.cameras)
                        {
                            var cameraDeviceResource = cameraDeviceResources[camera];

                            var world = new SharpDX.Matrix();
                            for (int i = 0; i < 4; i++)
                            {
                                for (int j = 0; j < 4; j++)
                                {
                                    world[i, j] = (float)camera.pose[i, j];
                                }
                            }
                            world.Transpose();

                            // view and projection matrix are post-multiply
                            var userWorldViewProjection = world * userView * userProjection;

                            depthAndColorShader.SetConstants(deviceContext, camera.calibration, userWorldViewProjection);
                            depthAndColorShader.Render(deviceContext, cameraDeviceResource.floatDepthImageRV, cameraDeviceResource.colorImageTextureRV, cameraDeviceResource.vertexBuffer, userViewRenderTargetView, userViewDepthStencilView, userViewViewport);
                        }
                    }

                    // 3d object
                    if (threeDObjectEnabled)
                    {
                        var world = SharpDX.Matrix.Scaling(1.0f) * SharpDX.Matrix.RotationY(90.0f / 180.0f * (float)Math.PI) *
                                    SharpDX.Matrix.RotationX(-40.0f / 180.0f * (float)Math.PI) * SharpDX.Matrix.Translation(0, 0.7f, 0.0f);

                        var pointLight = new PointLight();
                        pointLight.position = new Vector3(0, 2, 0);
                        pointLight.Ia       = new Vector3(0.1f, 0.1f, 0.1f);
                        meshShader.SetVertexShaderConstants(deviceContext, world, userView * userProjection, pointLight.position);
                        meshShader.Render(deviceContext, meshDeviceResources, pointLight, userViewRenderTargetView, userViewDepthStencilView, userViewViewport);
                    }

                    // wobble effect
                    if (wobbleEffectEnabled)
                    {
                        alpha += 0.05f;
                        if (alpha > 1)
                        {
                            radialWobbleShader.SetConstants(deviceContext, 0);
                        }
                        else
                        {
                            radialWobbleShader.SetConstants(deviceContext, alpha);
                        }
                        radialWobbleShader.Render(deviceContext, userViewSRV, filteredUserViewRenderTargetView);
                    }

                    // desktop duplication
                    if (desktopDuplicationEnabled)
                    {
                        // update the desktop texture; this will block until there is some change
                        var outputDuplicateFrameInformation = default(OutputDuplicateFrameInformation);
                        SharpDX.DXGI.Resource resource      = null;
                        outputDuplication.AcquireNextFrame(1000, out outputDuplicateFrameInformation, out resource);
                        var texture = resource.QueryInterface <Texture2D>();

                        // pick up the window under the cursor
                        var cursorPos = new POINT();
                        GetCursorPos(out cursorPos);
                        var hwnd = WindowFromPoint(cursorPos);
                        var rect = new RECT();
                        GetWindowRect(hwnd, out rect);

                        // adjust bounds so falls within source texture
                        if (rect.Left < 0)
                        {
                            rect.Left = 0;
                        }
                        if (rect.Top < 0)
                        {
                            rect.Top = 0;
                        }
                        if (rect.Right > texture.Description.Width - 1)
                        {
                            rect.Right = texture.Description.Width;
                        }
                        if (rect.Bottom > texture.Description.Height - 1)
                        {
                            rect.Bottom = texture.Description.Height;
                        }

                        int width  = rect.Right - rect.Left;
                        int height = rect.Bottom - rect.Top;

                        // resize our texture if necessary
                        if ((desktopTexture == null) || (desktopTexture.Description.Width != width) || (desktopTexture.Description.Height != height))
                        {
                            if (desktopTexture != null)
                            {
                                desktopTextureSRV.Dispose();
                                desktopTexture.Dispose();
                            }
                            var desktopTextureDesc = new Texture2DDescription()
                            {
                                Width             = width,
                                Height            = height,
                                MipLevels         = 1, // revisit this; we may benefit from mipmapping?
                                ArraySize         = 1,
                                Format            = SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                                Usage             = ResourceUsage.Default,
                                BindFlags         = BindFlags.ShaderResource,
                                CpuAccessFlags    = CpuAccessFlags.None,
                            };
                            desktopTexture    = new Texture2D(device, desktopTextureDesc);
                            desktopTextureSRV = new ShaderResourceView(device, desktopTexture);
                        }

                        // copy the winodw region into our texture
                        var sourceRegion = new ResourceRegion()
                        {
                            Left   = rect.Left,
                            Right  = rect.Right,
                            Top    = rect.Top,
                            Bottom = rect.Bottom,
                            Front  = 0,
                            Back   = 1,
                        };
                        deviceContext.CopySubresourceRegion(texture, 0, sourceRegion, desktopTexture, 0);
                        texture.Dispose();
                    }

                    // render user view to seperate form
                    passThroughShader.viewport = new Viewport(0, 0, userViewForm.videoPanel1.Width, userViewForm.videoPanel1.Height);

                    // TODO: clean this up by simply using a pointer to the userViewSRV
                    if (threeDObjectEnabled)
                    {
                        passThroughShader.Render(deviceContext, userViewSRV, userViewForm.renderTargetView);
                    }
                    if (wobbleEffectEnabled)
                    {
                        passThroughShader.Render(deviceContext, filteredUserViewSRV, userViewForm.renderTargetView);
                    }
                    if (desktopDuplicationEnabled)
                    {
                        passThroughShader.Render(deviceContext, desktopTextureSRV, userViewForm.renderTargetView);
                    }
                    userViewForm.swapChain.Present(0, PresentFlags.None);

                    // projection puts x and y in [-1,1]; adjust to obtain texture coordinates [0,1]
                    // TODO: put this in SetContants?
                    userProjection[0, 0] /= 2;
                    userProjection[1, 1] /= -2; // y points down
                    userProjection[2, 0] += 0.5f;
                    userProjection[2, 1] += 0.5f;

                    // projection mapping for each projector
                    foreach (var form in projectorForms)
                    {
                        deviceContext.ClearRenderTargetView(form.renderTargetView, Color4.Black);
                        deviceContext.ClearDepthStencilView(form.depthStencilView, DepthStencilClearFlags.Depth, 1, 0);

                        foreach (var camera in ensemble.cameras)
                        {
                            var cameraDeviceResource = cameraDeviceResources[camera];

                            var world = new SharpDX.Matrix();
                            for (int i = 0; i < 4; i++)
                            {
                                for (int j = 0; j < 4; j++)
                                {
                                    world[i, j] = (float)camera.pose[i, j];
                                }
                            }
                            world.Transpose();

                            var projectorWorldViewProjection = world * form.view * form.projection;
                            var userWorldViewProjection      = world * userView * userProjection;

                            projectiveTexturingShader.SetConstants(deviceContext, userWorldViewProjection, projectorWorldViewProjection);

                            // TODO: clean this up by simply using a pointer to the userViewSRV
                            if (wobbleEffectEnabled)
                            {
                                projectiveTexturingShader.Render(deviceContext, cameraDeviceResource.floatDepthImageRV, filteredUserViewSRV, cameraDeviceResource.vertexBuffer, form.renderTargetView, form.depthStencilView, form.viewport);
                            }
                            if (threeDObjectEnabled)
                            {
                                projectiveTexturingShader.Render(deviceContext, cameraDeviceResource.floatDepthImageRV, userViewSRV, cameraDeviceResource.vertexBuffer, form.renderTargetView, form.depthStencilView, form.viewport);
                            }
                            if (desktopDuplicationEnabled)
                            {
                                projectiveTexturingShader.Render(deviceContext, cameraDeviceResource.floatDepthImageRV, desktopTextureSRV, cameraDeviceResource.vertexBuffer, form.renderTargetView, form.depthStencilView, form.viewport);
                            }
                        }

                        form.swapChain.Present(1, PresentFlags.None);
                    }


                    if (desktopDuplicationEnabled)
                    {
                        outputDuplication.ReleaseFrame();
                    }


                    //Console.WriteLine(stopwatch.ElapsedMilliseconds);
                    stopwatch.Restart();
                }
            }
        }
Esempio n. 22
0
        /// <summary>
        ///   Struct constructor
        /// </summary>
        /// <param name="adapter1">DXGI adapter device instance</param>
        /// <param name="output">DXGI output associated with this source</param>
        /// <param name="region">Region of the DXGI output device</param>
        internal DxgiCaptureSource(Adapter1 adapter1, Output output, Rectangle region)
        {
            Device   = null;
            Adapter1 = adapter1;
            Output   = output;
            Output1  = null;
            Output6  = null;
            Region   = region;

            if (region != output.Description.DesktopBounds)
            {
                Subregion = new ResourceRegion(region.Left - output.Description.DesktopBounds.Left,
                                               region.Top - output.Description.DesktopBounds.Top,
                                               0,
                                               region.Width + region.Left,
                                               region.Height + region.Top,
                                               1);
            }
            else
            {
                Subregion = null;
            }

            try {
                // create device
                Device = new Device(adapter1, DeviceCreationFlags.None, FeatureLevel.Level_11_0)
                {
#if DEBUG
                    DebugName = output.Description.DeviceName + " // " + adapter1.Description.Description
#endif
                };

                DxgiDevice = Device.QueryInterface <SharpDX.DXGI.Device>();

                // create texture
                Texture = new Texture2D(Device, new Texture2DDescription {
                    CpuAccessFlags    = CpuAccessFlags.Read,
                    BindFlags         = BindFlags.None,
                    Format            = Format.B8G8R8A8_UNorm,
                    Width             = region.Width,
                    Height            = region.Height,
                    OptionFlags       = ResourceOptionFlags.None,
                    MipLevels         = 1,
                    ArraySize         = 1,
                    SampleDescription = { Count = 1, Quality = 0 },
                    Usage             = ResourceUsage.Staging
                });

                // duplicate desktop
                try {
                    Format[] formats = { Format.B8G8R8A8_UNorm };
                    Output6     = output.QueryInterface <Output6>();
                    Duplication = Output6.DuplicateOutput1(Device, 0, formats.Length, formats);
                } catch (Exception exception)
                    when(exception is NotSupportedException ||
                         exception.HResult == ResultCode.Unsupported.Result ||
                         exception.HResult == Result.NoInterface.Result)
                    {
                        Output1     = output.QueryInterface <Output1>();
                        Duplication = Output1.DuplicateOutput(Device);
                    }
            } catch (Exception exception)
                when(exception is NotSupportedException ||
                     exception is NotImplementedException ||
                     exception.HResult == ResultCode.Unsupported.Result ||
                     exception.HResult == Result.NotImplemented.Result ||
                     exception.HResult == Result.NoInterface.Result)
                {
                    throw new NotSupportedException("Platform not supported", exception);
                }

            Alive = true;
        }
Esempio n. 23
0
        private static void Main()
        {
            // Device creation
            var form = new RenderForm("Stereo test")
                           {
                               ClientSize = size,
                               //FormBorderStyle = System.Windows.Forms.FormBorderStyle.None,
                               //WindowState = FormWindowState.Maximized
                           };

            form.KeyDown += new KeyEventHandler(form_KeyDown);
               // form.Resize += new EventHandler(form_Resize);

            ModeDescription mDesc = new ModeDescription(form.ClientSize.Width, form.ClientSize.Height,
                                                        new Rational(120000, 1000), Format.R8G8B8A8_UNorm);
            mDesc.ScanlineOrdering = DisplayModeScanlineOrdering.Progressive;
            mDesc.Scaling = DisplayModeScaling.Unspecified;

            var desc = new SwapChainDescription()
                           {
                               BufferCount = 1,
                               ModeDescription = mDesc,
                                   Flags = SwapChainFlags.AllowModeSwitch,
                               IsWindowed = false,
                               OutputHandle = form.Handle,
                               SampleDescription = new SampleDescription(1, 0),
                               SwapEffect = SwapEffect.Discard,
                               Usage = Usage.RenderTargetOutput
                           };

            Device.CreateWithSwapChain(null, DriverType.Hardware, DeviceCreationFlags.Debug, desc, out device,
                                       out swapChain);

            //Stops Alt+enter from causing fullscreen skrewiness.
            factory = swapChain.GetParent<Factory>();
            factory.SetWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll);

            backBuffer = Resource.FromSwapChain<Texture2D>(swapChain, 0);
            renderView = new RenderTargetView(device, backBuffer);

            ImageLoadInformation info = new ImageLoadInformation()
                                            {
                                                BindFlags = BindFlags.None,
                                                CpuAccessFlags = CpuAccessFlags.Read,
                                                FilterFlags = FilterFlags.None,
                                                Format = SlimDX.DXGI.Format.R8G8B8A8_UNorm,
                                                MipFilterFlags = FilterFlags.None,
                                                OptionFlags = ResourceOptionFlags.None,
                                                Usage = ResourceUsage.Staging,
                                                MipLevels = 1
                                            };

            // Make texture 3D
            sourceTexture = Texture2D.FromFile(device, "medusa.jpg", info);
            ImageLoadInformation info2 = new ImageLoadInformation()
                                            {
                                                BindFlags = BindFlags.ShaderResource,
                                                CpuAccessFlags = CpuAccessFlags.None,
                                                FilterFlags = FilterFlags.None,
                                                Format = SlimDX.DXGI.Format.R8G8B8A8_UNorm,
                                                MipFilterFlags = FilterFlags.None,
                                                OptionFlags = ResourceOptionFlags.None,
                                                Usage = ResourceUsage.Default,
                                                MipLevels = 1
                                            };
            Texture2D tShader = Texture2D.FromFile(device, "medusa.jpg", info2);
            srv = new ShaderResourceView(device, tShader);
            //ResizeDevice(new Size(1920, 1080), true);
            // Create a quad that fills the whole screen

            BuildQuad();
            // Create world view (ortho) projection matrices
            //QuaternionCam qCam = new QuaternionCam();

            // Load effect from file. It is a basic effect that renders a full screen quad through
            // an ortho projectio=n matrix
            effect = Effect.FromFile(device, "Texture.fx", "fx_4_0", ShaderFlags.Debug, EffectFlags.None);
            EffectTechnique technique = effect.GetTechniqueByIndex(0);
            EffectPass pass = technique.GetPassByIndex(0);
            InputLayout layout = new InputLayout(device, pass.Description.Signature, new[]
                                                                                         {
                                                                                             new InputElement(
                                                                                                 "POSITION", 0,
                                                                                                 Format.
                                                                                                     R32G32B32A32_Float,
                                                                                                 0, 0),
                                                                                             new InputElement(
                                                                                                 "TEXCOORD", 0,
                                                                                                 Format.
                                                                                                     R32G32_Float,
                                                                                                 16, 0)
                                                                                         });
            //effect.GetVariableByName("mWorld").AsMatrix().SetMatrix(
            //    Matrix.Translation(Layout.OrthographicTransform(Vector2.Zero, 99, size)));
            //effect.GetVariableByName("mView").AsMatrix().SetMatrix(qCam.View);
            //effect.GetVariableByName("mProjection").AsMatrix().SetMatrix(qCam.OrthoProjection);
            //effect.GetVariableByName("tDiffuse").AsResource().SetResource(srv);

            // Set RT and Viewports
            device.OutputMerger.SetTargets(renderView);
            device.Rasterizer.SetViewports(new Viewport(0, 0, size.Width, size.Height, 0.0f, 1.0f));

            // Create solid rasterizer state
            RasterizerStateDescription rDesc = new RasterizerStateDescription()
                                                   {
                                                       CullMode = CullMode.None,
                                                       IsDepthClipEnabled = true,
                                                       FillMode = FillMode.Solid,
                                                       IsAntialiasedLineEnabled = false,
                                                       IsFrontCounterclockwise = true,
                                                       //IsMultisampleEnabled = true,
                                                   };
            RasterizerState rState = RasterizerState.FromDescription(device, rDesc);
            device.Rasterizer.State = rState;

            Texture2DDescription rtDesc = new Texture2DDescription
                                              {
                                                  ArraySize = 1,
                                                  Width = size.Width,
                                                  Height = size.Height,
                                                  BindFlags = BindFlags.RenderTarget,
                                                  CpuAccessFlags = CpuAccessFlags.None,
                                                  Format = SlimDX.DXGI.Format.R8G8B8A8_UNorm,
                                                  OptionFlags = ResourceOptionFlags.None,
                                                  Usage = ResourceUsage.Default,
                                                  MipLevels = 1,
                                                  SampleDescription = new SampleDescription(1, 0)
                                              };
            rtTex = new Texture2D(device, rtDesc);

            rv = new RenderTargetView(device, rtTex);

            stereoizedTexture = Make3D(sourceTexture);
            //ResizeDevice(new Size(1920, 1080), true);
            Console.WriteLine(form.ClientSize);
            // Main Loop
            MessagePump.Run(form, () =>
            {
            device.ClearRenderTargetView(renderView, Color.Cyan);

            //device.InputAssembler.SetInputLayout(layout);
            //device.InputAssembler.SetPrimitiveTopology(PrimitiveTopology.TriangleList);
            //device.OutputMerger.SetTargets(rv);
            //device.InputAssembler.SetVertexBuffers(0,
            //                                new VertexBufferBinding(vertices, 24, 0));
            //device.InputAssembler.SetIndexBuffer(indices, Format.R16_UInt, 0);
            //for (int i = 0; i < technique.Description.PassCount; ++i)
            //{
            //    // Render the full screen quad
            //    pass.Apply();
            //    device.DrawIndexed(6, 0, 0);
            //}
            ResourceRegion stereoSrcBox = new ResourceRegion { Front = 0, Back = 1, Top = 0, Bottom = size.Height, Left = 0, Right = size.Width };
            device.CopySubresourceRegion(stereoizedTexture, 0, stereoSrcBox, backBuffer, 0, 0, 0, 0);
            //device.CopyResource(rv.Resource, backBuffer);

            swapChain.Present(0, PresentFlags.None);
            });

            // Dispose resources
            vertices.Dispose();
            layout.Dispose();
            effect.Dispose();
            renderView.Dispose();
            backBuffer.Dispose();
            device.Dispose();
            swapChain.Dispose();

            rState.Dispose();
            stereoizedTexture.Dispose();
            sourceTexture.Dispose();
            indices.Dispose();
            srv.Dispose();
        }
Esempio n. 24
0
 public void UpdateSubresourceSafe(ref DataBox source, Resource resource, int srcBytesPerElement, int subresource, ResourceRegion region, bool isCompressedResource = false)
 {
     deviceContext.UpdateSubresourceSafe(source, resource, srcBytesPerElement, subresource, region, isCompressedResource);
 }
Esempio n. 25
0
        public void Evaluate(int SpreadMax)
        {
            if (this.FInput.IsConnected && this.FInEnabled[0])
            {
                if (this.RenderRequest != null)
                {
                    this.RenderRequest(this, this.FHost);
                }

                IDX11ReadableStructureBuffer b = this.FInput[0][this.AssignedContext];

                if (b != null)
                {
                    int elementcount = this.FInElementCount[0];
                    if (elementcount == 0)
                    {
                        elementcount = b.ElementCount;
                    }

                    DX11StagingStructuredBuffer staging = new DX11StagingStructuredBuffer(this.AssignedContext.Device
                                                                                          , elementcount, b.Stride);



                    ResourceRegion region = new ResourceRegion(0, 0, 0, this.FInElementCount[0] * b.Stride, 1, 1);
                    /*this.AssignedContext.CurrentDeviceContext.CopySubresourceRegion(b.Buffer, 0, staging.Buffer, 0, */
                    this.AssignedContext.CurrentDeviceContext.CopySubresourceRegion(b.Buffer, 0, region, staging.Buffer, 0, 0, 0, 0);

                    /*this.AssignedContext.CurrentDeviceContext.CopyResource(b.Buffer, staging.Buffer);*/

                    foreach (IIOContainer sp in this.outspreads)
                    {
                        ISpread s = (ISpread)sp.RawIOObject;
                        s.SliceCount = elementcount;
                    }

                    DataStream ds = staging.MapForRead(this.AssignedContext.CurrentDeviceContext);

                    for (int i = 0; i < elementcount; i++)
                    {
                        int cnt = 0;
                        foreach (string lay in layout)
                        {
                            switch (lay)
                            {
                            case "float":
                                ISpread <float> spr = (ISpread <float>) this.outspreads[cnt].RawIOObject;
                                spr[i] = ds.Read <float>();
                                break;

                            case "float2":
                                ISpread <Vector2> spr2 = (ISpread <Vector2>) this.outspreads[cnt].RawIOObject;
                                spr2[i] = ds.Read <Vector2>();
                                break;

                            case "float3":
                                ISpread <Vector3> spr3 = (ISpread <Vector3>) this.outspreads[cnt].RawIOObject;
                                spr3[i] = ds.Read <Vector3>();
                                break;

                            case "float4":
                                ISpread <Vector4> spr4 = (ISpread <Vector4>) this.outspreads[cnt].RawIOObject;
                                spr4[i] = ds.Read <Vector4>();
                                break;

                            case "float4x4":
                                ISpread <Matrix> sprm = (ISpread <Matrix>) this.outspreads[cnt].RawIOObject;
                                sprm[i] = ds.Read <Matrix>();
                                break;

                            case "int":
                                ISpread <int> spri = (ISpread <int>) this.outspreads[cnt].RawIOObject;
                                spri[i] = ds.Read <int>();
                                break;

                            case "uint":
                                ISpread <uint> sprui = (ISpread <uint>) this.outspreads[cnt].RawIOObject;
                                sprui[i] = ds.Read <uint>();
                                break;

                            case "uint2":
                                ISpread <Vector2> sprui2 = (ISpread <Vector2>) this.outspreads[cnt].RawIOObject;
                                uint ui1 = ds.Read <uint>();
                                uint ui2 = ds.Read <uint>();
                                sprui2[i] = new Vector2(ui1, ui2);
                                break;

                            case "uint3":
                                ISpread <Vector3> sprui3 = (ISpread <Vector3>) this.outspreads[cnt].RawIOObject;
                                uint ui31 = ds.Read <uint>();
                                uint ui32 = ds.Read <uint>();
                                uint ui33 = ds.Read <uint>();
                                sprui3[i] = new Vector3(ui31, ui32, ui33);
                                break;
                            }
                            cnt++;
                        }
                    }

                    staging.UnMap(this.AssignedContext.CurrentDeviceContext);

                    staging.Dispose();
                }
                else
                {
                    foreach (IIOContainer sp in this.outspreads)
                    {
                        ISpread s = (ISpread)sp.RawIOObject;
                        s.SliceCount = 0;
                    }
                }
            }
            else
            {
                foreach (IIOContainer sp in this.outspreads)
                {
                    ISpread s = (ISpread)sp.RawIOObject;
                    s.SliceCount = 0;
                }
            }
        }
Esempio n. 26
0
 public void UpdateSubresource(DataBox source, Resource resource, int subresource, ref ResourceRegion region)
 {
     deviceContext.UpdateSubresource(source, resource, subresource, region);
 }
Esempio n. 27
0
        public void CopyRegion(GraphicsResource source, int sourceSubresource, ResourceRegion? sourecRegion, GraphicsResource destination, int destinationSubResource, int dstX = 0, int dstY = 0, int dstZ = 0)
        {
            if (source == null) throw new ArgumentNullException("source");
            if (destination == null) throw new ArgumentNullException("destination");

            var nullableSharpDxRegion = new SharpDX.Direct3D11.ResourceRegion?();

            if (sourecRegion.HasValue)
            {
                var value = sourecRegion.Value;
                nullableSharpDxRegion = new SharpDX.Direct3D11.ResourceRegion(value.Left, value.Top, value.Front, value.Right, value.Bottom, value.Back);
            }

            NativeDeviceContext.CopySubresourceRegion(source.NativeResource, sourceSubresource, nullableSharpDxRegion, destination.NativeResource, destinationSubResource, dstX, dstY, dstZ);
        }
Esempio n. 28
0
        /// <summary>
        /// Upload a character's bitmap into the current cache.
        /// </summary>
        /// <param name="character">The character specifications corresponding to the bitmap</param>
        public void UploadCharacterBitmap(CharacterSpecification character)
        {
            if(character.Bitmap == null)
                throw new ArgumentNullException("character");

            if(character.IsBitmapUploaded)
                throw new InvalidOperationException("The character '"+character.Character+"' upload has been requested while its current glyph is valid.");

            var targetSize = new Int2(character.Bitmap.Width, character.Bitmap.Rows);
            if (!packer.Insert(targetSize.X, targetSize.Y, ref character.Glyph.Subrect))
            {
                // not enough space to place the new character -> remove less used characters and try again
                RemoveLessUsedCharacters();
                if (!packer.Insert(targetSize.X, targetSize.Y, ref character.Glyph.Subrect))
                {
                    // memory is too fragmented in order to place the new character -> clear all the characters and restart.
                    ClearCache();
                    if (!packer.Insert(targetSize.X, targetSize.Y, ref character.Glyph.Subrect))
                        throw new InvalidOperationException("The rendered character is too big for the cache texture");
                }
            }
            // updload the bitmap on the texture (if the size in the bitmap is not null)
            if (character.Bitmap.Rows != 0 && character.Bitmap.Width != 0)
            {
                var dataBox = new DataBox(character.Bitmap.Buffer, character.Bitmap.Pitch, character.Bitmap.Pitch * character.Bitmap.Rows);
                var region = new ResourceRegion(character.Glyph.Subrect.Left, character.Glyph.Subrect.Top, 0, character.Glyph.Subrect.Right, character.Glyph.Subrect.Bottom, 1);
                system.GraphicsDevice.UpdateSubresource(cacheTextures[0], 0, dataBox, region);
            }

            // update the glyph data
            character.IsBitmapUploaded = true;
            character.Glyph.BitmapIndex = 0;
        }
        public void Update(IPluginIO pin, DX11RenderContext context)
        {
            Device device = context.Device;
            DeviceContext ctx = context.CurrentDeviceContext;

            for (int i = 0; i < this.FOutGeom.SliceCount; i++)
            {
                DX11IndexedGeometry geom;
                if (this.invalidate || (!this.FOutGeom[i].Contains(context)))
                {
                    geom = (DX11IndexedGeometry)this.FInGeom[i][context].ShallowCopy();

                    DX11IndexedIndirectDrawer ind = new DX11IndexedIndirectDrawer();
                    geom.AssignDrawer(ind);

                    ind.Update(context, this.FInCnt[i]);

                    this.invalidate = false;
                }
                else
                {
                    geom = this.FOutGeom[i][context];
                }

                DX11IndexedIndirectDrawer drawer = (DX11IndexedIndirectDrawer)geom.Drawer;

                var argBuffer = drawer.IndirectArgs.Buffer;
                if (this.FInIdx.PluginIO.IsConnected)
                {
                    int idxOffset = this.FInIdxOffset[i];

                    ResourceRegion region = new ResourceRegion(idxOffset, 0, 0, idxOffset+ 4, 1, 1);
                    context.CurrentDeviceContext.CopySubresourceRegion(this.FInIdx[i][context].Buffer, 0, region, argBuffer, 0, 0, 0, 0);
                }

                if (this.FInInst.PluginIO.IsConnected)
                {
                    int instOffset = this.FInInstOffset[i];
                    ResourceRegion region = new ResourceRegion(instOffset, 0, 0,instOffset + 4, 1, 1);
                    context.CurrentDeviceContext.CopySubresourceRegion(this.FInInst[i][context].Buffer, 0, region, argBuffer, 0, 4, 0, 0);
                }

                this.FOutGeom[i][context] = geom;
            }
        }
Esempio n. 30
0
        public void Update(IPluginIO pin, DX11RenderContext context)
        {
            for (int i = 0; i < this.FOutGeom.SliceCount; i++)
            {
                if (this.FInEnabled[i])
                {
                    if (this.FInVCnt.IsChanged || this.FInICnt.IsChanged || this.FOutGeom[i].Contains(context) == false)
                    {
                        if (this.FOutGeom[i].Contains(context))
                        {
                            this.FOutGeom[i].Dispose(context);

                        }

                        this.FOutGeom[i][context] = new DX11NullGeometry(context);
                        DX11NullIndirectDrawer ind = new DX11NullIndirectDrawer();
                        ind.Update(context, this.FInVCnt[i], this.FInICnt[i]);
                        this.FOutGeom[i][context].AssignDrawer(ind);
                    }

                    DX11NullIndirectDrawer drawer = (DX11NullIndirectDrawer)this.FOutGeom[i][context].Drawer;

                    var argBuffer = drawer.IndirectArgs.Buffer;

                    if (this.FInI.PluginIO.IsConnected)
                    {
                        int instOffset = this.FInInstOffset[i];
                        ResourceRegion region = new ResourceRegion(instOffset, 0, 0, instOffset + 4, 1, 1);
                        context.CurrentDeviceContext.CopySubresourceRegion(this.FInI[i][context].Buffer, 0, region, argBuffer, 0, 4, 0, 0);
                    }

                    if (this.FInV.PluginIO.IsConnected)
                    {
                        int vOffset = this.FInVtxOffset[i];
                        ResourceRegion region = new ResourceRegion(vOffset, 0, 0, vOffset + 4, 1, 1);
                        context.CurrentDeviceContext.CopySubresourceRegion(this.FInV[i][context].Buffer, 0, region, argBuffer, 0, 0, 0, 0);
                    }
                }
            }
        }
Esempio n. 31
0
    protected internal bool GetCursor(Texture2D screenTexture, OutputDuplicateFrameInformation info, FrameInfo frame)
    {
        //Prepare buffer array to hold the cursor shape.
        if (CursorShapeBuffer == null || info.PointerShapeBufferSize > CursorShapeBuffer.Length)
        {
            CursorShapeBuffer = new byte[info.PointerShapeBufferSize];
        }

        //If there's a cursor shape available to be captured.
        if (info.PointerShapeBufferSize > 0)
        {
            //Pin the buffer in order to pass the address as parameter later.
            var pinnedBuffer        = GCHandle.Alloc(CursorShapeBuffer, GCHandleType.Pinned);
            var cursorBufferAddress = pinnedBuffer.AddrOfPinnedObject();

            //Load the cursor shape into the buffer.
            DuplicatedOutput.GetFramePointerShape(info.PointerShapeBufferSize, cursorBufferAddress, out _, out CursorShapeInfo);

            //If the cursor is monochrome, it will return the cursor shape twice, one is the mask.
            if (CursorShapeInfo.Type == 1)
            {
                CursorShapeInfo.Height /= 2;
            }

            //The buffer must be unpinned, to free resources.
            pinnedBuffer.Free();
        }

        //Store the current cursor position, if it was moved.
        if (info.LastMouseUpdateTime != 0)
        {
            PreviousPosition = info.PointerPosition;
        }

        //TODO: In a future version, don't merge the cursor image in here, let the editor do that.
        //Saves the position of the cursor, so the editor can add the mouse clicks overlay later.
        frame.CursorX = PreviousPosition.Position.X - (Left - OffsetLeft);
        frame.CursorY = PreviousPosition.Position.Y - (Top - OffsetTop);

        //If the method is supposed to simply the get the cursor shape no shape was loaded before, there's nothing else to do.
        //if (CursorShapeBuffer?.Length == 0 || (info.LastPresentTime == 0 && info.LastMouseUpdateTime == 0) || !info.PointerPosition.Visible)
        if (screenTexture == null || CursorShapeBuffer?.Length == 0)// || !info.PointerPosition.Visible)
        {
            //FallbackCursorCapture(frame);

            //if (CursorShapeBuffer != null)
            return(false);
        }

        //Don't let it bleed beyond the top-left corner, calculate the dimensions of the portion of the cursor that will appear.
        var leftCut   = frame.CursorX;
        var topCut    = frame.CursorY;
        var rightCut  = screenTexture.Description.Width - (frame.CursorX + CursorShapeInfo.Width);
        var bottomCut = screenTexture.Description.Height - (frame.CursorY + CursorShapeInfo.Height);

        //Adjust to the hotspot offset, so it's possible to add the highlight correctly later.
        frame.CursorX += CursorShapeInfo.HotSpot.X;
        frame.CursorY += CursorShapeInfo.HotSpot.Y;

        //Don't try merging the textures if the cursor is out of bounds.
        if (leftCut + CursorShapeInfo.Width < 1 || topCut + CursorShapeInfo.Height < 1 || rightCut + CursorShapeInfo.Width < 1 || bottomCut + CursorShapeInfo.Height < 1)
        {
            return(false);
        }

        var cursorLeft   = Math.Max(leftCut, 0);
        var cursorTop    = Math.Max(topCut, 0);
        var cursorWidth  = leftCut < 0 ? CursorShapeInfo.Width + leftCut : rightCut < 0 ? CursorShapeInfo.Width + rightCut : CursorShapeInfo.Width;
        var cursorHeight = topCut < 0 ? CursorShapeInfo.Height + topCut : bottomCut < 0 ? CursorShapeInfo.Height + bottomCut : CursorShapeInfo.Height;

        //The staging texture must be able to hold all pixels.
        if (CursorStagingTexture == null || CursorStagingTexture.Description.Width != cursorWidth || CursorStagingTexture.Description.Height != cursorHeight)
        {
            //In order to change the size of the texture, I need to instantiate it again with the new size.
            CursorStagingTexture?.Dispose();
            CursorStagingTexture = new Texture2D(Device, new Texture2DDescription
            {
                ArraySize         = 1,
                BindFlags         = BindFlags.None,
                CpuAccessFlags    = CpuAccessFlags.Write,
                Height            = cursorHeight,
                Format            = Format.B8G8R8A8_UNorm,
                Width             = cursorWidth,
                MipLevels         = 1,
                OptionFlags       = ResourceOptionFlags.None,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = ResourceUsage.Staging
            });
        }

        //The region where the cursor is located is copied to the staging texture to act as the background when dealing with masks and transparency.
        //The cutout must be the exact region needed and it can't overflow. It's not allowed to try to cut outside of the screenTexture region.
        var region = new ResourceRegion
        {
            Left   = cursorLeft,
            Top    = cursorTop,
            Front  = 0,
            Right  = cursorLeft + cursorWidth,
            Bottom = cursorTop + cursorHeight,
            Back   = 1
        };

        //Copy from the screen the region in which the cursor is located.
        Device.ImmediateContext.CopySubresourceRegion(screenTexture, 0, region, CursorStagingTexture, 0);

        //Get cursor details and draw it to the staging texture.
        DrawCursorShape(CursorStagingTexture, CursorShapeInfo, CursorShapeBuffer, leftCut < 0 ? leftCut * -1 : 0, topCut < 0 ? topCut * -1 : 0, cursorWidth, cursorHeight);

        //Copy back the cursor texture to the screen texture.
        Device.ImmediateContext.CopySubresourceRegion(CursorStagingTexture, 0, null, screenTexture, 0, cursorLeft, cursorTop);

        return(true);
    }
Esempio n. 32
0
 public void Present()
 {
     const int subResourceNumber = 0;
     ResourceRegion resourceRegion = new ResourceRegion
     {
         Back = 1,
         Bottom = StagingTexture.Description.Height,
         Front = 0,
         Left = 0,
         Right = StagingTexture.Description.Width,
         Top = 0
     };
     device.ImmediateContext.CopySubresourceRegion(SharedTexture, subResourceNumber, resourceRegion, StagingTexture, subResourceNumber, 0, 0, 0);
     device.ImmediateContext.MapSubresource(StagingTexture, 0, MapMode.Read, SlimDX.Direct3D11.MapFlags.None);
     device.ImmediateContext.UnmapSubresource(StagingTexture, 0);
     //device.ImmediateContext.Flush();
 }
Esempio n. 33
0
        public void Evaluate(int SpreadMax)
        {
            if (this.FInput.IsConnected && this.FInEnabled[0])
            {
                if (this.RenderRequest != null) { this.RenderRequest(this, this.FHost); }

                IDX11ReadableStructureBuffer b= this.FInput[0][this.AssignedContext];

                if (b != null)
                {

                    int elementcount = this.FInElementCount[0];
                    if (elementcount == 0) { elementcount = b.ElementCount; }

                    DX11StagingStructuredBuffer staging = new DX11StagingStructuredBuffer(this.AssignedContext.Device
                        , elementcount, b.Stride);

                    ResourceRegion region = new ResourceRegion(0,0,0,this.FInElementCount[0]*b.Stride,1,1);
                    /*this.AssignedContext.CurrentDeviceContext.CopySubresourceRegion(b.Buffer, 0, staging.Buffer, 0, */
                    this.AssignedContext.CurrentDeviceContext.CopySubresourceRegion(b.Buffer, 0, region,staging.Buffer, 0, 0, 0, 0);

                    /*this.AssignedContext.CurrentDeviceContext.CopyResource(b.Buffer, staging.Buffer);*/

                    foreach (IIOContainer sp in this.outspreads)
                    {
                        ISpread s = (ISpread)sp.RawIOObject;
                        s.SliceCount = elementcount;
                    }

                    DataStream ds = staging.MapForRead(this.AssignedContext.CurrentDeviceContext);

                    for (int i = 0; i < elementcount; i++)
                    {
                        int cnt = 0;
                        foreach (string lay in layout)
                        {
                            switch (lay)
                            {
                                case "float":
                                    ISpread<float> spr = (ISpread<float>)this.outspreads[cnt].RawIOObject;
                                    spr[i] = ds.Read<float>();
                                    break;
                                case "float2":
                                    ISpread<Vector2> spr2 = (ISpread<Vector2>)this.outspreads[cnt].RawIOObject;
                                    spr2[i] = ds.Read<Vector2>();
                                    break;
                                case "float3":
                                    ISpread<Vector3> spr3 = (ISpread<Vector3>)this.outspreads[cnt].RawIOObject;
                                    spr3[i] = ds.Read<Vector3>();
                                    break;
                                case "float4":
                                    ISpread<Vector4> spr4 = (ISpread<Vector4>)this.outspreads[cnt].RawIOObject;
                                    spr4[i] = ds.Read<Vector4>();
                                    break;
                                case "float4x4":
                                    ISpread<Matrix> sprm = (ISpread<Matrix>)this.outspreads[cnt].RawIOObject;
                                    sprm[i] = ds.Read<Matrix>();
                                    break;
                                case "int":
                                    ISpread<int> spri = (ISpread<int>)this.outspreads[cnt].RawIOObject;
                                    spri[i] = ds.Read<int>();
                                    break;
                                case "uint":
                                    ISpread<uint> sprui = (ISpread<uint>)this.outspreads[cnt].RawIOObject;
                                    sprui[i] = ds.Read<uint>();
                                    break;
                                case "uint2":
                                    ISpread<Vector2> sprui2 = (ISpread<Vector2>)this.outspreads[cnt].RawIOObject;
                                    uint ui1 = ds.Read<uint>();
                                    uint ui2 = ds.Read<uint>();
                                    sprui2[i] = new Vector2(ui1, ui2);
                                    break;
                                case "uint3":
                                    ISpread<Vector3> sprui3 = (ISpread<Vector3>)this.outspreads[cnt].RawIOObject;
                                    uint ui31 = ds.Read<uint>();
                                    uint ui32 = ds.Read<uint>();
                                    uint ui33 = ds.Read<uint>();
                                    sprui3[i] = new Vector3(ui31, ui32, ui33);
                                    break;
                            }
                            cnt++;
                        }

                    }

                    staging.UnMap(this.AssignedContext.CurrentDeviceContext);

                    staging.Dispose();
                }
                else
                {
                    foreach (IIOContainer sp in this.outspreads)
                    {
                        ISpread s = (ISpread)sp.RawIOObject;
                        s.SliceCount = 0;
                    }
                }
            }
            else
            {
                foreach (IIOContainer sp in this.outspreads)
                {
                    ISpread s = (ISpread)sp.RawIOObject;
                    s.SliceCount = 0;
                }
            }
        }
Esempio n. 34
0
        public void Test1D()
        {
            var textureData = new byte[256];

            for (int i = 0; i < textureData.Length; i++)
            {
                textureData[i] = (byte)i;
            }

            // -------------------------------------------------------
            // General test for a Texture1D
            // -------------------------------------------------------

            // Create Texture1D
            var texture = Texture1D.New(GraphicsDevice, textureData.Length, PixelFormat.R8.UNorm);

            // Check description against native description
            var d3d11Texture = (Direct3D11.Texture1D)texture;
            var d3d11SRV     = (Direct3D11.ShaderResourceView)texture;

            Assert.AreEqual(d3d11Texture.Description, new Direct3D11.Texture1DDescription()
            {
                Width          = textureData.Length,
                ArraySize      = 1,
                BindFlags      = BindFlags.ShaderResource,
                CpuAccessFlags = CpuAccessFlags.None,
                Format         = DXGI.Format.R8_UNorm,
                MipLevels      = 1,
                OptionFlags    = ResourceOptionFlags.None,
                Usage          = ResourceUsage.Default
            });

            // Check shader resource view.
            var srvDescription = d3d11SRV.Description;

            // Clear those fields that are garbage returned from ShaderResourceView.Description.
            srvDescription.Texture2DArray.ArraySize       = 0;
            srvDescription.Texture2DArray.FirstArraySlice = 0;

            Assert.AreEqual(srvDescription, new Direct3D11.ShaderResourceViewDescription()
            {
                Dimension = ShaderResourceViewDimension.Texture1D,
                Format    = DXGI.Format.R8_UNorm,
                Texture1D = { MipLevels = 1, MostDetailedMip = 0 },
            });

            // Check mipmap description
            var mipmapDescription    = texture.GetMipMapDescription(0);
            var rowStride            = textureData.Length * sizeof(byte);
            var refMipmapDescription = new MipMapDescription(textureData.Length, 1, 1, rowStride, rowStride, textureData.Length, 1);

            Assert.AreEqual(mipmapDescription, refMipmapDescription);

            // Check that getting the default SRV is the same as getting the first mip/array
            Assert.AreEqual(texture.ShaderResourceView[ViewType.Full, 0, 0].View, d3d11SRV);

            // Check GraphicsDevice.GetData/SetData data
            // Upload the textureData to the GPU
            texture.SetData(GraphicsDevice, textureData);

            // Read back data from the GPU
            var readBackData = texture.GetData <byte>();

            // Check that both content are equal
            Assert.True(Utilities.Compare(textureData, readBackData));

            // -------------------------------------------------------
            // Check with Texture1D.Clone and GraphicsDevice.Copy
            // -------------------------------------------------------
            using (var texture2 = texture.Clone <Texture1D>())
            {
                GraphicsDevice.Copy(texture, texture2);

                readBackData = texture2.GetData <byte>();

                // Check that both content are equal
                Assert.True(Utilities.Compare(textureData, readBackData));
            }

            // -------------------------------------------------------
            // Test SetData using a ResourceRegion
            // -------------------------------------------------------
            // Set the last 4 pixels in different orders
            var smallTextureDataRegion = new byte[] { 4, 3, 2, 1 };

            var region = new ResourceRegion(textureData.Length - 4, 0, 0, textureData.Length, 1, 1);

            texture.SetData(GraphicsDevice, smallTextureDataRegion, 0, 0, region);

            readBackData = texture.GetData <byte>();

            Array.Copy(smallTextureDataRegion, 0, textureData, textureData.Length - 4, 4);

            // Check that both content are equal
            Assert.True(Utilities.Compare(textureData, readBackData));

            // -------------------------------------------------------
            // Texture.Dispose()
            // -------------------------------------------------------
            // TODO check that Dispose is implemented correctly
            texture.Dispose();
        }
Esempio n. 35
0
        private static Texture2D Make3D(Texture2D stereoTexture)
        {
            NvStereoImageHeader header = new NvStereoImageHeader(0x4433564e, 3840, 1080, 4, 0x00000002);

            // stereoTexture contains a stereo image with the left eye image on the left half
            // and the right eye image on the right half
            // this staging texture will have an extra row to contain the stereo signature
            Texture2DDescription stagingDesc = new Texture2DDescription()
                                                   {
                                                       ArraySize = 1,
                                                       Width = 2*size.Width,
                                                       Height = size.Height + 1,
                                                       BindFlags = BindFlags.None,
                                                       CpuAccessFlags = CpuAccessFlags.Write,
                                                       Format = SlimDX.DXGI.Format.R8G8B8A8_UNorm,
                                                       OptionFlags = ResourceOptionFlags.None,
                                                       Usage = ResourceUsage.Staging,
                                                       MipLevels = 1,
                                                       SampleDescription = new SampleDescription(1, 0)
                                                   };
            Texture2D staging = new Texture2D(device, stagingDesc);

            // Identify the source texture region to copy (all of it)
            ResourceRegion stereoSrcBox = new ResourceRegion
                                              {Front = 0, Back = 1, Top = 0, Bottom = size.Height, Left = 0, Right = 2*size.Width};
            // Copy it to the staging texture
            device.CopySubresourceRegion(stereoTexture, 0, stereoSrcBox, staging, 0, 0, 0, 0);

            // Open the staging texture for reading
            DataRectangle box = staging.Map(0, MapMode.Write, SlimDX.Direct3D10.MapFlags.None);
            // Go to the last row
            //box.Data.Seek(stereoTexture.Description.Width*stereoTexture.Description.Height*4, System.IO.SeekOrigin.Begin);
            box.Data.Seek(box.Pitch*1080, System.IO.SeekOrigin.Begin);
            // Write the NVSTEREO header
            box.Data.Write(data, 0, data.Length);
            staging.Unmap(0);

            // Create the final stereoized texture
            Texture2DDescription finalDesc = new Texture2DDescription()
                                                 {
                                                     ArraySize = 1,
                                                     Width = 2 * size.Width,
                                                     Height = size.Height + 1,
                                                     BindFlags = BindFlags.ShaderResource,
                                                     CpuAccessFlags = CpuAccessFlags.Write,
                                                     Format = SlimDX.DXGI.Format.R8G8B8A8_UNorm,
                                                     OptionFlags = ResourceOptionFlags.None,
                                                     Usage = ResourceUsage.Dynamic,
                                                     MipLevels = 1,
                                                     SampleDescription = new SampleDescription(1, 0)
                                                 };

            // Copy the staging texture on a new texture to be used as a shader resource
            Texture2D final = new Texture2D(device, finalDesc);
            device.CopyResource(staging, final);
            staging.Dispose();
            return final;
        }
        public void Update(IPluginIO pin, DX11RenderContext context)
        {
            for (int i = 0; i < this.FOutGeom.SliceCount; i++)
            {
                DX11VertexGeometry geom = (DX11VertexGeometry)this.FInGeom[i][context].ShallowCopy();

                if (this.FInEnabled[i])
                {

                    if (this.FInGeom.IsChanged || this.FInCnt.IsChanged)
                    {
                        DX11VertexIndirectDrawer ind = new DX11VertexIndirectDrawer();
                        geom.AssignDrawer(ind);

                        ind.Update(context, this.FInCnt[i]);
                    }

                    DX11VertexIndirectDrawer drawer = (DX11VertexIndirectDrawer)geom.Drawer;
                    var argBuffer = drawer.IndirectArgs.Buffer;

                    if (this.FInI.PluginIO.IsConnected)
                    {
                        int instOffset = this.FInInstOffset[i];
                        ResourceRegion region = new ResourceRegion(instOffset, 0, 0, instOffset + 4, 1, 1);
                        context.CurrentDeviceContext.CopySubresourceRegion(this.FInI[i][context].Buffer, 0, region, argBuffer, 0, 4, 0, 0);
                    }

                    if (this.FInV.PluginIO.IsConnected)
                    {
                        int vOffset = this.FInVtxOffset[i];
                        ResourceRegion region = new ResourceRegion(vOffset, 0, 0, vOffset + 4, 1, 1);
                        context.CurrentDeviceContext.CopySubresourceRegion(this.FInV[i][context].Buffer, 0, region, argBuffer, 0, 0, 0, 0);
                    }

                    this.FOutGeom[i][context] = geom;
                }
            }
        }
Esempio n. 37
0
        Texture2D Make3D(Texture2D tex)
        {
            NvStereoImageHeader header = new NvStereoImageHeader(0x4433564e, 3840, 1080, 4, 0x00000002);
               // DataBox box = DeviceContext.Immediate.MapSubresource(tex, 0,
               //     tex.Description.Width * tex.Description.Height * 4, MapMode.Read, MapFlags.None);
               // Console.WriteLine(box.RowPitch);
               // int size = tex.Description.Width * tex.Description.Height * 8;
               // byte[] buffer = new byte[size/2];
               // int val = box.Data.ReadRange<byte>(buffer, 0, size/2);
               // DeviceContext.Immediate.UnmapSubresource(tex, 0);
            Texture2DDescription desc = new Texture2DDescription()
                                             {
                                                 ArraySize = 1,
                                                 Width = 3840,
                                                 Height = 1081,
                                                 BindFlags = BindFlags.None,
                                                 CpuAccessFlags = CpuAccessFlags.Write,
                                                 Format = SlimDX.DXGI.Format.R8G8B8A8_UNorm,
                                                 OptionFlags = ResourceOptionFlags.None,
                                                 Usage = ResourceUsage.Staging,
                                                 MipLevels = 1,
                                                 SampleDescription = new SampleDescription(1, 0)
                                             };

            ResourceRegion stereoSrcBox = new ResourceRegion
                                              {Front = 0, Back = 1, Top = 0, Bottom = 1080, Left = 0, Right = 3840};

            Texture2D outp = new Texture2D(Game.Context.Device, desc);

            DeviceContext.Immediate.CopySubresourceRegion(tex, 0, stereoSrcBox, outp, 0, 0, 0, 0);
            //DeviceContext.Immediate.CopyResource(tex, outp);
            DataBox box = DeviceContext.Immediate.MapSubresource(outp, 0,
                outp.Description.Width * outp.Description.Height * 4, MapMode.Write, MapFlags.None);
            //var val = box.Data.ReadByte();
            box.Data.Seek(tex.Description.Width * tex.Description.Height * 4, SeekOrigin.Begin);

            //box.Data.Write(data, 0, data.Length);
            //byte[] color = BitConverter.GetBytes(Color.White.ToArgb());
            //box.Data.Write(color,0, color.Length);
            //box.Data.Write(data, 0, data.Length);
            byte[] headerData = StructureToByteArray(header);
            box.Data.Write(headerData, 0, headerData.Length);
            //box.Data.Write(color, 0, color.Length);
            DeviceContext.Immediate.UnmapSubresource(outp, 0);
              //box.Data.Write(buffer, 0, buffer.Length);

            //DeviceContext.Immediate.CopySubresourceRegion(tex, 0, stereoSrcBox, outp, 0, 0, 0, 0);
            ////return Texture2D.FromMemory(Game.Context.Device, buffer);
            //Texture2D.ToFile(Game.Context.Immediate, outp, ImageFileFormat.Bmp, "prova.bmp");

            Texture2DDescription finalDesc = new Texture2DDescription()
            {
                ArraySize = 1,
                Width = 3840,
                Height = 1081,
                BindFlags = BindFlags.ShaderResource,
                CpuAccessFlags = CpuAccessFlags.Write,
                Format = SlimDX.DXGI.Format.R8G8B8A8_UNorm,
                OptionFlags = ResourceOptionFlags.None,
                Usage = ResourceUsage.Dynamic,
                MipLevels = 1,
                SampleDescription = new SampleDescription(1, 0)
            };

            Texture2D finalT = new Texture2D(DeviceContext.Device, finalDesc);
            DeviceContext.Immediate.CopyResource(outp, finalT);

            //Texture2D.ToFile(DeviceContext.Immediate, finalT, ImageFileFormat.Bmp, "prova.bmp");

            return finalT;
        }
        public ErrorCode UpdateBuffer()
        {
            ErrorCode Result = ErrorCode.Ok;

            try
            {
                if (!initialized)
                {
                    // Init();
                }

                bool lockTaken = false;
                try
                {
                    Monitor.TryEnter(syncLock, 5, ref lockTaken);

                    if (lockTaken)
                    {
                        foreach (var dupl in deskDupls)
                        {
                            var errorCode = dupl.TryGetScreenTexture(out Texture2D screenTexture);

                            if (errorCode != ErrorCode.Ok)
                            {
                                //CloseDx();

                                //Thread.Sleep(100);
                                return(errorCode);
                            }

                            var duplRect = dupl.duplRect;

                            ResourceRegion srcRegion = new ResourceRegion
                            {
                                Left   = duplRect.Left,
                                Top    = duplRect.Top,
                                Right  = duplRect.Right,
                                Bottom = duplRect.Bottom,
                                Back   = 1,
                            };

                            var destRect = dupl.drawRect;

                            device.ImmediateContext.CopySubresourceRegion(screenTexture, 0, srcRegion, compositionTexture, 0, destRect.Left, destRect.Top);
                        }
                    }
                    else
                    {
                        logger.Debug("lockTaken == false");
                    }
                }
                finally
                {
                    if (lockTaken)
                    {
                        Monitor.Exit(syncLock);
                    }
                }
            }
            catch (SharpDXException ex)
            {
                logger.Error(ex);
                // Process error...

                // CloseDx();

                //throw;
                Thread.Sleep(100);
            }

            return(Result);
        }
            private unsafe void DrawCursor(SharpDX.Direct2D1.RenderTarget renderTarger, CursorInfo cursor)
            {
                var position = cursor.Position;

                var shapeBuff = cursor.PtrShapeBuffer;
                var shapeInfo = cursor.ShapeInfo;

                int width  = shapeInfo.Width;
                int height = shapeInfo.Height;
                int pitch  = shapeInfo.Pitch;

                int left   = position.X;
                int top    = position.Y;
                int right  = position.X + width;
                int bottom = position.Y + height;

                //logger.Debug(left + " " + top + " " + right + " " + bottom);

                if (cursor.ShapeInfo.Type == (int)ShapeType.DXGI_OUTDUPL_POINTER_SHAPE_TYPE_COLOR)
                {
                    var data       = new DataPointer(shapeBuff, height * pitch);
                    var prop       = new Direct2D.BitmapProperties(new Direct2D.PixelFormat(Format.B8G8R8A8_UNorm, Direct2D.AlphaMode.Premultiplied));
                    var size       = new Size2(width, height);
                    var cursorBits = new Direct2D.Bitmap(renderTarger, size, data, pitch, prop);
                    try
                    {
                        var cursorRect = new RawRectangleF(left, top, right, bottom);

                        renderTarger.DrawBitmap(cursorBits, cursorRect, 1.0f, Direct2D.BitmapInterpolationMode.Linear);
                    }
                    finally
                    {
                        cursorBits?.Dispose();
                    }
                }
                else if (cursor.ShapeInfo.Type == (int)ShapeType.DXGI_OUTDUPL_POINTER_SHAPE_TYPE_MONOCHROME)
                {
                    height = height / 2;

                    left   = position.X;
                    top    = position.Y;
                    right  = position.X + width;
                    bottom = position.Y + height;
                    pitch  = width * 4;

                    Texture2D desktopRegionTex = null;
                    try
                    {
                        desktopRegionTex = new Texture2D(device,
                                                         new Texture2DDescription
                        {
                            CpuAccessFlags    = CpuAccessFlags.Read,
                            BindFlags         = BindFlags.None,
                            Format            = Format.B8G8R8A8_UNorm,
                            Width             = width,
                            Height            = height,
                            MipLevels         = 1,
                            ArraySize         = 1,
                            SampleDescription = { Count = 1, Quality = 0 },
                            Usage             = ResourceUsage.Staging,
                            OptionFlags       = ResourceOptionFlags.None,
                        });

                        var region           = new ResourceRegion(left, top, 0, right, bottom, 1);
                        var immediateContext = device.ImmediateContext;
                        immediateContext.CopySubresourceRegion(screenTexture, 0, region, desktopRegionTex, 0);

                        var dataBox = immediateContext.MapSubresource(desktopRegionTex, 0, MapMode.Read, MapFlags.None);
                        try
                        {
                            var desktopBuffer = new byte[width * height * 4];
                            Marshal.Copy(dataBox.DataPointer, desktopBuffer, 0, desktopBuffer.Length);

                            var shapeBufferLenght = width * height * 4;
                            var shapeBuffer       = new byte[shapeBufferLenght];

                            var maskBufferLenght = width * height / 8;
                            var andMaskBuffer    = new byte[maskBufferLenght];
                            Marshal.Copy(shapeBuff, andMaskBuffer, 0, andMaskBuffer.Length);

                            var xorMaskBuffer = new byte[maskBufferLenght];
                            Marshal.Copy(shapeBuff + andMaskBuffer.Length, xorMaskBuffer, 0, xorMaskBuffer.Length);

                            for (var row = 0; row < height; ++row)
                            {
                                byte mask = 0x80;

                                for (var col = 0; col < width; ++col)
                                {
                                    var maskIndex = row * width / 8 + col / 8;

                                    var andMask = ((andMaskBuffer[maskIndex] & mask) == mask) ? 0xFF : 0;
                                    var xorMask = ((xorMaskBuffer[maskIndex] & mask) == mask) ? 0xFF : 0;

                                    int pos = row * width * 4 + col * 4;
                                    for (int i = 0; i < 3; i++)
                                    {// RGB
                                        shapeBuffer[pos] = (byte)((desktopBuffer[pos] & andMask) ^ xorMask);
                                        pos++;
                                    }
                                    // Alpha
                                    shapeBuffer[pos] = (byte)((desktopBuffer[pos] & 0xFF) ^ 0);

                                    if (mask == 0x01)
                                    {
                                        mask = 0x80;
                                    }
                                    else
                                    {
                                        mask = (byte)(mask >> 1);
                                    }
                                }
                            }


                            Direct2D.Bitmap cursorBits = null;
                            try
                            {
                                fixed(byte *ptr = shapeBuffer)
                                {
                                    var data = new DataPointer(ptr, height * pitch);
                                    var prop = new Direct2D.BitmapProperties(new Direct2D.PixelFormat(Format.B8G8R8A8_UNorm, Direct2D.AlphaMode.Premultiplied));
                                    var size = new Size2(width, height);

                                    cursorBits = new Direct2D.Bitmap(renderTarger, size, data, pitch, prop);
                                };

                                var shapeRect = new RawRectangleF(left, top, right, bottom);

                                renderTarger.DrawBitmap(cursorBits, shapeRect, 1.0f, Direct2D.BitmapInterpolationMode.Linear);
                            }
                            finally
                            {
                                cursorBits?.Dispose();
                            }
                        }
                        finally
                        {
                            immediateContext.UnmapSubresource(desktopRegionTex, 0);
                        }
                    }
                    finally
                    {
                        desktopRegionTex?.Dispose();
                    }
                }
                else if (cursor.ShapeInfo.Type == (int)ShapeType.DXGI_OUTDUPL_POINTER_SHAPE_TYPE_COLOR)
                {
                    logger.Warn("Not supported cursor type " + ShapeType.DXGI_OUTDUPL_POINTER_SHAPE_TYPE_COLOR);
                }
            }
        private void PlatformGetData <T>(CubeMapFace cubeMapFace, int level, Rectangle rect, T[] data, int startIndex, int elementCount) where T : struct
        {
            // Create a temp staging resource for copying the data.
            //
            // TODO: Like in Texture2D, we should probably be pooling these staging resources
            // and not creating a new one each time.
            //
            var min       = _format.IsCompressedFormat() ? 4 : 1;
            var levelSize = Math.Max(size >> level, min);

            var desc = new Texture2DDescription
            {
                Width             = levelSize,
                Height            = levelSize,
                MipLevels         = 1,
                ArraySize         = 1,
                Format            = SharpDXHelper.ToFormat(_format),
                SampleDescription = new SampleDescription(1, 0),
                BindFlags         = BindFlags.None,
                CpuAccessFlags    = CpuAccessFlags.Read,
                Usage             = ResourceUsage.Staging,
                OptionFlags       = ResourceOptionFlags.None,
            };

            var d3dContext = GraphicsDevice._d3dContext;

            using (var stagingTex = new SharpDX.Direct3D11.Texture2D(GraphicsDevice._d3dDevice, desc))
            {
                lock (d3dContext)
                {
                    // Copy the data from the GPU to the staging texture.
                    var subresourceIndex = CalculateSubresourceIndex(cubeMapFace, level);
                    var elementsInRow    = rect.Width;
                    var rows             = rect.Height;
                    var region           = new ResourceRegion(rect.Left, rect.Top, 0, rect.Right, rect.Bottom, 1);
                    d3dContext.CopySubresourceRegion(GetTexture(), subresourceIndex, region, stagingTex, 0);

                    // Copy the data to the array.
                    DataStream stream = null;
                    try
                    {
                        var databox = d3dContext.MapSubresource(stagingTex, 0, MapMode.Read, MapFlags.None, out stream);

                        var elementSize = _format.GetSize();
                        if (_format.IsCompressedFormat())
                        {
                            // for 4x4 block compression formats an element is one block, so elementsInRow
                            // and number of rows are 1/4 of number of pixels in width and height of the rectangle
                            elementsInRow /= 4;
                            rows          /= 4;
                        }
                        var rowSize = elementSize * elementsInRow;
                        if (rowSize == databox.RowPitch)
                        {
                            stream.ReadRange(data, startIndex, elementCount);
                        }
                        else
                        {
                            // Some drivers may add pitch to rows.
                            // We need to copy each row separatly and skip trailing zeros.
                            stream.Seek(0, SeekOrigin.Begin);

                            var elementSizeInByte = ReflectionHelpers.SizeOf <T> .Get();

                            for (var row = 0; row < rows; row++)
                            {
                                int i;
                                for (i = row * rowSize / elementSizeInByte; i < (row + 1) * rowSize / elementSizeInByte; i++)
                                {
                                    data[i + startIndex] = stream.Read <T>();
                                }

                                if (i >= elementCount)
                                {
                                    break;
                                }

                                stream.Seek(databox.RowPitch - rowSize, SeekOrigin.Current);
                            }
                        }
                    }
                    finally
                    {
                        SharpDX.Utilities.Dispose(ref stream);
                    }
                }
            }
        }
        bool copyResource()
        {
            try
            {
                //MessageBox((IntPtr)0, screenTexture2D.Description.BindFlags.ToString() + "", "Oculus Error", 0);
                using (var screenTexture2D = _screenResource.QueryInterface <Texture2D>())
                {
                    /*var texture = new Texture2D(sccsVD4VE_LightNWithoutVr.SC_Console_DIRECTX._dxDevice.Device, new Texture2DDescription()
                     * {
                     *  CpuAccessFlags = CpuAccessFlags.None,
                     *  BindFlags = BindFlags.ShaderResource | BindFlags.RenderTarget,
                     *  Format = Format.B8G8R8A8_UNorm,
                     *  Width = columns,
                     *  Height = rows,
                     *  OptionFlags = ResourceOptionFlags.GenerateMipMaps,
                     *  MipLevels = 1,
                     *  ArraySize = 1,
                     *  SampleDescription = { Count = 1, Quality = 0 },
                     *  Usage = ResourceUsage.Default
                     * }, new DataRectangle(interptr, memoryBitmapStride));
                     *
                     * _device.ImmediateContext.UnmapSubresource(screenTexture2D, 0);*/

                    _device.ImmediateContext.CopyResource(screenTexture2D, _texture2D);
                }

                var dataBox = _device.ImmediateContext.MapSubresource(_texture2D, 0, SharpDX.Direct3D11.MapMode.Read, SharpDX.Direct3D11.MapFlags.None);

                int memoryBitmapStride = _textureDescription.Width * 4;

                int    columns  = _textureDescription.Width;
                int    rows     = _textureDescription.Height;
                IntPtr interptr = dataBox.DataPointer;

                _device.ImmediateContext.UnmapSubresource(_texture2D, 0);



                /*byte* ptr = (byte*)interptr.ToPointer();
                 *
                 * int _pixelSize = 3;
                 * int _nWidth = _textureDescriptionFinal.Width * _pixelSize;
                 * int _nHeight = _textureDescriptionFinal.Height;
                 * int counterY = 0;
                 * int counterX = 0;
                 *
                 * int _nWidthDIV = (_textureDescriptionFinal.Width * _pixelSize) / num_cols;
                 * int _nWidthDIVTWO = (_textureDescriptionFinal.Width * 4) / num_cols;
                 * int _nHeightDIV = _textureDescriptionFinal.Height / num_rows;
                 * int mainArrayIndex = 0;
                 *
                 * int ycount = 0;
                 * int xcount = 0;*/

                /* byte* ptr = (byte*)interptr.ToPointer();
                 *
                 * int _pixelSize = 3;
                 * int _nWidth = _textureDescriptionFinal.Width * _pixelSize;
                 * int _nHeight = _textureDescriptionFinal.Height;
                 * int counterY = 0;
                 * int counterX = 0;
                 * int mainArrayIndex = 0;
                 *
                 * int someIndexX = 0;
                 * int someIndexY = 0;
                 *
                 * int _nWidthDIV = (_textureDescriptionFinal.Width * _pixelSize) / num_cols;
                 * int _nWidthDIVTWO = (_textureDescriptionFinal.Width * 4) / num_cols;
                 * int _nHeightDIV = _textureDescriptionFinal.Height / num_rows;
                 *
                 * for (int y = 0; y < _nHeight; y++)
                 * {
                 *   for (int x = 0; x < _nWidth; x++)
                 *   {
                 *       if (x % _pixelSize == 0 || x == 0)
                 *       {
                 *           var bytePoser = ((y * _nWidth) + x);
                 *           mainArrayIndex = (counterY * num_cols) + counterX;
                 *
                 *           var test0 = ptr[bytePoser + 0];
                 *           var test1 = ptr[bytePoser + 1];
                 *           var test2 = ptr[bytePoser + 2];
                 *
                 *           var indexOfFracturedImageBytes = ((someIndexY) * _nWidthDIV) + someIndexX;
                 *
                 *           try
                 *           {
                 *               arrayOfBytes[mainArrayIndex][indexOfFracturedImageBytes + 0] = test0; //b
                 *               arrayOfBytes[mainArrayIndex][indexOfFracturedImageBytes + 1] = test1; //g
                 *               arrayOfBytes[mainArrayIndex][indexOfFracturedImageBytes + 2] = test2; //r
                 *               arrayOfBytes[mainArrayIndex][indexOfFracturedImageBytes + 3] = 1;     //a
                 *           }
                 *           catch (Exception ex)
                 *           {
                 *               MainWindow.MessageBox((IntPtr)0, "index: " + mainArrayIndex + " _ " + indexOfFracturedImageBytes + " _ " + ex.ToString(), "sccs message", 0);
                 *           }
                 *
                 *           ptr++;
                 *       }
                 *
                 *
                 *
                 *       /*if (someIndexY % _nHeightDIV == 0 && someIndexY != 0)
                 *       {
                 *           someIndexY = 0;
                 *       }
                 *
                 *       if (x % _nWidthDIV == 0 && x != 0 && counterX < 9)
                 *       {
                 *           counterX++;
                 *       }
                 *
                 *       someIndexX++;
                 *       if (someIndexX % _nWidthDIV == 0 && someIndexX != 0)
                 *       {
                 *           someIndexX = 0;
                 *       }
                 *   }
                 *
                 *   if (y % _nHeightDIV == 0 && y != 0 && counterY < 9)
                 *   {
                 *       someIndexY = 0;
                 *       counterY++;
                 *       counterX = 0;
                 *   }
                 *   someIndexY++;
                 * }*/

                _device.ImmediateContext.UnmapSubresource(_texture2D, 0);
                _device.ImmediateContext.CopyResource(_texture2D, _texture2DFinal);

                //arrayOfTexture2DFrac
                //Copy(_device, _texture2DFinal, arrayOfTexture2DFrac);
                //device.ImmediateContext.CopySubresourceRegion(source, 0, region, target, 0);

                //_SystemTickPerformance.Stop();
                //_SystemTickPerformance.Reset();
                //_SystemTickPerformance.Start();

                //image = new System.Drawing.Bitmap(columns, rows, memoryBitmapStride, PixelFormat.Format32bppArgb, interptr);

                //source_rect = new System.Drawing.Rectangle(0, 0, wid, hgt);

                source_rect = new System.Drawing.Rectangle(0, 0, _textureDescriptionFinal.Width, _textureDescriptionFinal.Height);

                var region = new ResourceRegion(0, 0, 0, wid, hgt, 1);

                region = new ResourceRegion(source_rect.X, source_rect.Y, 0, _textureDescriptionFinal.Width, _textureDescriptionFinal.Height, 1);

                for (int row = 0; row < num_rows; row++)
                {
                    source_rect.X = 0;

                    for (int col = 0; col < num_cols; col++)
                    {
                        var mainArrayIndex = (row * num_cols) + col;

                        region.Left = source_rect.X;

                        region.Top = source_rect.Y;

                        _device.ImmediateContext.CopySubresourceRegion(_texture2DFinal, 0, region, arrayOfTexture2DFrac[mainArrayIndex], 0);

                        _ShaderResourceViewArray[mainArrayIndex] = new ShaderResourceView(_device, _texture2DFinal, resourceViewDescription);

                        _device.ImmediateContext.GenerateMips(_ShaderResourceViewArray[mainArrayIndex]);

                        source_rect.X += wid;
                    }

                    source_rect.Y += hgt;
                }



                if (_ShaderResourceViewArray != null)
                {
                    _frameCaptureData._ShaderResourceArray = _ShaderResourceViewArray;
                }

                if (_lastShaderResourceViewArray != null)
                {
                    for (int i = 0; i < _lastShaderResourceViewArray.Length; i++)
                    {
                        if (_lastShaderResourceViewArray[i] != null)
                        {
                            _lastShaderResourceViewArray[i].Dispose();
                        }
                    }
                }

                _lastShaderResourceViewArray = _ShaderResourceViewArray;

                /*
                 * image = new System.Drawing.Bitmap(columns, rows, memoryBitmapStride, PixelFormat.Format32bppArgb, interptr);
                 *
                 * using (Graphics gr = Graphics.FromImage(piece))
                 * {
                 *   for (int row = 0; row < num_rows; row++)
                 *   {
                 *       source_rect.X = 0;
                 *       for (int col = 0; col < num_cols; col++)
                 *       {
                 *           //gr.DrawImage(image, dest_rect, source_rect, GraphicsUnit.Pixel);
                 *
                 *
                 *
                 *           //piece.Save(@"C:\Users\steve\OneDrive\Desktop\screenRecord\" + row.ToString("00") + col.ToString("00") + ".png");
                 *           source_rect.X += wid;
                 *       }
                 *       source_rect.Y += hgt;
                 *   }
                 * }
                 * MessageBox((IntPtr)0, _SystemTickPerformance.Elapsed.Milliseconds + "", "Oculus Error", 0);*/

                //_SystemTickPerformance.Stop();
                //_SystemTickPerformance.Reset();
                //_SystemTickPerformance.Start();

                /*for (int i = 0; i < arrayOfTexture2DFrac.Length; i++)
                 * {
                 *  if (arrayOfTexture2DFrac[i] != null)
                 *  {
                 *      dataBox = _device.ImmediateContext.MapSubresource(arrayOfTexture2DFrac[i], 0, SharpDX.Direct3D11.MapMode.Read, SharpDX.Direct3D11.MapFlags.None);
                 *      //memoryBitmapStride = _textureDescription.Width * 4;
                 *      //columns = _textureDescription.Width;
                 *      //rows = _textureDescription.Height;
                 *      interptr = dataBox.DataPointer;
                 *
                 *      _device.ImmediateContext.UnmapSubresource(arrayOfTexture2DFrac[i], 0);
                 *
                 *      System.Drawing.Bitmap image = new System.Drawing.Bitmap(wid, hgt, strider, PixelFormat.Format32bppArgb, interptr);// Marshal.UnsafeAddrOfPinnedArrayElement(arrayOfTexture2DFrac[i], 0));
                 *
                 *      string filePathVE = "desktop capture";
                 *      var exportedToFolderPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                 *
                 *      filePathVE = exportedToFolderPath + "\\" + filePathVE;// @"LAYERS\PNG\";
                 *
                 *      if (!Directory.Exists(filePathVE))
                 *      {
                 *          Directory.CreateDirectory(filePathVE);
                 *      }
                 *
                 *      var fi = new FileInfo(filePathVE);
                 *      fi.Refresh();
                 *
                 *      image.Save(filePathVE + "\\" + imageCounter + ".jpg");
                 *      imageCounter++;
                 *  }
                 * }*/
                //MessageBox((IntPtr)0, _SystemTickPerformance.Elapsed.Milliseconds + "", "Oculus Error", 0);

                /*if (_arrayOfIntPTR.Count > 0)
                 * {
                 *  if (_counterForPTR > 10)
                 *  {
                 *      for (int i = 0; i < (int)Math.Ceiling((double)_arrayOfIntPTR.Count * _howFast); i++)
                 *      {
                 *          DeleteObject(_arrayOfIntPTR[i]);
                 *      }
                 *      _counterForPTR = 0;
                 *  }
                 * }
                 * _counterForPTR++;*/

                return(true);
            }
            catch (Exception ex)
            {
                MainWindow.MessageBox((IntPtr)0, ex.ToString(), "sccs error message", 0);
            }
            return(false);
        }
Esempio n. 42
0
        public void SetData <T>(CubeMapFace face, int level, Rectangle?rect, T[] data, int startIndex, int elementCount) where T : struct
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }

            var elementSizeInByte = Marshal.SizeOf(typeof(T));
            var dataHandle        = GCHandle.Alloc(data, GCHandleType.Pinned);

            // Use try..finally to make sure dataHandle is freed in case of an error
            try
            {
                var dataPtr = (IntPtr)(dataHandle.AddrOfPinnedObject().ToInt64() + startIndex * elementSizeInByte);

                int xOffset, yOffset, width, height;
                if (rect.HasValue)
                {
                    xOffset = rect.Value.X;
                    yOffset = rect.Value.Y;
                    width   = rect.Value.Width;
                    height  = rect.Value.Height;
                }
                else
                {
                    xOffset = 0;
                    yOffset = 0;
                    width   = Math.Max(1, this.size >> level);
                    height  = Math.Max(1, this.size >> level);

                    // For DXT textures the width and height of each level is a multiple of 4.
                    // OpenGL only: The last two mip levels require the width and height to be
                    // passed as 2x2 and 1x1, but there needs to be enough data passed to occupy
                    // a 4x4 block.
                    // Ref: http://www.mentby.com/Group/mac-opengl/issue-with-dxt-mipmapped-textures.html
                    if (_format == SurfaceFormat.Dxt1 ||
                        _format == SurfaceFormat.Dxt1a ||
                        _format == SurfaceFormat.Dxt3 ||
                        _format == SurfaceFormat.Dxt5)
                    {
#if DIRECTX
                        width  = (width + 3) & ~3;
                        height = (height + 3) & ~3;
#else
                        if (width > 4)
                        {
                            width = (width + 3) & ~3;
                        }
                        if (height > 4)
                        {
                            height = (height + 3) & ~3;
                        }
#endif
                    }
                }

#if DIRECTX
                var box = new DataBox(dataPtr, GetPitch(width), 0);

                int subresourceIndex = (int)face * _levelCount + level;

                var region = new ResourceRegion
                {
                    Top    = yOffset,
                    Front  = 0,
                    Back   = 1,
                    Bottom = yOffset + height,
                    Left   = xOffset,
                    Right  = xOffset + width
                };

                var d3dContext = GraphicsDevice._d3dContext;
                lock (d3dContext)
                    d3dContext.UpdateSubresource(box, GetTexture(), subresourceIndex, region);
#elif PSM
                //TODO
#else
                GL.BindTexture(TextureTarget.TextureCubeMap, this.glTexture);
                GraphicsExtensions.CheckGLError();

                TextureTarget target = GetGLCubeFace(face);
                if (glFormat == (PixelFormat)All.CompressedTextureFormats)
                {
                    throw new NotImplementedException();
                }
                else
                {
                    GL.TexSubImage2D(target, level, xOffset, yOffset, width, height, glFormat, glType, dataPtr);
                    GraphicsExtensions.CheckGLError();
                }
#endif
            }
            finally
            {
                dataHandle.Free();
            }
        }
Esempio n. 43
0
        protected unsafe override void UpdateTextureCore(
            Texture texture,
            IntPtr source,
            uint sizeInBytes,
            uint x,
            uint y,
            uint z,
            uint width,
            uint height,
            uint depth,
            uint mipLevel,
            uint arrayLayer)
        {
            D3D11Texture d3dTex = Util.AssertSubtype <Texture, D3D11Texture>(texture);
            bool         useMap = (texture.Usage & TextureUsage.Staging) == TextureUsage.Staging;

            if (useMap)
            {
                uint subresource           = texture.CalculateSubresource(mipLevel, arrayLayer);
                MappedResourceCacheKey key = new MappedResourceCacheKey(texture, subresource);
                MappedResource         map = MapCore(texture, MapMode.Write, subresource);

                uint denseRowSize   = FormatHelpers.GetRowPitch(width, texture.Format);
                uint denseSliceSize = FormatHelpers.GetDepthPitch(denseRowSize, height, texture.Format);

                Util.CopyTextureRegion(
                    source.ToPointer(),
                    0, 0, 0,
                    denseRowSize, denseSliceSize,
                    map.Data.ToPointer(),
                    x, y, z,
                    map.RowPitch, map.DepthPitch,
                    width, height, depth,
                    texture.Format);

                UnmapCore(texture, subresource);
            }
            else
            {
                int            subresource    = D3D11Util.ComputeSubresource(mipLevel, texture.MipLevels, arrayLayer);
                ResourceRegion resourceRegion = new ResourceRegion(
                    left: (int)x,
                    right: (int)(x + width),
                    top: (int)y,
                    front: (int)z,
                    bottom: (int)(y + height),
                    back: (int)(z + depth));
                uint srcRowPitch   = FormatHelpers.GetSizeInBytes(texture.Format) * width;
                uint srcDepthPitch = srcRowPitch * depth;
                lock (_immediateContextLock)
                {
                    _immediateContext.UpdateSubresource(
                        d3dTex.DeviceTexture,
                        subresource,
                        resourceRegion,
                        source,
                        (int)srcRowPitch,
                        (int)srcDepthPitch);
                }
            }
        }
Esempio n. 44
0
        public void UpdateRectangles( IList< Image4ub > images, IList< Rect2i > targets )
        {
#if false
            var wrapper = D3D10Wrapper.Instance;

            var im = new Image4ub( this.Size, Color4ub.Red );
            fixed( void* ptr = im.Pixels )
            {
                var userBuffer = new IntPtr( ptr );
                var dataStream = new DataStream( userBuffer, 4 * im.NumPixels, true, true );
                var sourceBox = new DataBox( 4 * im.Width, 4 * im.Width * im.Height, dataStream );

                var targetRegion = new ResourceRegion
                {
                    Back = 1,
                    Front = 0,
                    Bottom = 4096,
                    Top = 0,
                    Left = 0,
                    Right = 4096
                };

                wrapper.Device.UpdateSubresource( sourceBox, Texture, 0, targetRegion );
                dataStream.Close();
            }

            return;
#endif
            if( images.Count != targets.Count )
            {
                throw new ArgumentException( "images and targets must be of the same length" );
            }

            var rect = Texture.Map( 0, MapMode.WriteDiscard, MapFlags.None );

            for( int i = 0; i < images.Count; ++i )
            {
                var im = images[ i ];
                var target = targets[ i ];

                for( int y = 0; y < im.Height; ++y )
                {
                    int sourceOffset = 4 * y * im.Width;
                    int sourceCount = 4 * im.Width;

                    rect.Data.Position = 4 * ( ( y + target.Origin.y ) * Width + target.Origin.x );
                    rect.Data.Write( im.Pixels, sourceOffset, sourceCount );
                }
            }

            rect.Data.Close();
            Texture.Unmap( 0 );
        }
        public void Update(IPluginIO pin, DX11RenderContext context)
        {
            if (this.FOutGeom.SliceCount == 0) { return; }

            if (this.dispatchBuffer == null)
            {
                this.dispatchBuffer = new DispatchIndirectBuffer(context);
            }

            if (!this.FOutGeom[0].Contains(context))
            {
                this.indirectDispatch = new DX11NullIndirectDispatcher();
                this.indirectDispatch.IndirectArgs = this.dispatchBuffer;

                DX11NullGeometry nullgeom = new DX11NullGeometry(context);
                nullgeom.AssignDrawer(this.indirectDispatch);

                this.FOutGeom[0][context] = nullgeom;
            }

            var countuav = this.FInArgBuffer[0][context];

            var argBuffer = this.dispatchBuffer.Buffer;

            int argOffset = this.FInArgOffset[0];
            ResourceRegion region = new ResourceRegion(argOffset, 0, 0, argOffset + 12, 1, 1); //Packed xyz value here
            context.CurrentDeviceContext.CopySubresourceRegion(this.FInArgBuffer[0][context].Buffer, 0, region, argBuffer, 0, 0, 0, 0);
        }
Esempio n. 46
0
 internal unsafe void UpdateSubresource(GraphicsResource resource, int subResourceIndex, DataBox databox, ResourceRegion region)
 {
     if (resource == null) throw new ArgumentNullException("resource");
     NativeDeviceContext.UpdateSubresource(*(SharpDX.DataBox*)Interop.Cast(ref databox), resource.NativeResource, subResourceIndex, *(SharpDX.Direct3D11.ResourceRegion*)Interop.Cast(ref region));
 }