Exemple #1
0
        public void Apply(DX11Texture2D texture, int w, int h, int d, SlimDX.DXGI.Format format, int slice)
        {
            format = format == SlimDX.DXGI.Format.Unknown ? texture.Format : format;

            if (this.rtarr != null)
            {
                if (this.rtarr.ElemCnt != d || this.rtarr.Width != w || this.rtarr.Height != h
                    || this.rtarr.Format != format)
                {
                    this.rtarr.Dispose(); this.rtarr = null;
                }
            }

            if (this.rtarr == null)
            {
                this.rtarr = new DX11RenderTextureArray(this.context, w, h, d, format);
            }

            this.shader.SelectTechnique("Render");
            this.quad.Bind(this.layout);

            int idx = VMath.Zmod(slice, d);

            //Push specific slice as render target
            this.context.RenderTargetStack.Push(this.rtarr.SliceRTV[idx]);

            //Call simple shader (could use full screen triangle instead)
            this.shader.SetBySemantic("TEXTURE", texture.SRV);
            this.shader.ApplyPass(0);
            this.quad.Draw();
            this.context.RenderTargetStack.Pop();
        }
Exemple #2
0
        public void Update(IPluginIO pin, DX11RenderContext context)
        {
            if (FInvalidate)
            {
                if (FTexture == null)
                {
                    return;
                }

                var texture            = new Texture2D(context.Device, FTexture.Description);
                var shaderResourceView = new ShaderResourceView(context.Device, texture);
                var resource           = DX11Texture2D.FromTextureAndSRV(context, texture, shaderResourceView);

                FTextureOut[0][context] = resource;

                FInvalidate = false;
            }

            if (FTexture == null)
            {
                return;
            }

            context.CurrentDeviceContext.CopyResource(FTexture, FTextureOut[0][context].Resource);
        }
        public void Update(DX11RenderContext context)
        {
            Device device = context.Device;

            if (this.spmax == 0)
            {
                return;
            }

            if (this.updateddevices.Contains(context))
            {
                return;
            }

            if (!this.FOutTexture[0].Contains(context))
            {
                var result = new DX11RenderTextureArray(context, (int)this.FInSize[0].X, (int)this.FInSize[0].Y, this.FInElementCount[0], DeviceFormatHelper.GetFormat(this.FInFormat[0]), true, this.FInMips[0] ? 0 : 1, this.FInAllowUAV[0]);
                this.FOutTexture[0][context]      = result;
                this.FOutDepthTexture[0][context] = new DX11DepthTextureArray(context, (int)this.FInSize[0].X, (int)this.FInSize[0].Y, this.FInElementCount[0], Format.R32_Float, true);
                for (int i = 0; i < this.FInElementCount[0]; i++)
                {
                    DX11Texture2D slice = DX11Texture2D.FromTextureAndSRV(context, result.Resource, result.SliceRTV[i].SRV);
                    this.FOutSliceTextures[i][context] = slice;
                }
            }

            this.updateddevices.Add(context);
        }
        public DX11MipSliceRenderTarget2D(DX11RenderContext context, DX11Texture2D texture, int mipindex, int w, int h)
        {
            this.context = context;
            this.Resource = texture.Resource;

            RenderTargetViewDescription rtd = new RenderTargetViewDescription()
            {
                Dimension = RenderTargetViewDimension.Texture2D,
                Format = texture.Format,
                MipSlice = mipindex
            };

            UnorderedAccessViewDescription uavd = new UnorderedAccessViewDescription()
            {
                Dimension = UnorderedAccessViewDimension.Texture2D,
                Format = texture.Format,
                MipSlice = mipindex,
            };

            ShaderResourceViewDescription srvd = new ShaderResourceViewDescription();
            srvd.Dimension = ShaderResourceViewDimension.Texture2D;
            srvd.MipLevels = 1;
            srvd.MostDetailedMip = mipindex;
            srvd.Format = texture.Format;

            this.SRV = new ShaderResourceView(context.Device, texture.Resource, srvd);
        }
        public DX11FileTexturePoolElement(DX11RenderContext context, string path, bool mips, bool async = false)
        {
            this.FileName = path;
            this.DoMips   = mips;
            this.refcount = 1;


            if (async)
            {
                this.m_task           = new FileTexture2dLoadTask(context, path, mips);
                m_task.StatusChanged += task_StatusChanged;

                context.ResourceScheduler.AddTask(m_task);
            }
            else
            {
                try
                {
                    ImageLoadInformation info = ImageLoadInformation.FromDefaults();
                    if (!this.DoMips)
                    {
                        info.MipLevels = 1;
                    }

                    this.Texture = DX11Texture2D.FromFile(context, path, info);
                    this.Status  = eDX11SheduleTaskStatus.Completed;
                }
                catch
                {
                    this.Status = eDX11SheduleTaskStatus.Error;
                }
            }
        }
        public void Update(IPluginIO pin, DX11RenderContext context)
        {
            if (this.FInvalidate)
            {
                if (this.FTextureOutput[0].Contains(context))
                {
                    this.FTextureOutput[0].Dispose(context);
                }

                try
                {
                    Texture2D          tex = context.Device.OpenSharedResource <Texture2D>(new IntPtr(this.FPointer[0]));
                    ShaderResourceView srv = new ShaderResourceView(context.Device, tex);

                    DX11Texture2D resource = DX11Texture2D.FromTextureAndSRV(context, tex, srv);

                    this.FTextureOutput[0][context] = resource;

                    this.FValid[0] = true;
                }
                catch (Exception ex)
                {
                    this.FValid[0] = false;
                }

                this.FInvalidate = false;
            }
        }
Exemple #7
0
        public void Apply(DX11Texture2D texture, int w, int h, int d, SlimDX.DXGI.Format format, int slice)
        {
            format = format == SlimDX.DXGI.Format.Unknown ? texture.Format : format;

            if (this.rtarr != null)
            {
                if (this.rtarr.ElemCnt != d || this.rtarr.Width != w || this.rtarr.Height != h ||
                    this.rtarr.Format != format)
                {
                    this.rtarr.Dispose(); this.rtarr = null;
                }
            }

            if (this.rtarr == null)
            {
                this.rtarr = new DX11RenderTextureArray(this.context, w, h, d, format, true, 1);
            }

            this.shader.SelectTechnique("Render");
            this.quad.Bind(this.layout);

            int idx = VMath.Zmod(slice, d);

            //Push specific slice as render target
            this.context.RenderTargetStack.Push(this.rtarr.SliceRTV[idx]);

            //Call simple shader (could use full screen triangle instead)
            this.shader.SetBySemantic("TEXTURE", texture.SRV);
            this.shader.ApplyPass(0);
            this.quad.Draw();
            this.context.RenderTargetStack.Pop();
        }
 private void DisposeTexture()
 {
     if (this.lasttexture != null)
     {
         this.lasttexture.Dispose(); this.lasttexture = null;
     }
 }
        public void Update(IPluginIO pin, DX11RenderContext context)
        {
            Device device = context.Device;

            if (this.spmax == 0)
            {
                return;
            }

            if (this.updateddevices.Contains(context))
            {
                return;
            }

            if (!this.FOutCubeTexture[0].Contains(context))
            {
                var cube = new DX11CubeRenderTarget(context, this.FInSize[0], this.sd, DeviceFormatHelper.GetFormat(this.FInFormat[0].Name), false, 1);
                this.FOutCubeTexture[0][context]      = cube;
                this.FOutCubeDepthTexture[0][context] = new DX11CubeDepthStencil(context, this.FInSize[0], this.sd, Format.D24_UNorm_S8_UInt);
                for (int i = 0; i < 6; i++)
                {
                    this.FOutSliceTextures[i][context] = DX11Texture2D.FromTextureAndSRV(context, cube.Resource, cube.SliceRTV[i].SRV);
                }
            }

            this.updateddevices.Add(context);
        }
Exemple #10
0
        public void Update(IPluginIO pin, DX11RenderContext context)
        {
            if (this.FInvalidate)
            {
                for (int i = 0; i < FTextureOutput.SliceCount; i++)
                {
                    if (this.FTextureOutput[i].Contains(context))
                    {
                        this.FTextureOutput[i].Dispose(context);
                    }

                    try
                    {
                        int                p     = unchecked ((int)this.FPointer[i]);
                        IntPtr             share = new IntPtr(p);
                        Texture2D          tex   = context.Device.OpenSharedResource <Texture2D>(share);
                        ShaderResourceView srv   = new ShaderResourceView(context.Device, tex);

                        DX11Texture2D resource = DX11Texture2D.FromTextureAndSRV(context, tex, srv);

                        this.FTextureOutput[i][context] = resource;
                        this.FValid[i] = true;
                    }
                    catch (Exception)
                    {
                        this.FValid[i] = false;
                    }
                }
                this.FInvalidate = false;
            }
        }
        public DX11MipSliceRenderTarget(DX11RenderContext context, DX11Texture2D texture, int mipindex, int w, int h)
        {
            this.context = context;
            this.Width = w;
            this.Height = h;
            this.Depth = 1;

            RenderTargetViewDescription rtd = new RenderTargetViewDescription()
            {
                Dimension = RenderTargetViewDimension.Texture2D,
                Format = texture.Format,
                MipSlice = mipindex
            };

            ShaderResourceViewDescription srvd = new ShaderResourceViewDescription();
            srvd.Dimension = ShaderResourceViewDimension.Texture2D;
            srvd.MipLevels = 1;
            srvd.MostDetailedMip = mipindex;
            srvd.Format = texture.Format;


            this.RTV = new RenderTargetView(context.Device, texture.Resource, rtd);
            this.SRV = new ShaderResourceView(context.Device, texture.Resource, srvd);
            
        }
Exemple #12
0
 private void InitTexture(DX11RenderContext context, int index, Texture2DDescription description)
 {
     this.FTextureOutput[index].Dispose(context);
     this.FTextureOutput[index]          = new DX11Resource <DX11Texture2D>();
     description.ArraySize               = 1;
     this.FTextureOutput[index][context] = DX11Texture2D.FromDescription(context, description);
 }
        public DX11SliceRenderTarget(DX11RenderContext context, DX11Texture2D texture, int sliceindex)
        {
            this.isowner = false;
            this.context = context;
            this.parent = texture;
            this.desc = texture.Description;

            RenderTargetViewDescription rtd = new RenderTargetViewDescription()
            {
                ArraySize = 1,
                Dimension = RenderTargetViewDimension.Texture2DArray,
                Format = texture.Format,
                MipSlice = 0,
                FirstArraySlice = sliceindex,
            };

            this.RTV = new RenderTargetView(context.Device, this.parent.Resource, rtd);

            ShaderResourceViewDescription srvd = new ShaderResourceViewDescription()
            {
                ArraySize = 1,
                Dimension = ShaderResourceViewDimension.Texture2DArray,
                Format = texture.Format,
                FirstArraySlice = sliceindex,
                MipLevels = texture.Resource.Description.MipLevels,
                MostDetailedMip = 0
            };

            this.SRV = new ShaderResourceView(context.Device, this.parent.Resource, srvd);
        }
Exemple #14
0
        public static DX11Texture2D SolidColor(DxDevice device, Color4 color)
        {
            DataStream ds = new DataStream(4, true, true);

            ds.Write <int>(color.ToRgba());

            Texture2DDescription td = new Texture2DDescription()
            {
                ArraySize         = 1,
                BindFlags         = BindFlags.ShaderResource,
                CpuAccessFlags    = CpuAccessFlags.None,
                Format            = Format.R8G8B8A8_UNorm,
                Height            = 1,
                MipLevels         = 1,
                OptionFlags       = ResourceOptionFlags.None,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = ResourceUsage.Immutable,
                Width             = 1
            };

            DataBox db = new DataBox(ds.DataPointer);

            db.RowPitch = 4;
            Texture2D texture = new Texture2D(device.Device, td, new DataBox[1] {
                db
            });

            ds.Dispose();
            ShaderResourceView srv = new ShaderResourceView(device.Device, texture);

            return(DX11Texture2D.FromReference(device, texture, srv));
        }
 private void BindTextureSemantic(Effect effect, string semantic, DX11Texture2D resource)
 {
     foreach (EffectResourceVariable erv in this.varmanager.texturecache)
     {
         if (erv.Description.Semantic == semantic)
         {
             effect.GetVariableByName(erv.Description.Name).AsResource().SetResource(resource.SRV);
         }
     }
 }
Exemple #16
0
        public static void SaveToMemoryCompressed(DX11RenderContext device, DX11Texture2D texture, DdsBlockType blockType, out IntPtr data, out int size, out IntPtr blob)
        {
            long retcode = NativeMethods.SaveCompressedTextureToMemory(device.Device.ComPointer, device.CurrentDeviceContext.ComPointer,
                texture.Resource.ComPointer, (int)blockType, out data, out size,out blob);

            if (retcode < 0)
            {
                throw new Exception("Failed to Save Texture");
            }
        }
Exemple #17
0
        public static void SaveToFileCompressed(DX11RenderContext device, DX11Texture2D texture, string path, DdsBlockType blockType)
        {
            long retcode = NativeMethods.SaveCompressedTextureToFile(device.Device.ComPointer, device.CurrentDeviceContext.ComPointer,
                texture.Resource.ComPointer, path, (int)blockType);

            if (retcode < 0)
            {
                throw new Exception("Failed to Save Texture");
            }
        }
        private void WriteResult(TextureArraySetSlice generator, DX11RenderContext context)
        {
            DX11RenderTextureArray result = generator.Result;

            this.FOutTB[0][context] = generator.Result;

            for (int i = 0; i < this.FOutSliceTextures.SliceCount; i++)
            {
                DX11Texture2D slice = DX11Texture2D.FromTextureAndSRV(context, result.Resource, result.SliceRTV[i].SRV);
                this.FOutSliceTextures[i][context] = slice;
            }
        }
        public bool TryGetFile(DX11RenderContext context, string path, bool domips,bool async, out DX11Texture2D texture)
        {
            lock (m_lock)
            {
                foreach (DX11FileTexturePoolElement element in this.pool)
                {
                    if (element.DoMips == domips && element.FileName == path)
                    {
                        if (element.Status == eDX11SheduleTaskStatus.Completed)
                        {
                            element.IncrementCounter();
                            texture = element.Texture;
                            return true;
                        }
                        else
                        {
                            element.IncrementCounter();
                            texture = null;
                            return false;
                        }
                    }
                }
            }

            DX11FileTexturePoolElement elem = new DX11FileTexturePoolElement(context, path, domips,async);
            elem.OnLoadComplete += elem_OnLoadComplete;

            lock (m_lock)
            {
                if (elem.Status != eDX11SheduleTaskStatus.Error)
                {
                    this.pool.Add(elem);
                    if (elem.Status == eDX11SheduleTaskStatus.Completed)
                    {
                        texture = elem.Texture;
                        return true;
                    }
                    else
                    {
                        texture = null;
                        return false;
                    }

                }
                else
                {
                    texture = null;
                    return false;
                }
            }
        }
        private void MainLoop_OnPresent(object sender, EventArgs e)
        {
            //Rendering is finished, so should be ok to grab texture now
            if (this.FTextureInput.PluginIO.IsConnected && this.FTextureInput.SliceCount > 0)
            {
                //Little temp hack, grab context from global, since for now we have one context anyway
                DX11RenderContext context = DX11GlobalDevice.DeviceManager.RenderContexts[0];

                if (this.FTextureInput[0].Contains(context))
                {
                    DX11Texture2D texture = this.FTextureInput[0][context];

                    if (texture is DX11DepthStencil)
                    {
                        this.logger.Log(LogType.Warning, "FrameDelay for depth texture is not supported");
                        return;
                    }

                    if (this.lasttexture != null)
                    {
                        if (this.lasttexture.Description != texture.Description)
                        {
                            this.DisposeTexture();
                        }
                    }

                    if (this.lasttexture == null)
                    {
                        this.lasttexture = DX11Texture2D.FromDescription(context, texture.Description);
                    }

                    context.CurrentDeviceContext.CopyResource(texture.Resource, this.lasttexture.Resource);

                    if (this.FInFlush[0])
                    {
                        context.CurrentDeviceContext.Flush();
                    }
                }
                else
                {
                    this.DisposeTexture();
                }
            }
            else
            {
                this.DisposeTexture();
            }
        }
Exemple #21
0
        public unsafe void Update(DX11RenderContext context)
        {
            FLogger.Log(LogType.Debug, "1");
            if (!this.invalidate)
            {
                return;
            }
            FLogger.Log(LogType.Debug, "2");


            FLogger.Log(LogType.Debug, "3");

            if (this.marginalTexture[0].Contains(context))
            {
                FLogger.Log(LogType.Debug, "dispose");
                this.marginalTexture[0].Dispose(context);
            }

            var data = this.hdrDataIn[0];

            if (this.hdrDataIn.IsConnected && data != null)
            {
                FLogger.Log(LogType.Debug, "yep");
                SlimDX.DXGI.Format fmt = SlimDX.DXGI.Format.R32G32B32A32_Float;
                int pixelSize          = 16;

                int stride = 128;
                FLogger.Log(LogType.Debug, "4");
                FLogger.Log(LogType.Debug, data.Length.ToString());
                byteSpread.SliceCount = stride * pixelSize * this.inHeight[0];
                FLogger.Log(LogType.Debug, "5");

                data.Read(byteSpread.Stream.Buffer, 0, stride * this.inHeight[0]);
                FLogger.Log(LogType.Debug, "6");
                data.Position = 0;

                using (SlimDX.DataStream dataStream = new DataStream(byteSpread.Stream.Buffer,
                                                                     true, true))
                {
                    DX11Texture2D texture = DX11Texture2D.CreateImmutable(context,
                                                                          this.inWidth[0], this.inHeight[0], fmt, stride, dataStream);

                    this.marginalTexture[0][context] = texture;
                }
            }

            this.invalidate = false;
        }
        public DX11SliceDepthStencil(DX11RenderContext context, DX11Texture2D texture, int sliceindex, Format depthformat)
        {
            this.context = context;
            this.parent = texture;

            DepthStencilViewDescription dsvd = new DepthStencilViewDescription()
            {
                ArraySize = 1,
                Dimension = DepthStencilViewDimension.Texture2DArray,
                Format = depthformat,
                MipSlice = 0,
                FirstArraySlice = sliceindex
            };

            this.DSV = new DepthStencilView(context.Device, this.parent.Resource, dsvd);
        }
        public void Present()
        {
            DX11RenderContext context = this.RenderContext;


            //Rendering is finished, so should be ok to grab texture now
            if (this.FTextureInput.IsConnected && this.FTextureInput.SliceCount > 0 && this.FTextureInput[0].Contains(context))
            {
                DX11Texture2D texture = this.FTextureInput[0][context];

                if (texture != null)
                {
                    if (texture is DX11DepthStencil)
                    {
                        this.logger.Log(LogType.Warning, "FrameDelay for depth texture is not supported");
                        return;
                    }

                    if (this.lasttexture != null)
                    {
                        if (this.lasttexture.Description != texture.Description)
                        {
                            this.DisposeTexture();
                        }
                    }

                    if (this.lasttexture == null)
                    {
                        this.lasttexture = DX11Texture2D.FromDescription(context, texture.Description);
                    }

                    context.CurrentDeviceContext.CopyResource(texture.Resource, this.lasttexture.Resource);

                    if (this.FInFlush[0])
                    {
                        context.CurrentDeviceContext.Flush();
                    }
                }
            }
            else
            {
                this.DisposeTexture();
            }
        }
Exemple #24
0
        public unsafe void Update(DX11RenderContext context)
        {
            if (this.FTextureOutput.SliceCount == 0)
            {
                return;
            }

            if (this.FInvalidate)
            {
                int index = 0;
                var data  = this.FInData[index];

                if (this.FTextureOutput[0].Contains(context))
                {
                    this.FTextureOutput[0].Dispose(context);
                }

                if (this.FInData.IsConnected && data != null)
                {
                    int width  = this.FInWidth[index];
                    int height = this.FInHeight[index];
                    var fmt    = this.FInFormat[index];

                    int pixelSize = DeviceFormatHelper.GetPixelSizeInBytes(fmt);

                    int stride = this.FInStride[index];
                    stride = stride <= 0 ? pixelSize * width : stride;

                    //Normally spread implementation, afaik , doesn't downsize the buffer
                    byteSpread.SliceCount = stride * pixelSize;

                    data.Position = this.FInDataLocation[0];
                    data.Read(byteSpread.Stream.Buffer, 0, stride * height);
                    data.Position = 0;

                    using (SlimDX.DataStream dataStream = new DataStream(byteSpread.Stream.Buffer, true, true))
                    {
                        DX11Texture2D texture = DX11Texture2D.CreateImmutable(context, width, height, fmt, stride, dataStream);
                        this.FTextureOutput[0][context] = texture;
                    }
                }
                this.FInvalidate = false;
            }
        }
Exemple #25
0
            public void SetPosition(DX11RenderContext ctx, int frame)
            {
                int frameindex = frame - this.CurrentFrame;

                frameindex = frameindex < 0 ? 0 : frameindex;
                frameindex = frameindex > Data.FileCount - 1 ? Data.FileCount - 1 : frameindex;

                if (frameindex != CurrentFrame)
                {
                    if (this.Texture == null)
                    {
                        this.Texture.Dispose();
                    }

                    ImageLoadInformation info = ImageLoadInformation.FromDefaults();
                    info.MipLevels = 1;
                    this.Texture   = DX11Texture2D.FromFile(ctx, Data.FilePath[frameindex], info);
                    CurrentFrame   = frameindex;
                }
            }
 public void Update(DX11RenderContext context)
 {
     if (this.FInvalidate)
     {
         for (int i = 0; i < FTextureOutput.SliceCount; i++)
         {
             try
             {
                 int           p        = unchecked ((int)this.FPointer[i]);
                 IntPtr        share    = new IntPtr(p);
                 DX11Texture2D resource = DX11Texture2D.FromSharedHandle(context, share);
                 this.FTextureOutput[i][context] = resource;
                 this.FValid[i] = true;
             }
             catch (Exception)
             {
                 this.FValid[i] = false;
             }
         }
         this.FInvalidate = false;
     }
 }
Exemple #27
0
        protected override void PostRender()
        {
            if (this.genmipmap && this.sampledesc.Count == 1)
            {
                VDX11.Device.ImmediateContext.GenerateMips(target.SRV);
            }


            if (this.FInSaveLastBuffer[0])
            {
                if (this.lastbuffer != null)
                {
                    if (this.lastbuffer.Resource.Description != target.Resource.Description)
                    {
                        this.lastbuffer.Dispose();
                        this.lastbuffer = null;
                    }
                }

                if (this.lastbuffer == null)
                {
                    Texture2D          t   = new Texture2D(VDX11.Device, target.Resource.Description);
                    ShaderResourceView srv = new ShaderResourceView(VDX11.Device, t);
                    this.lastbuffer = DX11Texture2D.FromTextureAndSRV(t, srv);
                }

                VDX11.Device.ImmediateContext.CopyResource(target.Resource, this.lastbuffer.Resource);
            }
            else
            {
                if (this.lastbuffer != null)
                {
                    this.lastbuffer.Dispose(); this.lastbuffer = null;
                }
            }

            this.FOutBuffers[0].AssignResourceAndSRV(target.Resource, target.SRV);
        }
Exemple #28
0
        public void UpdateDX11Resources(DX11RenderContext context)
        {
            var invalidate = !_newAccFrameReady.ContainsKey(context) || !DX11Texture.Contains(context);

            if (invalidate)
            {
                UpdateSize();
            }
            if (!invalidate)
            {
                invalidate = _newAccFrameReady[context];
            }

            if (_newAccFramePtr != IntPtr.Zero && invalidate)
            {
                if (DX11Texture.Contains(context))
                {
                    DX11Texture.Dispose(context);
                }
                try
                {
                    DX11Texture[context] = DX11Texture2D.FromSharedHandle(context, _newAccFramePtr);
                    IsTextureValid       = true;
                }
                catch
                {
                    IsTextureValid = false;
                }
            }

            if (invalidate)
            {
                _newAccFrameReady.UpdateGeneric(context, false);
                //Browser.Host.SendExternalBeginFrame();
            }
        }
Exemple #29
0
        public void Update(DX11RenderContext context)
        {
            Device        device = context.Device;
            DeviceContext ctx    = context.CurrentDeviceContext;

            if (!this.deviceshaderdata.Contains(context))
            {
                this.deviceshaderdata[context] = new DX11ShaderData(context, this.FShader);
            }
            if (!this.shaderVariableCache.Contains(context))
            {
                this.shaderVariableCache[context] = new DX11ShaderVariableCache(context, this.deviceshaderdata[context].ShaderInstance, this.varmanager);
            }
            if (!this.imageShaderInfo.Contains(context))
            {
                this.imageShaderInfo[context] = new ImageShaderInfo(this.deviceshaderdata[context].ShaderInstance);
            }

            DX11ShaderData  shaderdata = this.deviceshaderdata[context];
            ImageShaderInfo shaderInfo = this.imageShaderInfo[context];

            context.RenderStateStack.Push(new DX11RenderState());

            this.OnBeginQuery(context);


            //Clear shader stages
            shaderdata.ResetShaderStages(ctx);
            context.Primitives.ApplyFullTriVS();

            for (int i = 0; i < this.previousFrameResults.SliceCount; i++)
            {
                if (this.FInEnabled[i] || this.FInPreserveOnDisable[i] == false)
                {
                    this.previousFrameResults[i]?.UnLock();
                    this.previousFrameResults[i] = null;
                }
            }


            int wi, he;
            DX11ResourcePoolEntry <DX11RenderTarget2D> preservedtarget = null;

            renderSettings.CustomSemantics.Clear();
            renderSettings.ResourceSemantics.Clear();

            if (this.FInSemantics.IsConnected)
            {
                renderSettings.CustomSemantics.AddRange(this.FInSemantics.ToArray());
            }
            if (this.FInResSemantics.IsConnected)
            {
                renderSettings.ResourceSemantics.AddRange(this.FInResSemantics.ToArray());
            }

            for (int textureIndex = 0; textureIndex < this.spmax; textureIndex++)
            {
                int passcounter = 0;

                if (this.FInEnabled[textureIndex])
                {
                    List <DX11ResourcePoolEntry <DX11RenderTarget2D> > locktargets = new List <DX11ResourcePoolEntry <DX11RenderTarget2D> >();

                    #region Manage size
                    DX11Texture2D initial;
                    if (this.FIn.IsConnected)
                    {
                        if (this.FInUseDefaultSize[0])
                        {
                            if (this.FIn[textureIndex].Contains(context) && this.FIn[textureIndex][context] != null)
                            {
                                initial = this.FIn[textureIndex][context];
                            }
                            else
                            {
                                initial = context.DefaultTextures.WhiteTexture;
                            }
                            wi = (int)this.FInSize[0].X;
                            he = (int)this.FInSize[0].Y;
                        }
                        else
                        {
                            initial = this.FIn[textureIndex].Contains(context) ? this.FIn[textureIndex][context] : null;
                            if (initial != null)
                            {
                                wi = initial.Width;
                                he = initial.Height;
                            }
                            else
                            {
                                initial = context.DefaultTextures.WhiteTexture;
                                wi      = (int)this.FInSize[textureIndex].X;
                                he      = (int)this.FInSize[textureIndex].Y;
                            }
                        }
                    }
                    else
                    {
                        initial = context.DefaultTextures.WhiteTexture;
                        wi      = (int)this.FInSize[textureIndex].X;
                        he      = (int)this.FInSize[textureIndex].Y;
                    }
                    #endregion

                    renderSettings.RenderWidth  = wi;
                    renderSettings.RenderHeight = he;


                    this.varmanager.SetGlobalSettings(shaderdata.ShaderInstance, renderSettings);
                    var variableCache = this.shaderVariableCache[context];
                    variableCache.ApplyGlobals(renderSettings);


                    DX11ResourcePoolEntry <DX11RenderTarget2D> lasttmp = null;

                    List <DX11Texture2D> rtlist = new List <DX11Texture2D>();

                    //Go trough all passes
                    int tid = this.FInTechnique[textureIndex].Index;
                    ImageShaderTechniqueInfo techniqueInfo = shaderInfo.GetTechniqueInfo(tid);

                    //Now we need to add optional extra pass in case we want mip chain (only in case it's not needed, if texture has mips we just ignore)
                    if (techniqueInfo.WantMips)
                    {
                        //Single level and bigger than 1 should get a mip generation pass
                        if (initial.Width > 1 && initial.Height > 1 && initial.Resource.Description.MipLevels == 1)
                        {
                            //Texture might now be an allowed render target format, so we at least need to check that, and default to rgba8 unorm
                            //also check for auto mip map gen
                            var mipTargetFmt = initial.Format;
                            if (!context.IsSupported(FormatSupport.RenderTarget, mipTargetFmt) ||
                                !context.IsSupported(FormatSupport.MipMapAutoGeneration, mipTargetFmt) ||
                                !context.IsSupported(FormatSupport.UnorderedAccessView, mipTargetFmt))
                            {
                                mipTargetFmt = Format.R8G8B8A8_UNorm;
                            }



                            DX11ResourcePoolEntry <DX11RenderTarget2D> mipTarget = context.ResourcePool.LockRenderTarget(initial.Width, initial.Height, mipTargetFmt, new SampleDescription(1, 0), true, 0);
                            locktargets.Add(mipTarget);

                            context.RenderTargetStack.Push(mipTarget.Element);

                            context.BasicEffects.PointSamplerPixelPass.Apply(initial.SRV);

                            context.CurrentDeviceContext.Draw(3, 0);

                            context.RenderTargetStack.Pop();

                            context.CurrentDeviceContext.GenerateMips(mipTarget.Element.SRV);

                            //Replace initial by our new texture
                            initial = mipTarget.Element;
                        }
                    }

                    //Bind Initial (once only is ok) and mark for previous usage too
                    DX11Texture2D lastrt = initial;
                    shaderInfo.ApplyInitial(initial.SRV);

                    for (int passIndex = 0; passIndex < techniqueInfo.PassCount; passIndex++)
                    {
                        ImageShaderPassInfo passInfo = techniqueInfo.GetPassInfo(passIndex);
                        bool isLastPass = passIndex == techniqueInfo.PassCount - 1;


                        Format fmt = initial.Format;
                        if (passInfo.CustomFormat)
                        {
                            fmt = passInfo.Format;
                        }
                        bool mips = passInfo.Mips || (isLastPass && FInMipLastPass[textureIndex]);

                        int w, h;
                        if (passIndex == 0)
                        {
                            h = he;
                            w = wi;
                        }
                        else
                        {
                            h = passInfo.Reference == ImageShaderPassInfo.eImageScaleReference.Initial ? he : lastrt.Height;
                            w = passInfo.Reference == ImageShaderPassInfo.eImageScaleReference.Initial ? wi : lastrt.Width;
                        }

                        if (passInfo.DoScale)
                        {
                            if (passInfo.Absolute)
                            {
                                w = Convert.ToInt32(passInfo.ScaleVector.X);
                                h = Convert.ToInt32(passInfo.ScaleVector.Y);
                            }
                            else
                            {
                                w = Convert.ToInt32((float)w * passInfo.ScaleVector.X);
                                h = Convert.ToInt32((float)h * passInfo.ScaleVector.Y);
                            }

                            w = Math.Max(w, 1);
                            h = Math.Max(h, 1);
                        }

                        //Check format support for render target, and default to rgb8 if not
                        if (!context.IsSupported(FormatSupport.RenderTarget, fmt))
                        {
                            fmt = Format.R8G8B8A8_UNorm;
                        }

                        //To avoid uav issue
                        if (fmt == Format.B8G8R8A8_UNorm)
                        {
                            fmt = Format.R8G8B8A8_UNorm;
                        }

                        DX11ResourcePoolEntry <DX11RenderTarget2D> elem;
                        if (preservedtarget != null)
                        {
                            elem = preservedtarget;
                        }
                        else
                        {
                            elem = context.ResourcePool.LockRenderTarget(w, h, fmt, new SampleDescription(1, 0), mips, 0);
                            locktargets.Add(elem);
                        }
                        DX11RenderTarget2D rt = elem.Element;


                        if (this.FDepthIn.IsConnected && passInfo.UseDepth)
                        {
                            context.RenderTargetStack.Push(this.FDepthIn[0][context], true, elem.Element);
                        }
                        else
                        {
                            context.RenderTargetStack.Push(elem.Element);
                        }

                        if (passInfo.Clear)
                        {
                            elem.Element.Clear(new Color4(0, 0, 0, 0));
                        }

                        #region Check for depth/blend preset
                        bool validdepth = false;
                        bool validblend = false;

                        DepthStencilStateDescription ds = new DepthStencilStateDescription();
                        BlendStateDescription        bs = new BlendStateDescription();

                        if (passInfo.DepthPreset != "")
                        {
                            try
                            {
                                ds         = DX11DepthStencilStates.GetState(passInfo.DepthPreset);
                                validdepth = true;
                            }
                            catch
                            {
                            }
                        }

                        if (passInfo.BlendPreset != "")
                        {
                            try
                            {
                                bs         = DX11BlendStates.GetState(passInfo.BlendPreset);
                                validblend = true;
                            }
                            catch
                            {
                            }
                        }
                        #endregion

                        if (validdepth || validblend)
                        {
                            DX11RenderState state = new DX11RenderState();
                            if (validdepth)
                            {
                                state.DepthStencil = ds;
                            }
                            if (validblend)
                            {
                                state.Blend = bs;
                            }
                            context.RenderStateStack.Push(state);
                        }

                        renderSettings.RenderWidth  = w;
                        renderSettings.RenderHeight = h;
                        renderSettings.BackBuffer   = elem.Element;

                        //Apply settings (we do both here, as texture size semantic might ahve
                        variableCache.ApplyGlobals(renderSettings);
                        variableCache.ApplySlice(objectSettings, textureIndex);
                        //Bind last render target

                        shaderInfo.ApplyPrevious(lastrt.SRV);

                        this.BindPassIndexSemantic(shaderdata.ShaderInstance.Effect, passIndex);

                        if (this.FDepthIn.IsConnected)
                        {
                            if (this.FDepthIn[0].Contains(context))
                            {
                                shaderInfo.ApplyDepth(this.FDepthIn[0][context].SRV);
                            }
                        }

                        for (int list = 0; list < this.FinPrePostActions.SliceCount; list++)
                        {
                            if (this.FinPrePostActions[list] != null)
                            {
                                this.FinPrePostActions[list].OnBeginPass(context, passIndex);
                            }
                        }

                        //Apply pass and draw quad
                        passInfo.Apply(ctx);

                        if (passInfo.ComputeData.Enabled)
                        {
                            passInfo.ComputeData.Dispatch(context, w, h);
                            context.CleanUpCS();
                        }
                        else
                        {
                            ctx.ComputeShader.Set(null);
                            context.Primitives.FullScreenTriangle.Draw();
                            ctx.OutputMerger.SetTargets(this.nullrtvs);
                        }

                        //Generate mips if applicable
                        if (mips)
                        {
                            ctx.GenerateMips(rt.SRV);
                        }

                        if (!passInfo.KeepTarget)
                        {
                            rtlist.Add(rt);
                            lastrt          = rt;
                            lasttmp         = elem;
                            preservedtarget = null;
                            passcounter++;
                        }
                        else
                        {
                            preservedtarget = elem;
                        }


                        context.RenderTargetStack.Pop();

                        //Apply pass result semantic if applicable (after pop)
                        shaderInfo.ApplyPassResult(lasttmp.Element.SRV, passIndex);

                        if (validblend || validdepth)
                        {
                            context.RenderStateStack.Pop();
                        }

                        if (passInfo.HasState)
                        {
                            context.RenderStateStack.Apply();
                        }

                        for (int list = 0; list < this.FinPrePostActions.SliceCount; list++)
                        {
                            if (this.FinPrePostActions[list] != null)
                            {
                                this.FinPrePostActions[list].OnEndPass(context, passIndex);
                            }
                        }
                    }

                    //Set last render target
                    this.FOut[textureIndex][context] = lastrt;

                    //Unlock all resources
                    foreach (DX11ResourcePoolEntry <DX11RenderTarget2D> lt in locktargets)
                    {
                        lt.UnLock();
                    }

                    //Keep lock on last rt, since don't want it overidden
                    lasttmp.Lock();

                    this.previousFrameResults[textureIndex] = lasttmp;
                }
                else
                {
                    if (this.FInPreserveOnDisable[textureIndex])
                    {
                        //We kept it locked on top
                        this.FOut[textureIndex][context] = this.previousFrameResults[textureIndex] != null ? this.previousFrameResults[textureIndex].Element : null;
                    }
                    else
                    {
                        this.FOut[textureIndex][context] = this.FIn[textureIndex][context];
                    }
                }
            }

            context.RenderStateStack.Pop();

            this.OnEndQuery(context);
        }
 public void CopyFrom(DX11Texture2D tex)
 {
     this.context.CurrentDeviceContext.CopyResource(tex.Resource, this.Resource);
 }
Exemple #31
0
        public void Evaluate(int SpreadMax)
        {
            if (this.FInPath.IsChanged)
            {
                this.directories.Clear();
                string path = this.FInPath[0];

                try
                {
                    var subdirs = Directory.GetDirectories(path).ToList();

                    subdirs.ForEach(sd => this.directories.Add(new DirectoryData(sd)));
                    this.outdircount.SliceCount = subdirs.Count;
                    for (int i = 0; i < this.directories.Count; i++)
                    {
                        this.outdircount[i] = this.directories[i].FileCount;
                    }
                }
                catch
                {
                    this.directories.Clear();
                    this.outdircount.SliceCount = 0;
                }
            }

            if (this.outdircount.SliceCount == 0)
            {
                return;
            }

            if (this.FSpawn[0] && this.FSpawnIndex.SliceCount > 0)
            {
                for (int i = 0; i < this.FSpawnIndex.SliceCount; i++)
                {
                    int idx = this.FSpawnIndex[i];

                    if (this.spawners.Any(s => s.Index == idx))
                    {
                        //Emit animation
                        Spawner sp = new Spawner();
                        sp.Index        = idx;
                        sp.InitialFrame = this.FFrameIndex[0];
                        sp.CurrentFrame = 0;
                        sp.Data         = this.directories[idx];
                        sp.Texture      = DX11Texture2D.FromFile(ctx, sp.Data.FilePath[0]);

                        this.spawners.Add(sp);
                    }
                }
            }

            spawners.Where(s => s.CurrentFrame >= s.Data.FileCount).ToList().ForEach(s => { s.Dispose(); this.spawners.Remove(s); });

            this.outidx.SliceCount = spawners.Count;
            this.outpos.SliceCount = spawners.Count;
            this.outtex.SliceCount = spawners.Count;

            for (int i = 0; i < this.spawners.Count; i++)
            {
                Spawner s = this.spawners[i];
                this.outidx[i] = s.Index;
                this.outpos[i] = (double)s.CurrentFrame / (double)s.Data.FileCount;
                this.outtex[i] = new DX11Resource <DX11Texture2D>();
            }
        }
 private void DisposeTexture()
 {
     if (this.lasttexture != null) { this.lasttexture.Dispose(); this.lasttexture = null; }
 }
Exemple #33
0
            void TextureToBuffer(Texture2D src, ref IntPtr buffer)
            {
                try
                {
                    // create texture for get resource from GPU to CPU
                    Texture2D dst = DX11Texture2D.CreateStaging(AssignedContext, src);

                    // copy resource from src
                    AssignedContext.CurrentDeviceContext.CopyResource(src, dst);

                    // get databox to access byte buffer
                    // MapFlags.DoNotWait will throw exception when GPU not ready
                    DataBox db = AssignedContext.CurrentDeviceContext.MapSubresource(dst, 0, MapMode.Read, MapFlags.None);

                    // create buffer
                    if (dataStreamLength != db.Data.Length)
                    {
                        dataStreamLength = db.Data.Length;

                        // avoid size difference (is this correct way?)
                        if (dataStreamLength != bufferSize)
                        {
                            dataStreamLength = bufferSize;
                        }

                        srcBuffer = new byte[dataStreamLength];
                    }

                    // read data
                    db.Data.Read(srcBuffer, 0, (int)dataStreamLength);

                    // convert color if need
                    // ...

                    /*
                     * if (FInRGBAtoBGRA[0])
                     * {
                     *  ConvertBuffer();
                     *
                     *  Marshal.Copy(convertBuffer, 0, bufferPtr, (int)dataStreamLength);
                     * }
                     * else
                     * {
                     *  //await db.Data.ReadAsync(srcBuffer, 0, (int)dataStreamLength);
                     *  Marshal.Copy(srcBuffer, 0, bufferPtr, (int)dataStreamLength);
                     * }
                     */

                    //FLogger.Log(LogType.Message, "TextureToBuffer: " + db.RowPitch + "," + db.SlicePitch + "," + db.Data.Length);

                    // byte array to IntPtr
                    Marshal.Copy(srcBuffer, 0, buffer, (int)dataStreamLength);

                    // unmap resource
                    AssignedContext.CurrentDeviceContext.UnmapSubresource(dst, 0);

                    db = null;

                    // this will slow down but needed
                    dst.Dispose();
                    dst = null;
                }
                catch (Exception e)
                {
                    FLogger.Log(LogType.Error, e.Message);

                    return;
                }
            }
Exemple #34
0
        public DX11DepthStencil(DX11RenderContext context, int w, int h, SampleDescription sd, Format format)
        {
            this.context = context;
            var depthBufferDesc = new Texture2DDescription
            {
                ArraySize = 1,
                BindFlags = BindFlags.DepthStencil | BindFlags.ShaderResource,
                CpuAccessFlags = CpuAccessFlags.None,
                Format = DepthFormatsHelper.GetGenericTextureFormat(format),
                Height = h,
                Width = w,
                MipLevels = 1,
                OptionFlags = ResourceOptionFlags.None,
                SampleDescription = sd,
                Usage = ResourceUsage.Default
            };

            this.Resource = new Texture2D(context.Device, depthBufferDesc);

            ShaderResourceViewDescription srvd = new ShaderResourceViewDescription()
            {
                ArraySize = 1,
                Format = DepthFormatsHelper.GetSRVFormat(format),
                Dimension = sd.Count == 1 ? ShaderResourceViewDimension.Texture2D : ShaderResourceViewDimension.Texture2DMultisampled,
                MipLevels = 1,
                MostDetailedMip = 0
            };

            this.SRV = new ShaderResourceView(context.Device, this.Resource, srvd);


            if (format == Format.D24_UNorm_S8_UInt)
            {
                ShaderResourceViewDescription stencild = new ShaderResourceViewDescription()
                {
                    ArraySize = 1,
                    Format = SlimDX.DXGI.Format.X24_Typeless_G8_UInt,
                    Dimension = sd.Count == 1 ? ShaderResourceViewDimension.Texture2D : ShaderResourceViewDimension.Texture2DMultisampled,
                    MipLevels = 1,
                    MostDetailedMip = 0
                };

                this.stencilview = new ShaderResourceView(this.context.Device, this.Resource, stencild);

                this.Stencil = DX11Texture2D.FromTextureAndSRV(this.context, this.Resource, this.stencilview);

            }
            else
            {
                //Just pass depth instead
                this.Stencil = DX11Texture2D.FromTextureAndSRV(this.context, this.Resource, this.SRV);
            }

            DepthStencilViewDescription dsvd = new DepthStencilViewDescription()
            {
                Format = DepthFormatsHelper.GetDepthFormat(format),
                Dimension = sd.Count == 1 ? DepthStencilViewDimension.Texture2D : DepthStencilViewDimension.Texture2DMultisampled,
                MipSlice = 0
            };

            this.DSV = new DepthStencilView(context.Device, this.Resource, dsvd);



            //Read only dsv only supported in dx11 minimum
            if (context.IsFeatureLevel11)
            {
                dsvd.Flags = DepthStencilViewFlags.ReadOnlyDepth;
                if (format == Format.D24_UNorm_S8_UInt) { dsvd.Flags |= DepthStencilViewFlags.ReadOnlyStencil; }

                this.ReadOnlyDSV = new DepthStencilView(context.Device, this.Resource, dsvd);
            }




            this.desc = depthBufferDesc;
            this.isowner = true;
        }
Exemple #35
0
        public void Process(DX11Resource <DX11Texture2D> input, FeralTic.DX11.DX11RenderContext context)
        {
            DX11Texture2D t      = input[context];
            var           height = t.Height;
            var           width  = t.Width;

            var imageLink          = Output;
            var imageAttributes    = imageLink.ImageAttributes;
            var desiredImageFormat = ToOpenCVFormat(t.Format);

            if (desiredImageFormat == TColorFormat.UnInitialised)
            {
                throw (new Exception("No suitible image type available for this texture type " + t.Format.ToString()));
            }


            //--
            //check attributes and reinitialise the image and offscreen buffer if we haven't got the right description ready
            //
            if (imageAttributes == null || FOffscreenBuffer == null || !imageAttributes.Initialised || FOffscreenBuffer.Description.Format != t.Description.Format || imageAttributes.Width != t.Width || imageAttributes.Height != t.Height || imageAttributes.ColorFormat != desiredImageFormat)
            {
                if (FOffscreenBuffer != null)
                {
                    FOffscreenBuffer.Dispose();
                }

                var description = new Texture2DDescription()
                {
                    Width             = width,
                    Height            = height,
                    Format            = t.Format,
                    MipLevels         = 1,
                    Usage             = ResourceUsage.Staging,
                    BindFlags         = BindFlags.None,
                    CpuAccessFlags    = CpuAccessFlags.Read,
                    SampleDescription = new SampleDescription(1, 0),
                    ArraySize         = 1
                };

                FOffscreenBuffer = new Texture2D(context.Device, description);

                imageLink.Initialise(new CVImageAttributes(desiredImageFormat, t.Width, t.Height));
            }
            //
            //--


            //--
            //copy the texture to offscreen buffer
            //
            context.CurrentDeviceContext.CopyResource(t.Resource, FOffscreenBuffer);
            //
            //--


            //--
            //copy the data out of the offscreen buffer
            //
            var surface     = FOffscreenBuffer.AsSurface();
            var bytesPerRow = imageAttributes.Stride;

            var data = MapForRead(context.CurrentDeviceContext);

            lock (imageLink.BackLock)
            {
                var image = imageLink.BackImage;
                try
                {
                    var source = data.Data.DataPointer;

                    image.SetPixels(source);

                    var destination = image.Data;

                    for (int row = 0; row < t.Height; row++)
                    {
                        CopyMemory(destination, source, bytesPerRow);

                        source      += data.RowPitch;
                        destination += bytesPerRow;
                    }
                }
                finally
                {
                    UnMap(context.CurrentDeviceContext);
                }
            }
            //
            //--

            imageLink.Swap();
        }
Exemple #36
0
        public void Update(IPluginIO pin, DX11RenderContext context)
        {
            Device        device = context.Device;
            DeviceContext ctx    = context.CurrentDeviceContext;

            if (!this.deviceshaderdata.ContainsKey(context))
            {
                this.deviceshaderdata.Add(context, new DX11ShaderData(context));
                this.deviceshaderdata[context].SetEffect(this.FShader);
            }

            DX11ShaderData shaderdata = this.deviceshaderdata[context];

            if (this.shaderupdated)
            {
                shaderdata.SetEffect(this.FShader);
                this.shaderupdated = false;
            }

            context.RenderStateStack.Push(new DX11RenderState());

            this.OnBeginQuery(context);


            //Clear shader stages
            shaderdata.ResetShaderStages(ctx);
            context.Primitives.ApplyFullTriVS();

            foreach (DX11ResourcePoolEntry <DX11RenderTarget2D> rt in this.lastframetargets)
            {
                rt.UnLock();
            }
            this.lastframetargets.Clear();

            DX11ObjectRenderSettings or = new DX11ObjectRenderSettings();

            int  wi, he;
            bool preserve = false;
            DX11ResourcePoolEntry <DX11RenderTarget2D> preservedtarget = null;

            for (int i = 0; i < this.spmax; i++)
            {
                int passcounter = 0;

                if (this.FInEnabled[i])
                {
                    List <DX11ResourcePoolEntry <DX11RenderTarget2D> > locktargets = new List <DX11ResourcePoolEntry <DX11RenderTarget2D> >();


                    #region Manage size
                    DX11Texture2D initial;
                    if (this.FIn.PluginIO.IsConnected)
                    {
                        if (this.FInUseDefaultSize[0])
                        {
                            initial = context.DefaultTextures.WhiteTexture;
                            wi      = (int)this.FInSize[0].X;
                            he      = (int)this.FInSize[0].Y;
                        }
                        else
                        {
                            initial = this.FIn[i][context];
                            if (initial != null)
                            {
                                wi = initial.Width;
                                he = initial.Height;
                            }
                            else
                            {
                                initial = context.DefaultTextures.WhiteTexture;
                                wi      = (int)this.FInSize[0].X;
                                he      = (int)this.FInSize[0].Y;
                            }
                        }
                    }
                    else
                    {
                        initial = context.DefaultTextures.WhiteTexture;
                        wi      = (int)this.FInSize[0].X;
                        he      = (int)this.FInSize[0].Y;
                    }
                    #endregion

                    DX11RenderSettings r = new DX11RenderSettings();
                    r.RenderWidth  = wi;
                    r.RenderHeight = he;
                    if (this.FInSemantics.PluginIO.IsConnected)
                    {
                        r.CustomSemantics.AddRange(this.FInSemantics.ToArray());
                    }
                    if (this.FInResSemantics.PluginIO.IsConnected)
                    {
                        r.ResourceSemantics.AddRange(this.FInResSemantics.ToArray());
                    }

                    this.varmanager.SetGlobalSettings(shaderdata.ShaderInstance, r);

                    this.varmanager.ApplyGlobal(shaderdata.ShaderInstance);

                    DX11Texture2D lastrt = initial;
                    DX11ResourcePoolEntry <DX11RenderTarget2D> lasttmp = null;

                    List <DX11Texture2D> rtlist = new List <DX11Texture2D>();

                    //Bind Initial (once only is ok)
                    this.BindTextureSemantic(shaderdata.ShaderInstance.Effect, "INITIAL", initial);

                    //Go trough all passes
                    EffectTechnique tech = shaderdata.ShaderInstance.Effect.GetTechniqueByIndex(tid);

                    for (int j = 0; j < tech.Description.PassCount; j++)
                    {
                        ImageShaderPass pi   = this.varmanager.passes[j];
                        EffectPass      pass = tech.GetPassByIndex(j);

                        for (int kiter = 0; kiter < pi.IterationCount; kiter++)
                        {
                            if (passcounter > 0)
                            {
                                for (int pid = 0; pid < passcounter; pid++)
                                {
                                    string pname = "PASSRESULT" + pid;
                                    this.BindTextureSemantic(shaderdata.ShaderInstance.Effect, pname, rtlist[pid]);
                                }
                            }

                            Format fmt = initial.Format;
                            if (pi.CustomFormat)
                            {
                                fmt = pi.Format;
                            }
                            bool mips = pi.Mips;

                            int w, h;
                            if (j == 0)
                            {
                                h = he;
                                w = wi;
                            }
                            else
                            {
                                h = pi.Reference == ImageShaderPass.eImageScaleReference.Initial ? he : lastrt.Height;
                                w = pi.Reference == ImageShaderPass.eImageScaleReference.Initial ? wi : lastrt.Width;
                            }

                            if (pi.DoScale)
                            {
                                if (pi.Absolute)
                                {
                                    w = Convert.ToInt32(pi.ScaleVector.X);
                                    h = Convert.ToInt32(pi.ScaleVector.Y);
                                }
                                else
                                {
                                    w = Convert.ToInt32((float)w * pi.ScaleVector.X);
                                    h = Convert.ToInt32((float)h * pi.ScaleVector.Y);
                                }

                                w = Math.Max(w, 1);
                                h = Math.Max(h, 1);
                            }

                            //Check format support for render target, and default to rgb8 if not
                            if (!context.IsSupported(FormatSupport.RenderTarget, fmt))
                            {
                                fmt = Format.R8G8B8A8_UNorm;
                            }

                            //Since device is not capable of telling us BGR not supported
                            if (fmt == Format.B8G8R8A8_UNorm)
                            {
                                fmt = Format.R8G8B8A8_UNorm;
                            }

                            DX11ResourcePoolEntry <DX11RenderTarget2D> elem;
                            if (preservedtarget != null)
                            {
                                elem = preservedtarget;
                            }
                            else
                            {
                                elem = context.ResourcePool.LockRenderTarget(w, h, fmt, new SampleDescription(1, 0), mips, 0);
                                locktargets.Add(elem);
                            }
                            DX11RenderTarget2D rt = elem.Element;


                            if (this.FDepthIn.PluginIO.IsConnected && pi.UseDepth)
                            {
                                context.RenderTargetStack.Push(this.FDepthIn[0][context], true, elem.Element);
                            }
                            else
                            {
                                context.RenderTargetStack.Push(elem.Element);
                            }

                            if (pi.Clear)
                            {
                                elem.Element.Clear(new Color4(0, 0, 0, 0));
                            }

                            #region Check for depth/blend preset
                            bool validdepth = false;
                            bool validblend = false;

                            DepthStencilStateDescription ds = new DepthStencilStateDescription();
                            BlendStateDescription        bs = new BlendStateDescription();

                            if (pi.DepthPreset != "")
                            {
                                try
                                {
                                    ds         = DX11DepthStencilStates.Instance.GetState(pi.DepthPreset);
                                    validdepth = true;
                                }
                                catch
                                {
                                }
                            }

                            if (pi.BlendPreset != "")
                            {
                                try
                                {
                                    bs         = DX11BlendStates.Instance.GetState(pi.BlendPreset);
                                    validblend = true;
                                }
                                catch
                                {
                                }
                            }
                            #endregion

                            if (validdepth || validblend)
                            {
                                DX11RenderState state = new DX11RenderState();
                                if (validdepth)
                                {
                                    state.DepthStencil = ds;
                                }
                                if (validblend)
                                {
                                    state.Blend = bs;
                                }
                                context.RenderStateStack.Push(state);
                            }

                            r.RenderWidth  = w;
                            r.RenderHeight = h;
                            r.BackBuffer   = elem.Element;
                            this.varmanager.ApplyGlobal(shaderdata.ShaderInstance);

                            //Apply settings (note that textures swap is handled later)
                            this.varmanager.ApplyPerObject(context, shaderdata.ShaderInstance, or, i);

                            //Bind last render target
                            this.BindTextureSemantic(shaderdata.ShaderInstance.Effect, "PREVIOUS", lastrt);

                            this.BindPassIndexSemantic(shaderdata.ShaderInstance.Effect, j);
                            this.BindPassIterIndexSemantic(shaderdata.ShaderInstance.Effect, kiter);

                            if (this.FDepthIn.PluginIO.IsConnected)
                            {
                                if (this.FDepthIn[0].Contains(context))
                                {
                                    this.BindTextureSemantic(shaderdata.ShaderInstance.Effect, "DEPTHTEXTURE", this.FDepthIn[0][context]);
                                }
                            }

                            //Apply pass and draw quad
                            pass.Apply(ctx);

                            if (pi.ComputeData.Enabled)
                            {
                                pi.ComputeData.Dispatch(context, w, h);
                                context.CleanUpCS();
                            }
                            else
                            {
                                ctx.ComputeShader.Set(null);
                                context.Primitives.FullScreenTriangle.Draw();
                                ctx.OutputMerger.SetTargets(this.nullrtvs);
                            }

                            //Generate mips if applicable
                            if (pi.Mips)
                            {
                                ctx.GenerateMips(rt.SRV);
                            }

                            if (!pi.KeepTarget)
                            {
                                preserve = false;
                                rtlist.Add(rt);
                                lastrt          = rt;
                                lasttmp         = elem;
                                preservedtarget = null;
                                passcounter++;
                            }
                            else
                            {
                                preserve        = true;
                                preservedtarget = elem;
                            }


                            context.RenderTargetStack.Pop();

                            if (validblend || validdepth)
                            {
                                context.RenderStateStack.Pop();
                            }

                            if (pi.HasState)
                            {
                                context.RenderStateStack.Apply();
                            }
                        }
                    }

                    //Set last render target
                    this.FOut[i][context] = lastrt;

                    //Unlock all resources
                    foreach (DX11ResourcePoolEntry <DX11RenderTarget2D> lt in locktargets)
                    {
                        lt.UnLock();
                    }

                    //Keep lock on last rt, since don't want it overidden
                    lasttmp.Lock();

                    this.lastframetargets.Add(lasttmp);
                }
                else
                {
                    this.FOut[i][context] = this.FIn[i][context];
                }
            }

            context.RenderStateStack.Pop();

            this.OnEndQuery(context);

            //UnLock previous frame in applicable
            //if (previoustarget != null) { context.ResourcePool.Unlock(previoustarget); }
        }
        private void MainLoop_OnPresent(object sender, EventArgs e)
        {
            //Rendering is finished, so should be ok to grab texture now
            if (this.FTextureInput.PluginIO.IsConnected && this.FTextureInput.SliceCount > 0)
            {

                //Little temp hack, grab context from global, since for now we have one context anyway
                DX11RenderContext context = DX11GlobalDevice.DeviceManager.RenderContexts[0];

                if (this.FTextureInput[0].Contains(context))
                {
                    DX11Texture2D texture = this.FTextureInput[0][context];

                    if (this.lasttexture != null)
                    {
                        if (this.lasttexture.Description != texture.Description) { this.DisposeTexture(); }
                    }

                    if (this.lasttexture == null)
                    {
                        this.lasttexture = DX11Texture2D.FromDescription(context, texture.Description);
                    }

                    context.CurrentDeviceContext.CopyResource(texture.Resource, this.lasttexture.Resource);

                    if (this.FInFlush[0]) { context.CurrentDeviceContext.Flush(); }
                }
                else
                {
                    this.DisposeTexture();
                }
            }
            else
            {
                this.DisposeTexture();
            }
        }
        public bool TryGetFile(DX11RenderContext context, string path, bool domips, bool async, out DX11Texture2D texture)
        {
            lock (m_lock)
            {
                foreach (DX11FileTexturePoolElement element in this.pool)
                {
                    if (element.DoMips == domips && element.FileName == path)
                    {
                        if (element.Status == eDX11SheduleTaskStatus.Completed)
                        {
                            element.IncrementCounter();
                            texture = element.Texture;
                            return(true);
                        }
                        else
                        {
                            element.IncrementCounter();
                            texture = null;
                            return(false);
                        }
                    }
                }
            }


            DX11FileTexturePoolElement elem = new DX11FileTexturePoolElement(context, path, domips, async);

            elem.OnLoadComplete += elem_OnLoadComplete;

            lock (m_lock)
            {
                if (elem.Status != eDX11SheduleTaskStatus.Error)
                {
                    this.pool.Add(elem);
                    if (elem.Status == eDX11SheduleTaskStatus.Completed)
                    {
                        texture = elem.Texture;
                        return(true);
                    }
                    else
                    {
                        texture = null;
                        return(false);
                    }
                }
                else
                {
                    texture = null;
                    return(false);
                }
            }
        }
        public TexInfo GetRenderTarget(DX11RenderContext context)
        {
            TexInfo ti = new TexInfo();

            if (this.currentmode == eRenderFormatMode.Inherit)
            {
                if (this.texinputpin.IOObject.PluginIO.IsConnected)
                {
                    DX11Texture2D t = this.texinputpin.IOObject[0][context];

                    if (t.Resource != null)
                    {
                        ti.w = t.Width;
                        ti.h = t.Height;
                        if (DX11EnumFormatHelper.NullDeviceFormats.GetAllowedFormats(FormatSupport.RenderTarget).Contains(t.Format.ToString()))
                        {
                            ti.format = t.Format;
                        }
                        else
                        {
                            ti.format = DeviceFormatHelper.GetFormat(this.FInFormat.IOObject[0]);
                        }
                    }
                    else
                    {
                        ti.w      = (int)this.FInTextureSize.IOObject[0].x;
                        ti.h      = (int)this.FInTextureSize.IOObject[0].y;
                        ti.format = DeviceFormatHelper.GetFormat(this.FInFormat.IOObject[0]);
                    }
                }
                else
                {
                    ti.w      = (int)this.FInTextureSize.IOObject[0].x;
                    ti.h      = (int)this.FInTextureSize.IOObject[0].y;
                    ti.format = DeviceFormatHelper.GetFormat(this.FInFormat.IOObject[0]);
                }
            }

            if (this.currentmode == eRenderFormatMode.InheritSize)
            {
                if (this.texinputpin.IOObject.PluginIO.IsConnected)
                {
                    DX11Texture2D t = this.texinputpin.IOObject[0][context];

                    if (t.Resource != null)
                    {
                        ti.w = t.Width;
                        ti.h = t.Height;
                    }
                    else
                    {
                        ti.w = (int)this.FInTextureSize.IOObject[0].x;
                        ti.h = (int)this.FInTextureSize.IOObject[0].y;
                    }
                }
                else
                {
                    ti.w = (int)this.FInTextureSize.IOObject[0].x;
                    ti.h = (int)this.FInTextureSize.IOObject[0].y;
                }

                ti.format = DeviceFormatHelper.GetFormat(this.FInFormat.IOObject[0]);
            }

            if (this.currentmode == eRenderFormatMode.Manual)
            {
                ti.w      = (int)this.FInTextureSize.IOObject[0].x;
                ti.h      = (int)this.FInTextureSize.IOObject[0].y;
                ti.format = DeviceFormatHelper.GetFormat(this.FInFormat.IOObject[0]);
            }

            ti.w = Convert.ToInt32((double)ti.w * this.FInTextureScale.IOObject[0].x);
            ti.h = Convert.ToInt32((double)ti.h * this.FInTextureScale.IOObject[0].y);

            return(ti);
        }
Exemple #40
0
 public void Reset(DX11Texture2D texture, int w, int h, int d, SlimDX.DXGI.Format format)
 {
     format = format == SlimDX.DXGI.Format.Unknown ? texture.Format : format;
     this.rtarr.Dispose();
     this.rtarr = new DX11RenderTextureArray(this.context, w, h, d, format, true, 1);
 }
 private void BindTextureSemantic(Effect effect,string semantic, DX11Texture2D resource)
 {
     foreach (EffectResourceVariable erv in this.varmanager.texturecache)
     {
         if (erv.Description.Semantic == semantic)
         {
             /*erv.SetResource(resource.SRV);*/
             effect.GetVariableByName(erv.Description.Name).AsResource().SetResource(resource.SRV);
         }
     }
 }
Exemple #42
0
        unsafe public void Update(IPluginIO pin, DX11RenderContext context)
        {
            FOutLog[0] = _message;
            //DX11RenderContext sharedContext = this.AssignedContext;
            try
            {
                if (FInvalidate == true & this.FTextureIn.PluginIO.IsConnected)
                {
                    var dummyTex = new DX11Resource <DX11Texture2D>();

                    interop      = new D3DAngleInterop();
                    angleSurface = interop.CreateOffscreenSurface(600, 600);
                    //D3DShareHandle =  interop.GetD3DSharedHandleForSurface(angleSurface, 500, 500);
                    // angleSurface = interop.CreateSharedSurfaceFromTexture(v4SharedHandle, 500, 500);

                    IntPtr share = interop.GetD3DSharedHandleForSurface(angleSurface, 600, 600);

                    Texture2D          tex = context.Device.OpenSharedResource <Texture2D>(share);
                    ShaderResourceView srv = new ShaderResourceView(context.Device, tex);

                    DX11Texture2D        resource = DX11Texture2D.FromTextureAndSRV(context, tex, srv);
                    SlimDX.DXGI.Resource angleRes = new SlimDX.DXGI.Resource(tex);


                    interop.EnsureContext();
                    //Texture2D tex;
                    SlimDX.DXGI.Resource sharedRes;
                    IntPtr dxHandle = new IntPtr();
                    IntPtr shared;



                    try
                    {
                        //Texture2DDescription desc = tex.Description;
                        //desc.Height = 256;
                        //desc.Width = 256;

                        Texture2D inTex = this.FTextureIn[0][context].Resource;
                        if (inTex == null)
                        {
                            _message = "thiss isn't real";
                        }
                        Texture2DDescription desc, testDesc;
                        try
                        {
                            testDesc = inTex.Description;
                            desc     = inTex.Description;
                        }
                        catch (Exception e)
                        {
                            testDesc = tex.Description;
                            desc     = tex.Description;
                            _message = e.ToString();
                        }

                        // = inTex.Description;
                        desc.Height = 256;
                        desc.Width  = 256;

                        desc.BindFlags   = BindFlags.ShaderResource | BindFlags.RenderTarget;
                        desc.OptionFlags = ResourceOptionFlags.Shared;
                        desc.MipLevels   = 1;

                        if (desc.MipLevels != testDesc.MipLevels)
                        {
                            _message = "MIPS";
                        }

                        if (desc.ArraySize != testDesc.ArraySize)
                        {
                            _message = "Array";
                        }

                        if (desc.CpuAccessFlags != testDesc.CpuAccessFlags)
                        {
                            _message = "CPU";
                        }

                        if (desc.SampleDescription != testDesc.SampleDescription)
                        {
                            _message = "SAMPLE";
                        }

                        if (desc.Usage != testDesc.Usage)
                        {
                            _message = "Usage";
                        }


                        t = new Texture2D(context.Device, desc);

                        sharedRes = new SlimDX.DXGI.Resource(t);
                        dxHandle  = sharedRes.SharedHandle;
                        //_message = FTexturePointer[0].ToString();
                        ////FTexturePointer

                        ////int p = unchecked((int)this.FTexturePointer[0]);
                        ////IntPtr shared = new IntPtr(FTexturePointer[0]);

                        //if (shared != null)
                        //{
                        shared = interop.CreateSharedSurfaceFromTexture(dxHandle, desc.Width, desc.Height);
                        //shared = interop.CreateSharedSurfaceFromTexture(share, 600, 600);
                        //}
                        FTextureOutput[0] = new DX11Resource <DX11Texture2D>();
                        //FTextureOutput[0][context] = t;


                        ShaderResourceView tSRV = new ShaderResourceView(context.Device, t);
                        DX11Texture2D      tRes = DX11Texture2D.FromTextureAndSRV(context, t, tSRV);
                        FTextureOutput[0][context] = tRes;


                        GL.GenTextures(1, glTex);
                        GL.BindTexture(TextureTarget.Texture2D, glTex[0]);

                        interop.BindSurfaceToTexture(shared);

                        GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Nearest);
                        GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMinFilter.Nearest);

                        //GL.ActiveTexture(TextureUnit.Texture0);
                        //GL.BindTexture();
                    }
                    catch (Exception e)
                    {
                        //_message = e.ToString();
                    }

                    var vert = @"//#version 300 es
                        attribute vec4 vPosition;
                        attribute vec2 aTexCoord;
                        varying vec2 vTexCoord;
                        void main()
                        {
                            gl_Position = vPosition;
                            vTexCoord = aTexCoord;
                        }";

                    var frag = @"//#version 300 es
                        precision mediump float;
                        varying vec2 vTexCoord;
                        uniform vec4 color;
                        uniform sampler2D iChannel0;
                        void main()
                        {
                            vec2 uv = vTexCoord;
                            vec3 col = texture2D(iChannel0, uv).xyz;
                            gl_FragColor = vec4(col, 1.0);
                        }";


                    var status = new int[1];

                    const int GL_TRUE = 1;

                    _program = GL.CreateProgram();
                    var vs = GL.CreateShader(ShaderType.VertexShader);
                    GL.ShaderSource(vs, vert);
                    GL.CompileShader(vs);

                    GL.GetShader(vs, ShaderParameter.CompileStatus, status);
                    if (status[0] != GL_TRUE)
                    {
                        var error = GL.GetShaderInfoLog(vs);
                        throw new Exception(error);
                    }

                    var fs = GL.CreateShader(ShaderType.FragmentShader);
                    GL.ShaderSource(fs, frag);
                    GL.CompileShader(fs);

                    GL.GetShader(fs, ShaderParameter.CompileStatus, status);
                    if (status[0] != GL_TRUE)
                    {
                        var error = GL.GetShaderInfoLog(fs);
                        throw new Exception(error);
                    }

                    GL.AttachShader(_program, vs);
                    GL.AttachShader(_program, fs);

                    GL.BindAttribLocation(_program, 0, "vPosition");


                    GL.LinkProgram(_program);

                    //GL.DeleteShader(vs);
                    //GL.DeleteShader(fs);

                    GL.UseProgram(_program);


                    GL.GetProgram(_program, GetProgramParameterName.LinkStatus, status);
                    if (status[0] != GL_TRUE)
                    {
                        var error = GL.GetProgramInfoLog(_program);
                        throw new Exception(error);
                    }

                    uColor       = GL.GetUniformLocation(_program, "color");
                    mPositionLoc = GL.GetAttribLocation(_program, "vPosition");
                    mTexCoordLoc = GL.GetAttribLocation(_program, "aTexCoord");

                    FPointer[0] = share.ToInt64();
                    FValid[0]   = true;
                    FInvalidate = false;

                    //int[] glTex = new int[4];
                    //GL.GenTextures(1, glTex);
                    //GL.TexParameter(GL)
                    //GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int) TextureMagFilter.Nearest);
                }

                //this.AssignedContext.CurrentDeviceContext.CopyResource(this.FTextureIn[0][context].Resource, t);
                context.CurrentDeviceContext.CopyResource(FTextureIn[0][context].Resource, t);

                interop.MakeCurrent(angleSurface);

                float[] vVertices = new float[] { 0.0f, 0.5f, 0.0f,
                                                  -0.5f, -0.5f, 0.0f,
                                                  0.5f, -0.5f, 0.0f };


                float[] vertices = new float[]
                {
                    -0.5f, 0.5f, 0.0f,   // Position 0
                    0.0f, 0.0f,          // TexCoord 0
                    -0.5f, -0.5f, 0.0f,  // Position 1
                    0.0f, 1.0f,          // TexCoord 1
                    0.5f, -0.5f, 0.0f,   // Position 2
                    1.0f, 1.0f,          // TexCoord 2
                    0.5f, 0.5f, 0.0f,    // Position 3
                    1.0f, 0.0f           // TexCoord 3
                };

                short[] indices = { 0, 1, 2, 0, 2, 3 };

                GL.Viewport(0, 0, 500, 500);
                GL.ClearColor((float)ColorIn[0].R, (float)ColorIn[0].G, (float)ColorIn[0].B, 0.0f);
                GL.Clear(ClearBufferMask.ColorBufferBit);
                GL.UseProgram(_program);
                Color4 color = new Color4((float)ColorIn[0].R, (float)ColorIn[0].G, (float)ColorIn[0].B, (float)ColorIn[0].A);
                GL.Uniform4(uColor, color);

                //Vertex Attributes
                GL.VertexAttribPointer(mPositionLoc, 3, VertexAttribPointerType.Float, false, 5 * sizeof(float), vertices);
                // Load the texture coordinate
                GL.VertexAttribPointer(mTexCoordLoc, 2, VertexAttribPointerType.Float, false, 5 * sizeof(float), vertices.Skip(3).ToArray());


                //GL.VertexAttribPointer(0, 3, VertexAttribPointerType.Float, false, 0, vVertices);
                //GL.EnableVertexAttribArray(0);
                GL.EnableVertexAttribArray(mPositionLoc);
                GL.EnableVertexAttribArray(mTexCoordLoc);

                //Texture Bind
                GL.ActiveTexture(TextureUnit.Texture0);
                GL.BindTexture(TextureTarget.Texture2D, glTex[0]);


                int iChannel0 = GL.GetUniformLocation(_program, "iChannel0");
                GL.Uniform1(iChannel0, 0);


                GL.DrawArrays(PrimitiveType.Triangles, 0, 3);
                GL.DrawElements(PrimitiveType.Triangles, 6, DrawElementsType.UnsignedShort, indices);

                interop.SwapBuffers(angleSurface);
                GL.Finish();
                //_message = "running update";
            }
            catch (Exception e)
            {
                //_message = e.ToString();
                //_message = e.ToString();
            }
        }
            public void SetPosition(DX11RenderContext ctx, int frame)
            {
                int frameindex = frame - this.CurrentFrame;
                frameindex = frameindex < 0 ? 0 : frameindex;
                frameindex = frameindex > Data.FileCount - 1 ? Data.FileCount - 1 : frameindex;

                if (frameindex != CurrentFrame)
                {
                    if (this.Texture == null)
                    {
                        this.Texture.Dispose();
                    }

                    ImageLoadInformation info = ImageLoadInformation.FromDefaults();
                    info.MipLevels = 1;
                    this.Texture = DX11Texture2D.FromFile(ctx, Data.FilePath[frameindex],info);
                    CurrentFrame = frameindex;
                }
            }
        private void task_StatusChanged(IDX11ScheduledTask task)
        {
            this.Status = task.Status;
            if (this.Status == eDX11SheduleTaskStatus.Completed || this.Status == eDX11SheduleTaskStatus.Error)
            {
                this.Texture = m_task.Resource;

                if (this.OnLoadComplete != null)
                {
                    this.OnLoadComplete(this);
                }
            }
        }
        public void Update(IPluginIO pin, DX11RenderContext context)
        {
            Device        device = context.Device;
            DeviceContext ctx    = context.CurrentDeviceContext;

            if (!this.deviceshaderdata.ContainsKey(context))
            {
                this.deviceshaderdata.Add(context, new DX11ShaderData(context));
                this.deviceshaderdata[context].SetEffect(this.FShader);
            }

            DX11ShaderData shaderdata = this.deviceshaderdata[context];

            if (this.shaderupdated)
            {
                shaderdata.SetEffect(this.FShader);
                this.shaderupdated = false;
            }

            context.RenderStateStack.Push(new DX11RenderState());

            this.OnBeginQuery(context);


            //Clear shader stages
            shaderdata.ResetShaderStages(ctx);
            context.Primitives.ApplyFullTriVS();

            foreach (DX11ResourcePoolEntry <DX11RenderTarget2D> rt in this.lastframetargets)
            {
                rt.UnLock();
            }
            this.lastframetargets.Clear();

            DX11ObjectRenderSettings or = new DX11ObjectRenderSettings();

            int wi, he;

            for (int i = 0; i < this.spmax; i++)
            {
                if (this.FInEnabled[i])
                {
                    List <DX11ResourcePoolEntry <DX11RenderTarget2D> > locktargets = new List <DX11ResourcePoolEntry <DX11RenderTarget2D> >();

                    DX11Texture2D initial;
                    if (this.FIn.PluginIO.IsConnected)
                    {
                        if (this.FInUseDefaultSize[0])
                        {
                            initial = context.DefaultTextures.WhiteTexture;
                            wi      = (int)this.FInSize[0].X;
                            he      = (int)this.FInSize[0].Y;
                        }
                        else
                        {
                            initial = this.FIn[i][context];
                            if (initial != null)
                            {
                                wi = initial.Width;
                                he = initial.Height;
                            }
                            else
                            {
                                initial = context.DefaultTextures.WhiteTexture;
                                wi      = (int)this.FInSize[0].X;
                                he      = (int)this.FInSize[0].Y;
                            }
                        }
                    }
                    else
                    {
                        initial = context.DefaultTextures.WhiteTexture;
                        wi      = (int)this.FInSize[0].X;
                        he      = (int)this.FInSize[0].Y;
                    }

                    DX11RenderSettings r = new DX11RenderSettings();
                    r.RenderWidth  = wi;
                    r.RenderHeight = he;
                    if (this.FInSemantics.PluginIO.IsConnected)
                    {
                        r.CustomSemantics.AddRange(this.FInSemantics.ToArray());
                    }
                    if (this.FInResSemantics.PluginIO.IsConnected)
                    {
                        r.ResourceSemantics.AddRange(this.FInResSemantics.ToArray());
                    }

                    this.varmanager.SetGlobalSettings(shaderdata.ShaderInstance, r);

                    this.varmanager.ApplyGlobal(shaderdata.ShaderInstance);

                    DX11Texture2D lastrt = initial;
                    DX11ResourcePoolEntry <DX11RenderTarget2D> lasttmp = null;

                    List <DX11Texture2D> rtlist = new List <DX11Texture2D>();

                    //Bind Initial (once only is ok)
                    this.BindTextureSemantic(shaderdata.ShaderInstance.Effect, "INITIAL", initial);

                    if (this.persistedframe != null)
                    {
                        this.BindSemanticSRV(shaderdata.ShaderInstance.Effect, "LASTFRAME", persistedframe.SRV);
                    }

                    //Go trough all passes
                    EffectTechnique tech = shaderdata.ShaderInstance.Effect.GetTechniqueByIndex(tid);


                    for (int j = 0; j < tech.Description.PassCount; j++)
                    {
                        ImageShaderPass pi   = this.varmanager.passes[j];
                        EffectPass      pass = tech.GetPassByIndex(j);

                        if (j > 0)
                        {
                            int    pid   = j - 1;
                            string pname = "PASSRESULT" + pid;

                            this.BindTextureSemantic(shaderdata.ShaderInstance.Effect, pname, rtlist[pid]);
                        }

                        Format fmt = initial.Format;
                        if (pi.CustomFormat)
                        {
                            fmt = pi.Format;
                        }
                        bool mips = pi.Mips;

                        int w, h;
                        if (j == 0)
                        {
                            h = he;
                            w = wi;
                        }
                        else
                        {
                            h = pi.Reference == ImageShaderPass.eImageScaleReference.Initial ? he : lastrt.Height;
                            w = pi.Reference == ImageShaderPass.eImageScaleReference.Initial ? wi : lastrt.Width;
                        }

                        if (pi.DoScale)
                        {
                            h = Convert.ToInt32((float)h * pi.Scale);
                            w = Convert.ToInt32((float)w * pi.Scale);
                            h = Math.Max(h, 1);
                            w = Math.Max(w, 1);
                        }

                        //Check format support for render target, and default to rgb8 if not
                        if (!context.IsSupported(FormatSupport.RenderTarget, fmt))
                        {
                            fmt = Format.R8G8B8A8_UNorm;
                        }

                        //Since device is not capable of telling us BGR not supported
                        if (fmt == Format.B8G8R8A8_UNorm)
                        {
                            fmt = Format.R8G8B8A8_UNorm;
                        }


                        DX11ResourcePoolEntry <DX11RenderTarget2D> elem = context.ResourcePool.LockRenderTarget(w, h, fmt, new SampleDescription(1, 0), mips, 0);
                        locktargets.Add(elem);
                        DX11RenderTarget2D rt = elem.Element;
                        ctx.OutputMerger.SetTargets(rt.RTV);

                        r.RenderWidth  = w;
                        r.RenderHeight = h;
                        r.BackBuffer   = rt;
                        this.varmanager.ApplyGlobal(shaderdata.ShaderInstance);

                        //Apply settings (note that textures swap is handled later)
                        this.varmanager.ApplyPerObject(context, shaderdata.ShaderInstance, or, i);

                        Viewport vp = new Viewport();
                        vp.Width  = rt.Width;
                        vp.Height = rt.Height;
                        ctx.Rasterizer.SetViewports(vp);

                        //Bind last render target
                        this.BindTextureSemantic(shaderdata.ShaderInstance.Effect, "PREVIOUS", lastrt);

                        //Apply pass and draw quad
                        pass.Apply(ctx);

                        if (pi.ComputeData.Enabled)
                        {
                            pi.ComputeData.Dispatch(context, w, h);
                            context.CleanUpCS();
                        }
                        else
                        {
                            ctx.ComputeShader.Set(null);
                            context.Primitives.FullScreenTriangle.Draw();
                            ctx.OutputMerger.SetTargets(this.nullrtvs);
                        }

                        //Generate mips if applicable
                        if (pi.Mips)
                        {
                            ctx.GenerateMips(rt.SRV);
                        }

                        rtlist.Add(rt);

                        lastrt  = rt;
                        lasttmp = elem;
                    }

                    //Set last render target
                    this.FOut[i][context] = lastrt;

                    //Unlock all resources
                    foreach (DX11ResourcePoolEntry <DX11RenderTarget2D> lt in locktargets)
                    {
                        lt.UnLock();
                    }

                    //Keep lock on last rt, since don't want it overidden
                    lasttmp.Lock();

                    //this.lastframetargets.
                    //this.lasttarget = lasttmp;

                    this.lastframetargets.Add(lasttmp);


                    //previousrts[context] = lasttmp.Element;
                }
                else
                {
                    this.FOut[i][context] = this.FIn[i][context];
                }
            }

            context.RenderStateStack.Pop();

            this.OnEndQuery(context);

            //UnLock previous frame in applicable
            //if (previoustarget != null) { context.ResourcePool.Unlock(previoustarget); }
        }
				public void Save(DX11Texture2D texture, FeralTic.DX11.DX11RenderContext context, string filename, SlimDX.Direct3D11.ImageFileFormat format)
				{
					if (texture == null)
					{
						throw (new Exception("No texture"));
					}
					CurrentState = State.Saving;

					if (FBackSurface == null || FBackSurface.Description.Width != texture.Width || FBackSurface.Description.Height != texture.Height || context != FContext)
					{
						if (FBackSurface != null)
						{
							FBackSurface.Dispose();
						}
						var description = new Texture2DDescription()
						{
							Width = texture.Width,
							Height = texture.Height,
							Format = texture.Format,
							MipLevels = 1,
							Usage = ResourceUsage.Staging,
							BindFlags = BindFlags.None,
							CpuAccessFlags = CpuAccessFlags.Read,
							SampleDescription = new SampleDescription(1, 0),
							ArraySize = 1
						};
						FBackSurface = new Texture2D(context.Device, description);
						FContext = context;
					}

					context.CurrentDeviceContext.CopyResource(texture.Resource, FBackSurface);
					FFilename = filename;
					FFormat = format;
					//FThread = new Thread(ThreadedFunction);
					//FThread.Name = "Recorder";
					//FThread.Start();
					ThreadedFunction();
				}
Exemple #47
0
 public void Reset(DX11Texture2D texture, int w, int h, int d, SlimDX.DXGI.Format format)
 {
     format = format == SlimDX.DXGI.Format.Unknown ? texture.Format : format;
     this.rtarr.Dispose();
     this.rtarr = new DX11RenderTextureArray(this.context, w, h, d, format);
 }