本文整理汇总了C#中SharpDX.Direct3D11.Texture2D.Dispose方法的典型用法代码示例。如果您正苦于以下问题:C# Texture2D.Dispose方法的具体用法?C# Texture2D.Dispose怎么用?C# Texture2D.Dispose使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类SharpDX.Direct3D11.Texture2D
的用法示例。
在下文中一共展示了Texture2D.Dispose方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: SharpCubeTarget
/// <summary>
/// Constructor
/// </summary>
/// <param name="device">Device</param>
/// <param name="size">Cube Size</param>
/// <param name="format">Color Format</param>
public SharpCubeTarget(SharpDevice device, int size, Format format)
{
Device = device;
Size = size;
Texture2D target = new Texture2D(device.Device, new Texture2DDescription()
{
Format = format,
Width = size,
Height = size,
ArraySize = 6,
BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource,
CpuAccessFlags = CpuAccessFlags.None,
MipLevels = 1,
OptionFlags = ResourceOptionFlags.TextureCube,
SampleDescription = new SampleDescription(1, 0),
Usage = ResourceUsage.Default,
});
_target = new RenderTargetView(device.Device, target);
_resource = new ShaderResourceView(device.Device, target);
target.Dispose();
var _zbufferTexture = new Texture2D(Device.Device, new Texture2DDescription()
{
Format = Format.D16_UNorm,
ArraySize = 6,
MipLevels = 1,
Width = size,
Height = size,
SampleDescription = new SampleDescription(1, 0),
Usage = ResourceUsage.Default,
BindFlags = BindFlags.DepthStencil,
CpuAccessFlags = CpuAccessFlags.None,
OptionFlags = ResourceOptionFlags.TextureCube
});
// Create the depth buffer view
_zbuffer = new DepthStencilView(Device.Device, _zbufferTexture);
_zbufferTexture.Dispose();
}
示例2: CaptureScreen
public static Bitmap CaptureScreen()
{
// # of graphics card adapter
const int numAdapter = 0;
// # of output device (i.e. monitor)
const int numOutput = 1;
// Create DXGI Factory1
var factory = new Factory1();
var adapter = factory.GetAdapter1(numAdapter);
// Create device from Adapter
var device = new Device(adapter);
// Get DXGI.Output
var output = adapter.GetOutput(numOutput);
var output1 = output.QueryInterface<Output1>();
// Width/Height of desktop to capture
int width = ((Rectangle)output.Description.DesktopBounds).Width;
//width = 1024;
int height = ((Rectangle)output.Description.DesktopBounds).Height;
//height = 1024;
// Create Staging texture CPU-accessible
var textureDesc = new Texture2DDescription
{
CpuAccessFlags = CpuAccessFlags.Read,
BindFlags = BindFlags.None,
Format = Format.B8G8R8A8_UNorm,
Width = width,
Height = height,
OptionFlags = ResourceOptionFlags.None,
MipLevels = 1,
ArraySize = 1,
SampleDescription = { Count = 1, Quality = 0 },
Usage = ResourceUsage.Staging
};
var screenTexture = new Texture2D(device, textureDesc);
// Duplicate the output
var duplicatedOutput = output1.DuplicateOutput(device);
bool captureDone = false;
Bitmap bitmap = null;
for (int i = 0; !captureDone; i++)
{
try
{
SharpDX.DXGI.Resource screenResource;
OutputDuplicateFrameInformation duplicateFrameInformation;
// Try to get duplicated frame within given time
duplicatedOutput.AcquireNextFrame(10000, out duplicateFrameInformation, out screenResource);
if (i > 0)
{
// copy resource into memory that can be accessed by the CPU
using (var screenTexture2D = screenResource.QueryInterface<Texture2D>())
device.ImmediateContext.CopyResource(screenTexture2D, screenTexture);
// Get the desktop capture texture
var mapSource = device.ImmediateContext.MapSubresource(screenTexture, 0, MapMode.Read, MapFlags.None);
// Create Drawing.Bitmap
bitmap = new System.Drawing.Bitmap(width, height, PixelFormat.Format32bppArgb);
var boundsRect = new System.Drawing.Rectangle(0, 0, width, height);
// Copy pixels from screen capture Texture to GDI bitmap
var mapDest = bitmap.LockBits(boundsRect, ImageLockMode.WriteOnly, bitmap.PixelFormat);
var sourcePtr = mapSource.DataPointer;
var destPtr = mapDest.Scan0;
for (int y = 0; y < height; y++)
{
// Copy a single line
Utilities.CopyMemory(destPtr, sourcePtr, width * 4);
// Advance pointers
sourcePtr = IntPtr.Add(sourcePtr, mapSource.RowPitch);
destPtr = IntPtr.Add(destPtr, mapDest.Stride);
}
// Release source and dest locks
bitmap.UnlockBits(mapDest);
device.ImmediateContext.UnmapSubresource(screenTexture, 0);
// Capture done
captureDone = true;
}
screenResource.Dispose();
duplicatedOutput.ReleaseFrame();
}
catch (SharpDXException e)
{
if (e.ResultCode.Code != SharpDX.DXGI.ResultCode.WaitTimeout.Result.Code)
{
//.........这里部分代码省略.........
示例3: ResizeBuffers
void ResizeBuffers()
{
// Dispose all previous allocated resources
Utilities.Dispose(ref _backbufferView);
Utilities.Dispose(ref _zbufferView);
if (RenderViewSize.Width == 0 || RenderViewSize.Height == 0)
return;
// Resize the backbuffer
SwapChain.ResizeBuffers(1, RenderViewSize.Width, RenderViewSize.Height, Format.R8G8B8A8_UNorm, SwapChainFlags.AllowModeSwitch);
// Get the backbuffer from the swapchain
var _backBufferTexture = SwapChain.GetBackBuffer<Texture2D>(0);
_backBufferTexture.DebugName = "Lilium BackBuffer";
// Backbuffer
_backbufferView = new RenderTargetView(Device, _backBufferTexture);
_backbufferView.DebugName = "Lilium BackBuffer View";
_backBufferTexture.Dispose();
// Depth buffer
var _zbufferTexture = new Texture2D(Device, new Texture2DDescription()
{
Format = Format.D24_UNorm_S8_UInt,
ArraySize = 1,
MipLevels = 1,
Width = RenderViewSize.Width,
Height = RenderViewSize.Height,
SampleDescription = new SampleDescription(Config.MSAASampleCount, Config.MSAAQuality),
Usage = ResourceUsage.Default,
BindFlags = BindFlags.DepthStencil,
CpuAccessFlags = CpuAccessFlags.None,
OptionFlags = ResourceOptionFlags.None
});
_zbufferTexture.DebugName = "Lilium DepthStencilBuffer";
// Create the depth buffer view
_zbufferView = new DepthStencilView(Device, _zbufferTexture);
_zbufferView.DebugName = "Lilium DepthStencilBuffer View";
_zbufferTexture.Dispose();
DeviceContext.Rasterizer.SetViewport(0, 0, RenderViewSize.Width, RenderViewSize.Height);
DeviceContext.OutputMerger.SetTargets(_zbufferView, _backbufferView);
// Resize UI Surface
if(mUISurface != null)
mUISurface.SetDesignHeight(RenderViewSize.Height);
needResize = false;
}
示例4: PresentHook
//.........这里部分代码省略.........
// Copy the subresource region, we are dealing with a flat 2D texture with no MipMapping, so 0 is the subresource index
theTexture.Device.ImmediateContext.CopySubresourceRegion(theTexture, 0, new ResourceRegion()
{
Top = regionToCapture.Top,
Bottom = regionToCapture.Bottom,
Left = regionToCapture.Left,
Right = regionToCapture.Right,
Front = 0,
Back = 1 // Must be 1 or only black will be copied
}, textureDest, 0, 0, 0, 0);
// Note: it would be possible to capture multiple frames and process them in a background thread
// Copy to memory and send back to host process on a background thread so that we do not cause any delay in the rendering pipeline
Guid requestId = this.Request.RequestId; // this.Request gets set to null, so copy the RequestId for use in the thread
ThreadPool.QueueUserWorkItem(delegate
{
//FileStream fs = new FileStream(@"c:\temp\temp.bmp", FileMode.Create);
//Texture2D.ToStream(testSubResourceCopy, ImageFileFormat.Bmp, fs);
DateTime startCopyToSystemMemory = DateTime.Now;
using (MemoryStream ms = new MemoryStream())
{
Texture2D.ToStream(textureDest.Device.ImmediateContext, textureDest, ImageFileFormat.Bmp, ms);
ms.Position = 0;
this.DebugMessage("PresentHook: Copy to System Memory time: " + (DateTime.Now - startCopyToSystemMemory).ToString());
DateTime startSendResponse = DateTime.Now;
ProcessCapture(ms, requestId);
this.DebugMessage("PresentHook: Send response time: " + (DateTime.Now - startSendResponse).ToString());
}
// Free the textureDest as we no longer need it.
textureDest.Dispose();
textureDest = null;
this.DebugMessage("PresentHook: Full Capture time: " + (DateTime.Now - startTime).ToString());
});
// Prevent the request from being processed a second time
this.Request = null;
// Make sure we free up the resolved texture if it was created
if (textureResolved != null)
{
textureResolved.Dispose();
textureResolved = null;
}
}
this.DebugMessage("PresentHook: Copy BackBuffer time: " + (DateTime.Now - startTime).ToString());
this.DebugMessage("PresentHook: Request End");
}
#endregion
#if OVERLAYENGINE
#region Draw overlay (after screenshot so we don't capture overlay as well)
if (this.Config.ShowOverlay)
{
// Initialise Overlay Engine
if (_swapChainPointer != swapChain.NativePointer || _overlayEngine == null)
{
if (_overlayEngine != null)
_overlayEngine.Dispose();
_overlayEngine = new DX11.DXOverlayEngine();
_overlayEngine.Overlays.Add(new Capture.Hook.Common.Overlay
{
Elements =
{
//new Capture.Hook.Common.TextElement(new System.Drawing.Font("Times New Roman", 22)) { Text = "Test", Location = new System.Drawing.Point(200, 200), Color = System.Drawing.Color.Yellow, AntiAliased = false},
new Capture.Hook.Common.FramesPerSecond(new System.Drawing.Font("Arial", 16)) { Location = new System.Drawing.Point(5,5), Color = System.Drawing.Color.Red, AntiAliased = true }
}
});
_overlayEngine.Initialise(swapChain);
_swapChainPointer = swapChain.NativePointer;
}
// Draw Overlay(s)
else if (_overlayEngine != null)
{
foreach (var overlay in _overlayEngine.Overlays)
overlay.Frame();
_overlayEngine.Draw();
}
}
#endregion
#endif
}
catch (Exception e)
{
// If there is an error we do not want to crash the hooked application, so swallow the exception
this.DebugMessage("PresentHook: Exeception: " + e.GetType().FullName + ": " + e.ToString());
//return unchecked((int)0x8000FFFF); //E_UNEXPECTED
}
// As always we need to call the original method, note that EasyHook has already repatched the original method
// so calling it here will not cause an endless recursion to this function
swapChain.Present(syncInterval, flags);
return SharpDX.Result.Ok.Code;
}
示例5: Save
private static void Save(IResource res, Stream stream, ImageFileFormat fmt)
{
var texture = res.Resource as Texture2D;
var textureCopy = new Texture2D(MyRender11.Device, new Texture2DDescription
{
Width = (int)texture.Description.Width,
Height = (int)texture.Description.Height,
MipLevels = 1,
ArraySize = 1,
Format = texture.Description.Format,
Usage = ResourceUsage.Staging,
SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
BindFlags = BindFlags.None,
CpuAccessFlags = CpuAccessFlags.Read,
OptionFlags = ResourceOptionFlags.None
});
RC.CopyResource(res, textureCopy);
DataStream dataStream;
var dataBox = RC.MapSubresource(
textureCopy,
0,
0,
MapMode.Read,
MapFlags.None,
out dataStream);
var dataRectangle = new DataRectangle
{
DataPointer = dataStream.DataPointer,
Pitch = dataBox.RowPitch
};
var bitmap = new Bitmap(
MyRender11.WIC,
textureCopy.Description.Width,
textureCopy.Description.Height,
PixelFormatFromFormat(textureCopy.Description.Format), // TODO: should use some conversion from textureCopy.Description.Format
dataRectangle);
using (var wicStream = new WICStream(MyRender11.WIC, stream))
{
BitmapEncoder bitmapEncoder;
switch (fmt)
{
case ImageFileFormat.Png:
bitmapEncoder = new PngBitmapEncoder(MyRender11.WIC, wicStream);
break;
case ImageFileFormat.Jpg:
bitmapEncoder = new JpegBitmapEncoder(MyRender11.WIC, wicStream);
break;
case ImageFileFormat.Bmp:
bitmapEncoder = new BmpBitmapEncoder(MyRender11.WIC, wicStream);
break;
default:
MyRenderProxy.Assert(false, "Unsupported file format.");
bitmapEncoder = null;
break;
}
if (bitmapEncoder != null)
{
using (var bitmapFrameEncode = new BitmapFrameEncode(bitmapEncoder))
{
bitmapFrameEncode.Initialize();
bitmapFrameEncode.SetSize(bitmap.Size.Width, bitmap.Size.Height);
var pixelFormat = PixelFormat.FormatDontCare;
bitmapFrameEncode.SetPixelFormat(ref pixelFormat);
bitmapFrameEncode.WriteSource(bitmap);
bitmapFrameEncode.Commit();
bitmapEncoder.Commit();
}
bitmapEncoder.Dispose();
}
}
RC.UnmapSubresource(textureCopy, 0);
textureCopy.Dispose();
bitmap.Dispose();
}
示例6: Run
//.........这里部分代码省略.........
// ---------------------------------------------------------------------------------------------------
// Acquire the mutexes. These are needed to assure the device in use has exclusive access to the surface
// ---------------------------------------------------------------------------------------------------
var device10Mutex = textureD3D10.QueryInterface<KeyedMutex>();
var device11Mutex = textureD3D11.QueryInterface<KeyedMutex>();
// ---------------------------------------------------------------------------------------------------
// Main rendering loop
// ---------------------------------------------------------------------------------------------------
bool first = true;
RenderLoop
.Run(form,
() =>
{
if(first)
{
form.Activate();
first = false;
}
// clear the render target to black
context.ClearRenderTargetView(renderTargetView, Colors.DarkSlateGray);
// Draw the triangle
context.InputAssembler.InputLayout = layoutColor;
context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBufferColor, VertexPositionColor.SizeInBytes, 0));
context.OutputMerger.BlendState = null;
var currentTechnique = effect.GetTechniqueByName("Color");
for (var pass = 0; pass < currentTechnique.Description.PassCount; ++pass)
{
using (var effectPass = currentTechnique.GetPassByIndex(pass))
{
System.Diagnostics.Debug.Assert(effectPass.IsValid, "Invalid EffectPass");
effectPass.Apply(context);
}
context.Draw(3, 0);
};
// Draw Ellipse on the shared Texture2D
device10Mutex.Acquire(0, 100);
renderTarget2D.BeginDraw();
renderTarget2D.Clear(Colors.Black);
renderTarget2D.DrawGeometry(tesselatedGeometry, solidColorBrush);
renderTarget2D.DrawEllipse(new Ellipse(center, 200, 200), solidColorBrush, 20, null);
renderTarget2D.EndDraw();
device10Mutex.Release(0);
// Draw the shared texture2D onto the screen, blending the 2d content in
device11Mutex.Acquire(0, 100);
var srv = new ShaderResourceView(device11, textureD3D11);
effect.GetVariableByName("g_Overlay").AsShaderResource().SetResource(srv);
context.InputAssembler.InputLayout = layoutOverlay;
context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleStrip;
context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBufferOverlay, VertexPositionTexture.SizeInBytes, 0));
context.OutputMerger.BlendState = blendStateTransparent;
currentTechnique = effect.GetTechniqueByName("Overlay");
for (var pass = 0; pass < currentTechnique.Description.PassCount; ++pass)
{
using (var effectPass = currentTechnique.GetPassByIndex(pass))
{
System.Diagnostics.Debug.Assert(effectPass.IsValid, "Invalid EffectPass");
effectPass.Apply(context);
}
context.Draw(4, 0);
}
srv.Dispose();
device11Mutex.Release(0);
swapChain.Present(0, PresentFlags.None);
});
// dispose everything
vertexBufferColor.Dispose();
vertexBufferOverlay.Dispose();
layoutColor.Dispose();
layoutOverlay.Dispose();
effect.Dispose();
shaderByteCode.Dispose();
renderTarget2D.Dispose();
swapChain.Dispose();
device11.Dispose();
device10.Dispose();
textureD3D10.Dispose();
textureD3D11.Dispose();
factory1.Dispose();
adapter1.Dispose();
sharedResource.Dispose();
factory2D.Dispose();
surface.Dispose();
solidColorBrush.Dispose();
blendStateTransparent.Dispose();
device10Mutex.Dispose();
device11Mutex.Dispose();
}
示例7: InitDX
public void InitDX(RenderForm form)
{
// SwapChain description
SwapChainDescription desc = new SwapChainDescription()
{
BufferCount = 1,
ModeDescription =
new ModeDescription(form.ClientSize.Width, form.ClientSize.Height, new Rational(60, 1), Format.R10G10B10A2_UNorm),//.R8G8B8A8_UNorm),
IsWindowed = true,
OutputHandle = form.Handle,
SampleDescription = new SampleDescription(1, 0),
SwapEffect = SwapEffect.Discard,
Usage = Usage.RenderTargetOutput
};
// Create Device and SwapChain
#if DEBUG
Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.Debug, desc, out device, out swapChain);
#else
Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, desc, out device, out swapChain);
#endif
context = device.ImmediateContext;
// Ignore all windows events
factory = swapChain.GetParent<Factory>();
factory.MakeWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll);
// New RenderTargetView from the backbuffer
backBuffer = Texture2D.FromSwapChain<Texture2D>(swapChain, 0);
renderView = new RenderTargetView(device, backBuffer);
LoadShaders();
FileSystemWatcher watcher = new FileSystemWatcher(@"\dev\Galaxies\Galaxies\", "*.fx");
watcher.NotifyFilter = NotifyFilters.LastWrite;
watcher.Changed += new FileSystemEventHandler(Watcher_Changed);
watcher.EnableRaisingEvents = true;
// Compile Vertex and Pixel shaders
//vertexShaderByteCode = ShaderBytecode.CompileFromFile("MiniTri.fx", "VS", "vs_5_0");
//vertexShader = new VertexShader(device, vertexShaderByteCode);
//pixelShaderByteCode = ShaderBytecode.CompileFromFile("MiniTri.fx", "PS", "ps_5_0");
//pixelShader = new PixelShader(device, pixelShaderByteCode);
// Create Constant Buffer
//constantBuffer = new Buffer(device, Utilities.SizeOf<Matrix>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);
int tempSize = System.Runtime.InteropServices.Marshal.SizeOf(new ShaderParamStruct());
constantBuffer = new Buffer(device, tempSize, ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);
// Create Depth Buffer & View
var depthBuffer = new Texture2D(device, new Texture2DDescription()
{
Format = Format.D32_Float_S8X24_UInt,
ArraySize = 1,
MipLevels = 1,
Width = form.ClientSize.Width,
Height = form.ClientSize.Height,
SampleDescription = new SampleDescription(1, 0),
Usage = ResourceUsage.Default,
BindFlags = BindFlags.DepthStencil,
CpuAccessFlags = CpuAccessFlags.None,
OptionFlags = ResourceOptionFlags.None
});
depthView = new DepthStencilView(device, depthBuffer);
//RasterizerStateDescription rsd = new RasterizerStateDescription() { IsMultisampleEnabled = true };
//rsd.CullMode = CullMode.Back;
//rsd.FillMode = FillMode.Solid;
//rsd.IsMultisampleEnabled = true;
//rsd.IsAntialiasedLineEnabled = false;
//rsd.IsDepthClipEnabled = false;
//rsd.IsScissorEnabled = false;
//RasterizerState rs = new RasterizerState(device, rsd);
//device.ImmediateContext.Rasterizer.State = rs;
//rs.Dispose();
depthBuffer.Dispose();
texMan = new TextureManager();
}
示例8: SaveBackBuffer
public void SaveBackBuffer(string filename, ImageFileFormat format)
{
if (MultiSampleCount != 1)
{
Texture2D tex2 = new Texture2D(RenderContext11.PrepDevice, new Texture2DDescription()
{
Format = RenderContext11.DefaultColorFormat,
ArraySize = 1,
MipLevels = 1,
Width = (int)ViewPort.Width,
Height = (int)ViewPort.Height,
SampleDescription = new SampleDescription(1, 0),
Usage = ResourceUsage.Default,
BindFlags = BindFlags.ShaderResource | BindFlags.RenderTarget,
CpuAccessFlags = CpuAccessFlags.None,
OptionFlags = ResourceOptionFlags.None
});
devContext.ResolveSubresource(backBuffer, 0, tex2, 0, RenderContext11.DefaultColorFormat);
Texture2D.ToFile(devContext, tex2, format, filename);
tex2.Dispose();
GC.SuppressFinalize(tex2);
}
else
{
Texture2D.ToFile(devContext, backBuffer, format, filename);
}
}
示例9: GetScreenBitmap
public Bitmap GetScreenBitmap()
{
MemoryStream ms = new MemoryStream();
if (MultiSampleCount != 1)
{
Texture2D tex2 = new Texture2D(RenderContext11.PrepDevice, new Texture2DDescription()
{
Format = RenderContext11.DefaultColorFormat,
ArraySize = 1,
MipLevels = 1,
Width = (int)ViewPort.Width,
Height = (int)ViewPort.Height,
SampleDescription = new SampleDescription(1, 0),
Usage = ResourceUsage.Default,
BindFlags = BindFlags.RenderTarget,
CpuAccessFlags = CpuAccessFlags.None,
OptionFlags = ResourceOptionFlags.None
});
devContext.ResolveSubresource(backBuffer, 0, tex2, 0, RenderContext11.DefaultColorFormat);
Texture2D.ToStream(devContext, tex2, ImageFileFormat.Png, ms);
tex2.Dispose();
GC.SuppressFinalize(tex2);
}
else
{
Texture2D.ToStream(devContext, backBuffer, ImageFileFormat.Png, ms);
}
ms.Seek(0, SeekOrigin.Begin);
Bitmap bmp = new Bitmap(ms);
ms.Close();
ms.Dispose();
return bmp;
}
示例10: GenerateHeightMaps
private void GenerateHeightMaps()
{
ShaderBytecode shaderByteCode = ShaderBytecode.CompileFromFile(@"Data/Shaders/TerrainCompute.hlsl", "initTerrain", "cs_5_0", Shader.ShaderFlags);
ComputeShader initTerrain = new ComputeShader(_context.DirectX.Device, shaderByteCode);
shaderByteCode.Dispose();
shaderByteCode = ShaderBytecode.CompileFromFile(@"Data/Shaders/TerrainCompute.hlsl", "initWater", "cs_5_0", Shader.ShaderFlags);
ComputeShader initWater = new ComputeShader(_context.DirectX.Device, shaderByteCode);
shaderByteCode.Dispose();
shaderByteCode = ShaderBytecode.CompileFromFile(@"Data/Shaders/TerrainCompute.hlsl", "applyRandomDisplacement", "cs_5_0", Shader.ShaderFlags);
_baseTerrainGeneration = new ComputeShader(_context.DirectX.Device, shaderByteCode);
shaderByteCode.Dispose();
shaderByteCode = ShaderBytecode.CompileFromFile(@"Data/Shaders/TerrainCompute.hlsl", "flowsCalculation", "cs_5_0", Shader.ShaderFlags);
_flowsCalculation = new ComputeShader(_context.DirectX.Device, shaderByteCode);
shaderByteCode.Dispose();
shaderByteCode = ShaderBytecode.CompileFromFile(@"Data/Shaders/TerrainCompute.hlsl", "updateWaterLevel", "cs_5_0", Shader.ShaderFlags);
_updateWaterLevel = new ComputeShader(_context.DirectX.Device, shaderByteCode);
shaderByteCode.Dispose();
Texture2DDescription textureDescription = new Texture2DDescription
{
ArraySize = 1,
BindFlags = BindFlags.ShaderResource | BindFlags.UnorderedAccess,
CpuAccessFlags = CpuAccessFlags.None,
Format = Format.R32_Float,
Height = TextureSize,
Width = TextureSize,
MipLevels = 1,
OptionFlags = ResourceOptionFlags.None,
SampleDescription = new SampleDescription(1, 0),
Usage = ResourceUsage.Default
};
ConstantBuffer<ComputeData> computeBuffer = new ConstantBuffer<ComputeData>(_context);
_context.DirectX.DeviceContext.ComputeShader.SetConstantBuffer(1, computeBuffer.Buffer);
foreach (Face face in _faces)
{
Texture2D terrainTexture = new Texture2D(_context.DirectX.Device, textureDescription);
face.TerrainSrv = new ShaderResourceView(_context.DirectX.Device, terrainTexture);
face.TerrainUav = new UnorderedAccessView(_context.DirectX.Device, terrainTexture);
terrainTexture.Dispose();
Texture2D waterTexture = new Texture2D(_context.DirectX.Device, textureDescription);
face.WaterSrv = new ShaderResourceView(_context.DirectX.Device, waterTexture);
face.WaterUav = new UnorderedAccessView(_context.DirectX.Device, waterTexture);
waterTexture.Dispose();
Texture2D flowsTexture = new Texture2D(_context.DirectX.Device, textureDescription);
face.FlowsLeftUav = new UnorderedAccessView(_context.DirectX.Device, flowsTexture);
flowsTexture.Dispose();
flowsTexture = new Texture2D(_context.DirectX.Device, textureDescription);
face.FlowsTopUav = new UnorderedAccessView(_context.DirectX.Device, flowsTexture);
flowsTexture.Dispose();
flowsTexture = new Texture2D(_context.DirectX.Device, textureDescription);
face.FlowsRightUav = new UnorderedAccessView(_context.DirectX.Device, flowsTexture);
flowsTexture.Dispose();
flowsTexture = new Texture2D(_context.DirectX.Device, textureDescription);
face.FlowsBottomUav = new UnorderedAccessView(_context.DirectX.Device, flowsTexture);
flowsTexture.Dispose();
_context.DirectX.DeviceContext.ComputeShader.SetUnorderedAccessView(0, face.TerrainUav);
_context.DirectX.DeviceContext.ComputeShader.SetUnorderedAccessView(1, face.WaterUav);
_context.DirectX.DeviceContext.ComputeShader.Set(initTerrain);
computeBuffer.Update(new ComputeData(TextureSize - 1 - BatchSize, 0, 0, 0.0f));
_context.DirectX.DeviceContext.Dispatch(TextureSize / BatchSize, TextureSize / BatchSize, 1);
_context.DirectX.DeviceContext.ComputeShader.Set(initWater);
computeBuffer.Update(new ComputeData(TextureSize - 1 - BatchSize, 0, 0, 0.05f));
_context.DirectX.DeviceContext.Dispatch(TextureSize / BatchSize, TextureSize / BatchSize, 1);
_context.DirectX.DeviceContext.ComputeShader.Set(initTerrain);
computeBuffer.Update(new ComputeData(TextureSize - 1 - BatchSize, BatchSize / 2, BatchSize / 2, 0.5f));
_context.DirectX.DeviceContext.Dispatch(TextureSize / BatchSize - 1, TextureSize / BatchSize - 1, 1);
}
_planeBuffer = new ConstantBuffer<PlaneData>(_context);
initTerrain.Dispose();
computeBuffer.Dispose();
}
示例11: SwapBuffers
/// <summary>
///
/// </summary>
/// <param name="syncInterval"></param>
public override void SwapBuffers(int syncInterval)
{
eyeTextures[0].SwapTexture.Commit();
eyeTextures[1].SwapTexture.Commit();
layerEyeFov.Header.Type = OVR.LayerType.EyeFov;
layerEyeFov.Header.Flags = OVR.LayerFlags.None;
layerEyeFov.SensorSampleTime = sampleTime;
for (int i = 0; i < 2; i++) {
layerEyeFov.ColorTexture[i] = eyeTextures[i].SwapTexture.TextureChain;
layerEyeFov.Viewport[i] = eyeTextures[i].ViewportSize;
layerEyeFov.Fov[i] = hmd.DefaultEyeFov[i];
layerEyeFov.RenderPose[i] = eyePoses[i];
}
if (hmd.SubmitFrame(frameIndex, layers) < 0) {
Log.Warning("OculusRiftDisplay SubmitFrame returned error");
}
OVR.SessionStatus sessionStatus;
hmd.GetSessionStatus(out sessionStatus);
if (sessionStatus.ShouldQuit > 0)
Application.Exit();
if (sessionStatus.ShouldRecenter > 0)
hmd.RecenterPose();
frameIndex++;
var mirrorTextureD3D11 = new SharpDX.Direct3D11.Texture2D(mirrorTexture.GetMirrorBufferPtr());
d3dDevice.ImmediateContext.CopyResource(mirrorTextureD3D11, backbufferColor.Surface.Resource);
mirrorTextureD3D11.Dispose();
swapChain.Present(0, PresentFlags.None);
}
示例12: CompileButton_Click
private void CompileButton_Click(object sender, RoutedEventArgs e)
{
//make the width and height flexible
if (paths.Count > 2 && redIndex > -1 && greenIndex > -1 && blueIndex > -1)
{
Device d = new Device(SharpDX.Direct3D.DriverType.Hardware);
ImageLoadInformation loadInfo = new ImageLoadInformation()
{
BindFlags = BindFlags.None,
CpuAccessFlags = CpuAccessFlags.Read,
Format = SharpDX.DXGI.Format.R8G8B8A8_UNorm,
OptionFlags = ResourceOptionFlags.None,
Usage = ResourceUsage.Staging
};
Texture2D red, green, blue,final;
red = Texture2D.FromFile<Texture2D>(d,paths[redIndex],loadInfo);
green = Texture2D.FromFile<Texture2D>(d, paths[greenIndex],loadInfo);
blue = Texture2D.FromFile<Texture2D>(d, paths[blueIndex],loadInfo);
final = new Texture2D(d, new Texture2DDescription()
{
ArraySize = 1,
BindFlags = BindFlags.None,
CpuAccessFlags = CpuAccessFlags.Write,
Format = SharpDX.DXGI.Format.R8G8B8A8_UNorm,
Height = 3456,
MipLevels = 0,
OptionFlags = ResourceOptionFlags.None,
SampleDescription = new SharpDX.DXGI.SampleDescription(1,0),
Usage = ResourceUsage.Staging,
Width = 4608
});
DataBox redDataBox = d.ImmediateContext.MapSubresource(red,0,MapMode.Read,MapFlags.None);
DataBox greenDataBox = d.ImmediateContext.MapSubresource(green, 0, MapMode.Read, MapFlags.None);
DataBox blueDataBox = d.ImmediateContext.MapSubresource(blue, 0, MapMode.Read, MapFlags.None);
DataBox finalDataBox = d.ImmediateContext.MapSubresource(final, 0, MapMode.Write, MapFlags.None);
byte[]
redData = new byte[redDataBox.RowPitch * red.Description.Height],
greenData = new byte[greenDataBox.RowPitch * green.Description.Height],
blueData =new byte[blueDataBox.RowPitch * blue.Description.Height],
finalData = new byte[finalDataBox.RowPitch * final.Description.Height];
Utilities.Read(redDataBox.DataPointer, redData, 0, redData.Length);
Utilities.Read(greenDataBox.DataPointer, greenData, 0, greenData.Length);
Utilities.Read(blueDataBox.DataPointer, blueData, 0, blueData.Length);
for (int x = 0; x < final.Description.Width; x++)
{
for (int y = 0; y < final.Description.Height; y++)
{
int index = (x*4) + (y * finalDataBox.RowPitch);
finalData[index] = redData[index];
finalData[index + 1] = greenData[index];
finalData[index + 2] = blueData[index];
finalData[index + 3] = 255;//A
}
}
Utilities.Write(finalDataBox.DataPointer, finalData, 0, finalData.Length);
d.ImmediateContext.UnmapSubresource(red, 0);
d.ImmediateContext.UnmapSubresource(green, 0);
d.ImmediateContext.UnmapSubresource(blue, 0);
d.ImmediateContext.UnmapSubresource(final, 0);
Texture2D.ToFile(d.ImmediateContext, final, ImageFileFormat.Png, "C:\\dan\\projectmedia\\BumpMap\\final.png");
final.Dispose();
red.Dispose();
green.Dispose();
blue.Dispose();
d.Dispose();
}
else MessageBox.Show("must choose at least 3 files and select 3 to be the red green and blue channels");
}
示例13: InitializeOculus
//.........这里部分代码省略.........
int textureIndex = eyeTexture.SwapTextureSet.CurrentIndex++;
immediateContext.OutputMerger.SetRenderTargets(eyeTexture.DepthStencilView, eyeTexture.RenderTargetViews[textureIndex]);
immediateContext.ClearRenderTargetView(eyeTexture.RenderTargetViews[textureIndex], Color.Black);
immediateContext.ClearDepthStencilView(eyeTexture.DepthStencilView, DepthStencilClearFlags.Depth | DepthStencilClearFlags.Stencil, 1.0f, 0);
immediateContext.Rasterizer.SetViewport(eyeTexture.Viewport);
//added a custom rasterizer
immediateContext.Rasterizer.State = rasterizerState;
// Retrieve the eye rotation quaternion and use it to calculate the LookAt direction and the LookUp direction.
Quaternion rotationQuaternion = SharpDXHelpers.ToQuaternion(eyePoses[eyeIndex].Orientation);
Matrix rotationMatrix = Matrix.RotationQuaternion(rotationQuaternion);
Vector3 lookUp = Vector3.Transform(new Vector3(0, -1, 0), rotationMatrix).ToVector3();
Vector3 lookAt = Vector3.Transform(new Vector3(0, 0, 1), rotationMatrix).ToVector3();
Vector3 viewPosition = position - eyePoses[eyeIndex].Position.ToVector3();
//use this to get the first rotation to goal
Matrix world = Matrix.Scaling(1.0f) /** Matrix.RotationX(timeSinceStart*0.2f) */* Matrix.RotationY(timeSinceStart * 2 / 10f) /** Matrix.RotationZ(timeSinceStart*3/10f)*/;
Matrix viewMatrix = Matrix.LookAtRH(viewPosition, viewPosition + lookAt, lookUp);
Matrix projectionMatrix = OVR.ovrMatrix4f_Projection(eyeTexture.FieldOfView, 0.1f, 10.0f, OVR.ProjectionModifier.None).ToMatrix();
projectionMatrix.Transpose();
Matrix worldViewProjection = world * viewMatrix * projectionMatrix;
worldViewProjection.Transpose();
// Update the transformation matrix.
immediateContext.UpdateSubresource(ref worldViewProjection, constantBuffer);
// Draw the cube
//immediateContext.Draw(vertices.Length/2, 0);
immediateContext.DrawIndexed(indices.Length, 0, 0);
}
hmd.SubmitFrame(0, layers);
immediateContext.CopyResource(mirrorTextureD3D11, backBuffer);
swapChain.Present(0, PresentFlags.None);
if (newTextureArrived == true)
{
newTextureArrived = false;
DataBox map = device.ImmediateContext.MapSubresource(myTexture, 0, MapMode.WriteDiscard, SharpDX.Direct3D11.MapFlags.None);
//load the BitMapSource with appropriate formating (Format32bppPRGBA)
SharpDX.WIC.BitmapSource bitMap = LoadBitmap(new SharpDX.WIC.ImagingFactory(), streamTexture);
//string newFile = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) + @"\img_merged.jpg";
//SharpDX.WIC.BitmapSource bitMap = LoadBitmapFromFile(new SharpDX.WIC.ImagingFactory(), newFile);
int width = bitMap.Size.Width;
int height = bitMap.Size.Height;
int stride = bitMap.Size.Width * 4;
bitMap.CopyPixels(stride, map.DataPointer, height * stride);
device.ImmediateContext.UnmapSubresource(myTexture, 0);
//bitMap.Dispose();
streamTexture.Seek(0, SeekOrigin.Begin);
}
});
#endregion
// Release all resources
inputLayout.Dispose();
constantBuffer.Dispose();
indexBuffer.Dispose();
vertexBuffer.Dispose();
inputLayout.Dispose();
shaderSignature.Dispose();
pixelShader.Dispose();
pixelShaderByteCode.Dispose();
vertexShader.Dispose();
vertexShaderByteCode.Dispose();
mirrorTextureD3D11.Dispose();
layers.Dispose();
eyeTextures[0].Dispose();
eyeTextures[1].Dispose();
immediateContext.ClearState();
immediateContext.Flush();
immediateContext.Dispose();
depthStencilState.Dispose();
depthStencilView.Dispose();
depthBuffer.Dispose();
backBufferRenderTargetView.Dispose();
backBuffer.Dispose();
swapChain.Dispose();
factory.Dispose();
// Disposing the device, before the hmd, will cause the hmd to fail when disposing.
// Disposing the device, after the hmd, will cause the dispose of the device to fail.
// It looks as if the hmd steals ownership of the device and destroys it, when it's shutting down.
// device.Dispose();
hmd.Dispose();
oculus.Dispose();
}