void GenerateIfRequired() { if (_buffer != null) { return; } // TODO: To use Immutable resources we would need to delay creation of // the Buffer until SetData() and recreate them if set more than once. var accessflags = SharpDX.Direct3D11.CpuAccessFlags.None; var usage = SharpDX.Direct3D11.ResourceUsage.Default; if (_isDynamic) { accessflags |= SharpDX.Direct3D11.CpuAccessFlags.Write; usage = SharpDX.Direct3D11.ResourceUsage.Dynamic; } _buffer = new SharpDX.Direct3D11.Buffer(GraphicsDevice._d3dDevice, VertexDeclaration.VertexStride * VertexCount, usage, SharpDX.Direct3D11.BindFlags.VertexBuffer, accessflags, SharpDX.Direct3D11.ResourceOptionFlags.None, 0 // StructureSizeInBytes ); _binding = new SharpDX.Direct3D11.VertexBufferBinding(_buffer, VertexDeclaration.VertexStride, 0); }
private void GenerateIfRequired() { if (_buffer != null) { return; } // TODO: To use true Immutable resources we would need to delay creation of // the Buffer until SetData() and recreate them if set more than once. var accessflags = SharpDX.Direct3D11.CpuAccessFlags.None; var resUsage = SharpDX.Direct3D11.ResourceUsage.Default; if (IsDynamic) { accessflags |= SharpDX.Direct3D11.CpuAccessFlags.Write; resUsage = SharpDX.Direct3D11.ResourceUsage.Dynamic; } _buffer = new SharpDX.Direct3D11.Buffer( GraphicsDevice._d3dDevice, Capacity * ElementType.TypeSize(), resUsage, SharpDX.Direct3D11.BindFlags.IndexBuffer, accessflags, SharpDX.Direct3D11.ResourceOptionFlags.None, 0); // StructureSizeInBytes }
protected override void Dispose(bool disposing) { if (!IsDisposed) { #if DIRECTX if (disposing) { if (_buffer != null) { _buffer.Dispose(); _buffer = null; } } #elif PSM //Do nothing _buffer = null; #elif !PORTABLE GraphicsDevice.AddDisposeAction(() => { GL.DeleteBuffers(1, ref ibo); GraphicsExtensions.CheckGLError(); }); #endif } base.Dispose(disposing); }
protected IndexBuffer(GraphicsDevice graphicsDevice, IndexElementSize indexElementSize, int indexCount, BufferUsage usage, bool dynamic) { if (graphicsDevice == null) { throw new ArgumentNullException("GraphicsDevice is null"); } this.GraphicsDevice = graphicsDevice; this.IndexElementSize = indexElementSize; this.IndexCount = indexCount; this.BufferUsage = usage; _isDynamic = dynamic; #if DIRECTX GenerateIfRequired(); #elif PSM if (indexElementSize != IndexElementSize.SixteenBits) { throw new NotImplementedException("PSS Currently only supports ushort (SixteenBits) index elements"); } _buffer = new ushort[indexCount]; #elif !PORTABLE Threading.BlockOnUIThread(GenerateIfRequired); #endif }
void GenerateIfRequired() { if (_buffer != null) { return; } // TODO: To use true Immutable resources we would need to delay creation of // the Buffer until SetData() and recreate them if set more than once. var sizeInBytes = IndexCount * (this.IndexElementSize == IndexElementSize.SixteenBits ? 2 : 4); var accessflags = SharpDX.Direct3D11.CpuAccessFlags.None; var resUsage = SharpDX.Direct3D11.ResourceUsage.Default; if (_isDynamic) { accessflags |= SharpDX.Direct3D11.CpuAccessFlags.Write; resUsage = SharpDX.Direct3D11.ResourceUsage.Dynamic; } _buffer = new SharpDX.Direct3D11.Buffer(GraphicsDevice._d3dDevice, sizeInBytes, resUsage, SharpDX.Direct3D11.BindFlags.IndexBuffer, accessflags, SharpDX.Direct3D11.ResourceOptionFlags.None, 0 // StructureSizeInBytes ); }
/// <summary> /// Initializes a new instance of the <see cref="MeshCache"/> class. /// </summary> /// <param name="vertexBuffer">The vertex buffer.</param> /// <param name="tagGroups">The tag groups.</param> public MeshCache(DXBuffer vertexBuffer, IEnumerable<TagGroup> tagGroups) { _vertexBuffer = vertexBuffer; _tagGroups = tagGroups; IsPrelit = false; _localMatrix = DXMatrix.Identity; }
/// <summary> /// Initializes a new instance of the <see cref="MeshCache"/> class. /// </summary> /// <param name="vertexBuffer">The vertex buffer.</param> /// <param name="tagGroups">The tag groups.</param> /// <param name="localMatrix">The local matrix.</param> public MeshCache(DXBuffer vertexBuffer, IEnumerable<TagGroup> tagGroups, DXMatrix localMatrix) { _vertexBuffer = vertexBuffer; _tagGroups = tagGroups; IsPrelit = false; _localMatrix = localMatrix; }
protected IndexBuffer(GraphicsDevice graphicsDevice, IndexElementSize indexElementSize, int indexCount, BufferUsage bufferUsage, bool dynamic) { if (graphicsDevice == null) { throw new ArgumentNullException("Graphics Device Cannot Be Null"); } this.graphicsDevice = graphicsDevice; this.IndexElementSize = indexElementSize; this.IndexCount = indexCount; this.BufferUsage = bufferUsage; var sizeInBytes = indexCount * (this.IndexElementSize == IndexElementSize.SixteenBits ? 2 : 4); _isDynamic = dynamic; #if DIRECTX // TODO: To use true Immutable resources we would need to delay creation of // the Buffer until SetData() and recreate them if set more than once. var accessflags = SharpDX.Direct3D11.CpuAccessFlags.None; var usage = SharpDX.Direct3D11.ResourceUsage.Default; if (dynamic) { accessflags |= SharpDX.Direct3D11.CpuAccessFlags.Write; usage = SharpDX.Direct3D11.ResourceUsage.Dynamic; } _buffer = new SharpDX.Direct3D11.Buffer(graphicsDevice._d3dDevice, sizeInBytes, usage, SharpDX.Direct3D11.BindFlags.IndexBuffer, accessflags, SharpDX.Direct3D11.ResourceOptionFlags.None, 0 // StructureSizeInBytes ); #elif PSS if (indexElementSize != IndexElementSize.SixteenBits) { throw new NotImplementedException("PSS Currently only supports ushort (SixteenBits) index elements"); } _buffer = new ushort[indexCount]; #else Threading.BlockOnUIThread(() => { #if IPHONE || ANDROID GL.GenBuffers(1, ref ibo); #else GL.GenBuffers(1, out ibo); #endif GraphicsExtensions.CheckGLError(); GL.BindBuffer(BufferTarget.ElementArrayBuffer, ibo); GraphicsExtensions.CheckGLError(); GL.BufferData(BufferTarget.ElementArrayBuffer, (IntPtr)sizeInBytes, IntPtr.Zero, dynamic ? BufferUsageHint.StreamDraw : BufferUsageHint.StaticDraw); GraphicsExtensions.CheckGLError(); }); #endif }
/// <summary> /// Initializes a new instance of the <see cref="MeshCache"/> class. /// </summary> /// <param name="vertexBuffer">The vertex buffer.</param> /// <param name="tagGroups">The tag groups.</param> /// <param name="localMatrix">The local matrix.</param> /// <param name="isPrelit">if set to <c>true</c> [is prelit].</param> /// <param name="tag">The tag.</param> public MeshCache(DXBuffer vertexBuffer, IEnumerable<TagGroup> tagGroups, DXMatrix localMatrix, bool isPrelit, int? tag) { _vertexBuffer = vertexBuffer; _tagGroups = tagGroups; _localMatrix = localMatrix; IsPrelit = isPrelit; Tag = tag; }
private void InitializeTriangle() { triangleVertexBuffer = SharpDX.Direct3D11.Buffer.Create <SharpDX.Vector3>(d3dDevice, SharpDX.Direct3D11.BindFlags.VertexBuffer, vertices); idexBuffer = SharpDX.Direct3D11.Buffer.Create <int>(d3dDevice, SharpDX.Direct3D11.BindFlags.IndexBuffer, indexes); constBuffer = new SharpDX.Direct3D11.Buffer(d3dDevice, SharpDX.Utilities.SizeOf <SharpDX.Color4>(), SharpDX.Direct3D11.ResourceUsage.Default, SharpDX.Direct3D11.BindFlags.ConstantBuffer, SharpDX.Direct3D11.CpuAccessFlags.None, SharpDX.Direct3D11.ResourceOptionFlags.None, 0); SharpDX.Color4 color = new SharpDX.Color4(1f, 0f, 1f, 1); d3dDeviceContext.UpdateSubresource(ref color, constBuffer); }
private void PlatformGetData <T>(int offsetInBytes, T[] data, int startIndex, int elementCount, int vertexStride) where T : struct { GenerateIfRequired(); if (_isDynamic) { throw new NotImplementedException(); } else { var deviceContext = GraphicsDevice._d3dContext; // Copy the buffer to a staging resource var stagingDesc = _buffer.Description; stagingDesc.BindFlags = SharpDX.Direct3D11.BindFlags.None; stagingDesc.CpuAccessFlags = SharpDX.Direct3D11.CpuAccessFlags.Read | SharpDX.Direct3D11.CpuAccessFlags.Write; stagingDesc.Usage = SharpDX.Direct3D11.ResourceUsage.Staging; stagingDesc.OptionFlags = SharpDX.Direct3D11.ResourceOptionFlags.None; using (var stagingBuffer = new SharpDX.Direct3D11.Buffer(GraphicsDevice._d3dDevice, stagingDesc)) { lock (GraphicsDevice._d3dContext) deviceContext.CopyResource(_buffer, stagingBuffer); int TsizeInBytes = SharpDX.Utilities.SizeOf <T>(); var dataHandle = GCHandle.Alloc(data, GCHandleType.Pinned); try { var startBytes = startIndex * TsizeInBytes; var dataPtr = (IntPtr)(dataHandle.AddrOfPinnedObject().ToInt64() + startBytes); lock (GraphicsDevice._d3dContext) { // Map the staging resource to a CPU accessible memory var box = deviceContext.MapSubresource(stagingBuffer, 0, SharpDX.Direct3D11.MapMode.Read, SharpDX.Direct3D11.MapFlags.None); if (vertexStride == TsizeInBytes) { SharpDX.Utilities.CopyMemory(dataPtr, box.DataPointer + offsetInBytes, vertexStride * elementCount); } else { for (int i = 0; i < elementCount; i++) { SharpDX.Utilities.CopyMemory(dataPtr + i * TsizeInBytes, box.DataPointer + i * vertexStride + offsetInBytes, TsizeInBytes); } } // Make sure that we unmap the resource in case of an exception deviceContext.UnmapSubresource(stagingBuffer, 0); } } finally { dataHandle.Free(); } } } }
private void PlatformInitialize() { // Allocate the hardware constant buffer. var desc = new SharpDX.Direct3D11.BufferDescription(); desc.SizeInBytes = _buffer.Length; desc.Usage = SharpDX.Direct3D11.ResourceUsage.Default; desc.BindFlags = SharpDX.Direct3D11.BindFlags.ConstantBuffer; desc.CpuAccessFlags = SharpDX.Direct3D11.CpuAccessFlags.None; lock (GraphicsDevice._d3dContext) _cbuffer = new SharpDX.Direct3D11.Buffer(GraphicsDevice._d3dDevice, desc); }
void InitializeP() { int N = cc.c.N; const int INIT_THREAD_GROUPS = 256; PBuf = gpu.CreateBufferRW((2 + INIT_THREAD_GROUPS) * N, 4, 1); // for betaList[] and affinityFactor[] cc.c.chacedP = false; using (var sd = gpu.LoadShader("TsneDx.InitializeP.cso")) using (var sd3 = gpu.LoadShader("TsneDx.InitializeP3.cso")) { // Calcualtes the distanceFactor[]. gpu.SetShader(sd3); cc.c.cmd = 1; cc.c.groupNumber = 64; for (int bIdx = 0; bIdx < N; bIdx += cc.c.groupNumber) { cc.c.blockIdx = bIdx; cc.Upload(); gpu.Run(cc.c.groupNumber); } cc.c.cmd = 2; // cc.c.groupNumber, groupMax[0..groupNumber] are the maximal values of matrix sub-section. cc.Upload(); gpu.Run(); // Calculates the betaList[]. gpu.SetShader(sd3); cc.c.cmd = 3; cc.c.groupNumber = INIT_THREAD_GROUPS; for (int bIdx = 0; bIdx < N; bIdx += cc.c.groupNumber) { cc.c.blockIdx = bIdx; cc.Upload(); gpu.Run(cc.c.groupNumber); } // calculates the affinityFactor[] gpu.SetShader(sd3); cc.c.cmd = 4; cc.c.groupNumber = 128; // groupNumber must be smaller than GroupSize as required by next command. for (int bIdx = 0; bIdx < N; bIdx += cc.c.groupNumber) { cc.c.blockIdx = bIdx; cc.Upload(); gpu.Run(cc.c.groupNumber); } gpu.SetShader(sd); // cc.c.groupNumber must contains the number of partial sumes in groupMax[]. cc.Upload(); gpu.Run(); } }
private void PlatformInitialize() { // Allocate the hardware constant buffer. var desc = new SharpDX.Direct3D11.BufferDescription(); desc.SizeInBytes = _buffer.Length; desc.Usage = SharpDX.Direct3D11.ResourceUsage.Default; desc.BindFlags = SharpDX.Direct3D11.BindFlags.ConstantBuffer; desc.CpuAccessFlags = SharpDX.Direct3D11.CpuAccessFlags.None; lock (GraphicsDevice._d3dContext) _cbuffer = new SharpDX.Direct3D11.Buffer(GraphicsDevice._d3dDevice, desc); }
protected VertexBuffer(GraphicsDevice graphicsDevice, VertexDeclaration vertexDeclaration, int vertexCount, BufferUsage bufferUsage, bool dynamic) { if (graphicsDevice == null) { throw new ArgumentNullException("Graphics Device Cannot Be null"); } this.GraphicsDevice = graphicsDevice; this.VertexDeclaration = vertexDeclaration; this.VertexCount = vertexCount; this.BufferUsage = bufferUsage; // Make sure the graphics device is assigned in the vertex declaration. if (vertexDeclaration.GraphicsDevice != graphicsDevice) { vertexDeclaration.GraphicsDevice = graphicsDevice; } _isDynamic = dynamic; #if DIRECTX // TODO: To use Immutable resources we would need to delay creation of // the Buffer until SetData() and recreate them if set more than once. var accessflags = SharpDX.Direct3D11.CpuAccessFlags.None; var usage = SharpDX.Direct3D11.ResourceUsage.Default; if (dynamic) { accessflags |= SharpDX.Direct3D11.CpuAccessFlags.Write; usage = SharpDX.Direct3D11.ResourceUsage.Dynamic; } _buffer = new SharpDX.Direct3D11.Buffer(graphicsDevice._d3dDevice, vertexDeclaration.VertexStride * vertexCount, usage, SharpDX.Direct3D11.BindFlags.VertexBuffer, accessflags, SharpDX.Direct3D11.ResourceOptionFlags.None, 0 // StructureSizeInBytes ); _binding = new SharpDX.Direct3D11.VertexBufferBinding(_buffer, VertexDeclaration.VertexStride, 0); #elif PSM //Do nothing, we cannot create the storage array yet #else Threading.BlockOnUIThread(GenerateIfRequired); #endif }
void CalculateP() { int N = cc.c.N; distanceBuf = gpu.CreateBufferRW((N * N - N) / 2, 4, 0); using (var shader = gpu.LoadShader("TsneDx.CreateDistanceCache.cso")) { gpu.SetShader(shader); int groupNr = 256; for (int i = 0; i < N; i += groupNr) { cc.c.blockIdx = i; cc.Upload(); gpu.Run(groupNr); } } PBuf = gpu.CreateBufferRW(N * N, 4, 1); cc.c.chacedP = true; using (var sd = gpu.LoadShader("TsneDx.CalculateP.cso")) { // Calculate the squared distance matrix in to P using (var sd2 = gpu.LoadShader("TsneDx.CalculatePFromCache.cso")) { gpu.SetShader(sd2); gpu.Run(64); } gpu.SetShader(sd); // Normalize and symmetrizing the distance matrix cc.c.cmd = 4; cc.Upload(); gpu.Run(); // Convert the matrix to affinities. cc.c.cmd = 2; cc.c.groupNumber = 4; for (int bIdx = 0; bIdx < N; bIdx += cc.c.groupNumber * GpuGroupSize) { cc.c.blockIdx = bIdx; cc.Upload(); gpu.Run(cc.c.groupNumber); } // Normalize and symmetrizing the affinity matrix gpu.SetShader(sd); cc.c.cmd = 3; cc.Upload(); gpu.Run(); } }
void CreatedCachedStagingBuffer() { if (_cachedStagingBuffer != null) { return; } var stagingDesc = _buffer.Description; stagingDesc.BindFlags = SharpDX.Direct3D11.BindFlags.None; stagingDesc.CpuAccessFlags = SharpDX.Direct3D11.CpuAccessFlags.Read | SharpDX.Direct3D11.CpuAccessFlags.Write; stagingDesc.Usage = SharpDX.Direct3D11.ResourceUsage.Staging; stagingDesc.OptionFlags = SharpDX.Direct3D11.ResourceOptionFlags.None; _cachedStagingBuffer = new SharpDX.Direct3D11.Buffer(GraphicsDevice._d3dDevice, stagingDesc); }
/// <summary> /// Creates device-based resources to store a constant buffer, cube /// geometry, and vertex and pixel shaders. In some cases this will also /// store a geometry shader. /// </summary> public void CreateDeviceDependentResourcesAsync() { ReleaseDeviceDependentResources(); // Create a constant buffer to store the model matrix. modelConstantBuffer = this.ToDispose(SharpDX.Direct3D11.Buffer.Create( deviceResources.D3DDevice, SharpDX.Direct3D11.BindFlags.ConstantBuffer, ref modelConstantBufferData)); // Create the Texture, ShaderResource and Sampler state lock (thisLock) { m_texture = this.ToDispose(new SharpDX.Direct3D11.Texture2D(deviceResources.D3DDevice, new SharpDX.Direct3D11.Texture2DDescription() { Format = SharpDX.DXGI.Format.R8G8B8A8_UNorm, Width = (int)m_mediaPlayer.PlaybackSession.NaturalVideoWidth, //Width Height = (int)m_mediaPlayer.PlaybackSession.NaturalVideoHeight, //Height MipLevels = 1, ArraySize = 1, BindFlags = SharpDX.Direct3D11.BindFlags.ShaderResource | SharpDX.Direct3D11.BindFlags.RenderTarget, Usage = SharpDX.Direct3D11.ResourceUsage.Default, CpuAccessFlags = SharpDX.Direct3D11.CpuAccessFlags.None, SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0), OptionFlags = SharpDX.Direct3D11.ResourceOptionFlags.None })); m_textureView = this.ToDispose(new SharpDX.Direct3D11.ShaderResourceView(deviceResources.D3DDevice, m_texture)); } m_quadTextureSamplerState = this.ToDispose(new SharpDX.Direct3D11.SamplerState(deviceResources.D3DDevice, new SharpDX.Direct3D11.SamplerStateDescription() { Filter = SharpDX.Direct3D11.Filter.Anisotropic, AddressU = SharpDX.Direct3D11.TextureAddressMode.Clamp, AddressV = SharpDX.Direct3D11.TextureAddressMode.Clamp, AddressW = SharpDX.Direct3D11.TextureAddressMode.Clamp, MaximumAnisotropy = 3, MinimumLod = 0, MaximumLod = 3, MipLodBias = 0, BorderColor = new SharpDX.Mathematics.Interop.RawColor4(0, 0, 0, 0), ComparisonFunction = SharpDX.Direct3D11.Comparison.Never })); CreateD3D11Surface(); LoadShaders(); }
public override void Dispose() { #if DIRECTX if (_buffer != null) { _buffer.Dispose(); _buffer = null; } #elif PSS //Do nothing _vertexArray = null; #else GL.DeleteBuffers(1, ref vbo); GraphicsExtensions.CheckGLError(); #endif base.Dispose(); }
protected IndexBuffer(GraphicsDevice graphicsDevice, IndexElementSize indexElementSize, int indexCount, BufferUsage usage, bool dynamic) { if (graphicsDevice == null) { throw new ArgumentNullException("GraphicsDevice is null"); } this.GraphicsDevice = graphicsDevice; this.IndexElementSize = indexElementSize; this.IndexCount = indexCount; this.BufferUsage = usage; var sizeInBytes = indexCount * (this.IndexElementSize == IndexElementSize.SixteenBits ? 2 : 4); _isDynamic = dynamic; #if DIRECTX // TODO: To use true Immutable resources we would need to delay creation of // the Buffer until SetData() and recreate them if set more than once. var accessflags = SharpDX.Direct3D11.CpuAccessFlags.None; var resUsage = SharpDX.Direct3D11.ResourceUsage.Default; if (dynamic) { accessflags |= SharpDX.Direct3D11.CpuAccessFlags.Write; resUsage = SharpDX.Direct3D11.ResourceUsage.Dynamic; } _buffer = new SharpDX.Direct3D11.Buffer(graphicsDevice._d3dDevice, sizeInBytes, resUsage, SharpDX.Direct3D11.BindFlags.IndexBuffer, accessflags, SharpDX.Direct3D11.ResourceOptionFlags.None, 0 // StructureSizeInBytes ); #elif PSM if (indexElementSize != IndexElementSize.SixteenBits) { throw new NotImplementedException("PSS Currently only supports ushort (SixteenBits) index elements"); } _buffer = new ushort[indexCount]; #else Threading.BlockOnUIThread(GenerateIfRequired); #endif }
private unsafe void PlatformGetData(int byteOffset, Span <byte> destination) { if (_buffer == null) { return; } if (IsDynamic) { throw new NotImplementedException(); } // Copy the texture to a staging resource var stagingDesc = _buffer.Description; stagingDesc.BindFlags = SharpDX.Direct3D11.BindFlags.None; stagingDesc.CpuAccessFlags = SharpDX.Direct3D11.CpuAccessFlags.Read | SharpDX.Direct3D11.CpuAccessFlags.Write; stagingDesc.Usage = SharpDX.Direct3D11.ResourceUsage.Staging; stagingDesc.OptionFlags = SharpDX.Direct3D11.ResourceOptionFlags.None; using (var stagingBuffer = new SharpDX.Direct3D11.Buffer(GraphicsDevice._d3dDevice, stagingDesc)) { var deviceContext = GraphicsDevice._d3dContext; lock (deviceContext) { deviceContext.CopyResource(_buffer, stagingBuffer); // Map the staging resource to CPU accessible memory try { var box = deviceContext.MapSubresource( stagingBuffer, 0, SharpDX.Direct3D11.MapMode.Read, SharpDX.Direct3D11.MapFlags.None); int srcBytes = Count * ElementType.TypeSize(); var byteSrc = new ReadOnlySpan <byte>((void *)(box.DataPointer + byteOffset), srcBytes); byteSrc.Slice(0, destination.Length).CopyTo(destination); } finally { // Make sure that we unmap the resource in case of an exception deviceContext.UnmapSubresource(stagingBuffer, 0); } } } }
public GpuBufferArray( int elementSize, int elementCount, GpuDevice device, GpuResourceInfo resourceInfo) : base(device, elementCount * elementSize, resourceInfo) { ElementSize = elementSize; ElementCount = elementCount; mResource = new SharpDX.Direct3D11.Buffer(GpuDevice.Device, new SharpDX.Direct3D11.BufferDescription() { BindFlags = GpuConvert.ToBindUsage(ResourceInfo.BindUsage), CpuAccessFlags = GpuConvert.ToCpuAccessFlag(ResourceInfo.CpuAccessFlag), OptionFlags = SharpDX.Direct3D11.ResourceOptionFlags.BufferStructured, SizeInBytes = SizeInBytes, StructureByteStride = ElementSize, Usage = GpuConvert.ToHeapType(ResourceInfo.HeapType) }); }
private void Initialize() { #if DIRECTX // Allocate the hardware constant buffer. var desc = new SharpDX.Direct3D11.BufferDescription(); desc.SizeInBytes = _buffer.Length; desc.Usage = SharpDX.Direct3D11.ResourceUsage.Default; desc.BindFlags = SharpDX.Direct3D11.BindFlags.ConstantBuffer; desc.CpuAccessFlags = SharpDX.Direct3D11.CpuAccessFlags.None; _cbuffer = new SharpDX.Direct3D11.Buffer(graphicsDevice._d3dDevice, desc); #elif OPENGL var data = new byte[_parameters.Length]; for (var i = 0; i < _parameters.Length; i++) { data[i] = (byte)(_parameters[i] | _offsets[i]); } HashKey = MonoGame.Utilities.Hash.ComputeHash(data); #endif }
public GpuBuffer( int bufferSize, int elementSize, GpuDevice device, GpuResourceInfo resourceInfo) : base(device, bufferSize, resourceInfo) { ElementSize = elementSize; mResource = new SharpDX.Direct3D11.Buffer(GpuDevice.Device, new SharpDX.Direct3D11.BufferDescription() { BindFlags = GpuConvert.ToBindUsage(ResourceInfo.BindUsage), CpuAccessFlags = GpuConvert.ToCpuAccessFlag(ResourceInfo.CpuAccessFlag), OptionFlags = SharpDX.Direct3D11.ResourceOptionFlags.None, SizeInBytes = SizeInBytes, StructureByteStride = ElementSize, Usage = GpuConvert.ToHeapType(ResourceInfo.HeapType) }); Debug.Assert(bufferSize % elementSize == 0); }
public static void RenderQuadTree2(SharpDevice device, SharpShader shader, SharpDX.Direct3D11.Buffer buffer, Matrix viewProjection) { if (secondQuadTreeMesh == null) { return; } secondQuadtreeRenderData.worldViewProjection = quadTreeTranslation * viewProjection; device.SetFillModeSolid(); device.SetCullModeNone(); device.SetDefaultBlendState(); device.ApplyRasterState(); device.UpdateAllStates(); device.UpdateData(buffer, secondQuadtreeRenderData); device.DeviceContext.VertexShader.SetConstantBuffer(0, buffer); shader.Apply(); secondQuadTreeMesh.Draw(); }
public async void CreateDeviceDependentResourcesAsync() { ReleaseDeviceDependentResources(); var folder = Windows.ApplicationModel.Package.Current.InstalledLocation; var vertexShaderFilename = @"Content\Shaders\Camera Testing\VprtVertexShader.cso"; var vertexShaderBytecode = await DirectXHelper.ReadDataAsync(await folder.GetFileAsync(vertexShaderFilename)); vertexShader = ToDispose(new SharpDX.Direct3D11.VertexShader(deviceResources.D3DDevice, vertexShaderBytecode)); SharpDX.Direct3D11.InputElement[] vertexDescription = { new SharpDX.Direct3D11.InputElement("POSITION", 0, SharpDX.DXGI.Format.R32G32B32_Float, 0, 0, SharpDX.Direct3D11.InputClassification.PerVertexData, 0), new SharpDX.Direct3D11.InputElement("TEXCOORD", 0, SharpDX.DXGI.Format.R32G32_Float, 12, 0, SharpDX.Direct3D11.InputClassification.PerVertexData, 0) }; inputLayout = ToDispose(new SharpDX.Direct3D11.InputLayout(deviceResources.D3DDevice, vertexShaderBytecode, vertexDescription)); var pixelShaderBytecode = await DirectXHelper.ReadDataAsync(await folder.GetFileAsync(@"Content\Shaders\Camera Testing\PixelShader.cso")); pixelShader = ToDispose(new SharpDX.Direct3D11.PixelShader(deviceResources.D3DDevice, pixelShaderBytecode)); VertexPositionUV[] vertices = { new VertexPositionUV(new Vector3(-0.2f, -0.2f, 0.0f), new Vector2(0.0f, 0.0f)), new VertexPositionUV(new Vector3(0.2f, -0.2f, 0.0f), new Vector2(1.0f, 0.0f)), new VertexPositionUV(new Vector3(0.2f, 0.2f, 0.0f), new Vector2(1.0f, 1.0f)), new VertexPositionUV(new Vector3(-0.2f, 0.2f, 0.0f), new Vector2(0.0f, 1.0f)) }; vertexBuffer = ToDispose(SharpDX.Direct3D11.Buffer.Create(deviceResources.D3DDevice, SharpDX.Direct3D11.BindFlags.VertexBuffer, vertices)); ushort[] indices = { 0, 1, 2, 2, 3, 0 }; indexBuffer = ToDispose(SharpDX.Direct3D11.Buffer.Create(deviceResources.D3DDevice, SharpDX.Direct3D11.BindFlags.IndexBuffer, indices)); modelConstantBuffer = ToDispose(SharpDX.Direct3D11.Buffer.Create(deviceResources.D3DDevice, SharpDX.Direct3D11.BindFlags.ConstantBuffer, ref modelConstantBufferData)); loadingFinished = true; }
/// <summary> /// Creates device-based resources to store a constant buffer, cube /// geometry, and vertex and pixel shaders. In some cases this will also /// store a geometry shader. /// </summary> public async void CreateDeviceDependentResourcesAsync() { ReleaseDeviceDependentResources(); usingVprtShaders = deviceResources.D3DDeviceSupportsVprt; var folder = Windows.ApplicationModel.Package.Current.InstalledLocation; // On devices that do support the D3D11_FEATURE_D3D11_OPTIONS3:: // VPAndRTArrayIndexFromAnyShaderFeedingRasterizer optional feature // we can avoid using a pass-through geometry shader to set the render // target array index, thus avoiding any overhead that would be // incurred by setting the geometry shader stage. var vertexShaderFileName = usingVprtShaders ? "Content\\Shaders\\VPRTVertexShader.cso" : "Content\\Shaders\\VertexShader.cso"; // Load the compiled vertex shader. var vertexShaderByteCode = await DirectXHelper.ReadDataAsync(await folder.GetFileAsync(vertexShaderFileName)); // After the vertex shader file is loaded, create the shader and input layout. vertexShader = this.ToDispose(new SharpDX.Direct3D11.VertexShader( deviceResources.D3DDevice, vertexShaderByteCode)); SharpDX.Direct3D11.InputElement[] vertexDesc = { new SharpDX.Direct3D11.InputElement("POSITION", 0, SharpDX.DXGI.Format.R32G32B32_Float, 0, 0, SharpDX.Direct3D11.InputClassification.PerVertexData, 0), new SharpDX.Direct3D11.InputElement("COLOR", 0, SharpDX.DXGI.Format.R32G32B32_Float, 12, 0, SharpDX.Direct3D11.InputClassification.PerVertexData, 0), }; inputLayout = this.ToDispose(new SharpDX.Direct3D11.InputLayout( deviceResources.D3DDevice, vertexShaderByteCode, vertexDesc)); if (!usingVprtShaders) { // Load the compiled pass-through geometry shader. var geometryShaderByteCode = await DirectXHelper.ReadDataAsync(await folder.GetFileAsync("Content\\Shaders\\GeometryShader.cso")); // After the pass-through geometry shader file is loaded, create the shader. geometryShader = this.ToDispose(new SharpDX.Direct3D11.GeometryShader( deviceResources.D3DDevice, geometryShaderByteCode)); } // Load the compiled pixel shader. var pixelShaderByteCode = await DirectXHelper.ReadDataAsync(await folder.GetFileAsync("Content\\Shaders\\PixelShader.cso")); // After the pixel shader file is loaded, create the shader. pixelShader = this.ToDispose(new SharpDX.Direct3D11.PixelShader( deviceResources.D3DDevice, pixelShaderByteCode)); // Load mesh vertices. Each vertex has a position and a color. // Note that the cube size has changed from the default DirectX app // template. Windows Holographic is scaled in meters, so to draw the // cube at a comfortable size we made the cube width 0.2 m (20 cm). VertexPositionColor[] cubeVertices = { new VertexPositionColor(new Vector3(-0.1f, -0.1f, -0.1f), new Vector3(0.0f, 0.0f, 0.0f)), new VertexPositionColor(new Vector3(-0.1f, -0.1f, 0.1f), new Vector3(0.0f, 0.0f, 1.0f)), new VertexPositionColor(new Vector3(-0.1f, 0.1f, -0.1f), new Vector3(0.0f, 1.0f, 0.0f)), new VertexPositionColor(new Vector3(-0.1f, 0.1f, 0.1f), new Vector3(0.0f, 1.0f, 1.0f)), new VertexPositionColor(new Vector3(0.1f, -0.1f, -0.1f), new Vector3(1.0f, 0.0f, 0.0f)), new VertexPositionColor(new Vector3(0.1f, -0.1f, 0.1f), new Vector3(1.0f, 0.0f, 1.0f)), new VertexPositionColor(new Vector3(0.1f, 0.1f, -0.1f), new Vector3(1.0f, 1.0f, 0.0f)), new VertexPositionColor(new Vector3(0.1f, 0.1f, 0.1f), new Vector3(1.0f, 1.0f, 1.0f)), }; vertexBuffer = this.ToDispose(SharpDX.Direct3D11.Buffer.Create( deviceResources.D3DDevice, SharpDX.Direct3D11.BindFlags.VertexBuffer, cubeVertices)); // Load mesh indices. Each trio of indices represents // a triangle to be rendered on the screen. // For example: 0,2,1 means that the vertices with indexes // 0, 2 and 1 from the vertex buffer compose the // first triangle of this mesh. ushort[] cubeIndices = { 2, 1, 0, // -x 2, 3, 1, 6, 4, 5, // +x 6, 5, 7, 0, 1, 5, // -y 0, 5, 4, 2, 6, 7, // +y 2, 7, 3, 0, 4, 6, // -z 0, 6, 2, 1, 3, 7, // +z 1, 7, 5, }; indexCount = cubeIndices.Length; indexBuffer = this.ToDispose(SharpDX.Direct3D11.Buffer.Create( deviceResources.D3DDevice, SharpDX.Direct3D11.BindFlags.IndexBuffer, cubeIndices)); // Create a constant buffer to store the model matrix. modelConstantBuffer = this.ToDispose(SharpDX.Direct3D11.Buffer.Create( deviceResources.D3DDevice, SharpDX.Direct3D11.BindFlags.ConstantBuffer, ref modelConstantBufferData)); // Once the cube is loaded, the object is ready to be rendered. loadingComplete = true; }
protected VertexBuffer(GraphicsDevice graphicsDevice, VertexDeclaration vertexDeclaration, int vertexCount, BufferUsage bufferUsage, bool dynamic) { if (graphicsDevice == null) { throw new ArgumentNullException("Graphics Device Cannot Be null"); } this.graphicsDevice = graphicsDevice; this.VertexDeclaration = vertexDeclaration; this.VertexCount = vertexCount; this.BufferUsage = bufferUsage; // Make sure the graphics device is assigned in the vertex declaration. if (vertexDeclaration.GraphicsDevice != graphicsDevice) { vertexDeclaration.GraphicsDevice = graphicsDevice; } _isDynamic = dynamic; #if DIRECTX // TODO: To use Immutable resources we would need to delay creation of // the Buffer until SetData() and recreate them if set more than once. var accessflags = SharpDX.Direct3D11.CpuAccessFlags.None; var usage = SharpDX.Direct3D11.ResourceUsage.Default; if (dynamic) { accessflags |= SharpDX.Direct3D11.CpuAccessFlags.Write; usage = SharpDX.Direct3D11.ResourceUsage.Dynamic; } _buffer = new SharpDX.Direct3D11.Buffer(graphicsDevice._d3dDevice, vertexDeclaration.VertexStride * vertexCount, usage, SharpDX.Direct3D11.BindFlags.VertexBuffer, accessflags, SharpDX.Direct3D11.ResourceOptionFlags.None, 0 // StructureSizeInBytes ); _binding = new SharpDX.Direct3D11.VertexBufferBinding(_buffer, VertexDeclaration.VertexStride, 0); #elif PSS //Do nothing, we cannot create the storage array yet #else Threading.BlockOnUIThread(() => { //GLExt.Oes.GenVertexArrays(1, out this.vao); //GLExt.Oes.BindVertexArray(this.vao); #if IPHONE || ANDROID GL.GenBuffers(1, ref this.vbo); #else GL.GenBuffers(1, out this.vbo); #endif GraphicsExtensions.CheckGLError(); GL.BindBuffer(BufferTarget.ArrayBuffer, this.vbo); GraphicsExtensions.CheckGLError(); GL.BufferData(BufferTarget.ArrayBuffer, new IntPtr(vertexDeclaration.VertexStride * vertexCount), IntPtr.Zero, dynamic ? BufferUsageHint.StreamDraw : BufferUsageHint.StaticDraw); GraphicsExtensions.CheckGLError(); }); #endif }
public SkyboxRenderer(Device device) { this.device = device; bufferVs1 = device.CreateBuffer <VsData>(); shader = new Shader(device, "../../Skybox.hlsl", vertexEntry: "VS", pixelEntry: "PS"); }
private void Initialize() { #if DIRECTX // Allocate the hardware constant buffer. var desc = new SharpDX.Direct3D11.BufferDescription(); desc.SizeInBytes = _buffer.Length; desc.Usage = SharpDX.Direct3D11.ResourceUsage.Default; desc.BindFlags = SharpDX.Direct3D11.BindFlags.ConstantBuffer; desc.CpuAccessFlags = SharpDX.Direct3D11.CpuAccessFlags.None; lock (GraphicsDevice._d3dContext) _cbuffer = new SharpDX.Direct3D11.Buffer(GraphicsDevice._d3dDevice, desc); #elif OPENGL var data = new byte[_parameters.Length]; for (var i = 0; i < _parameters.Length; i++) { data[i] = (byte)(_parameters[i] | _offsets[i]); } HashKey = MonoGame.Utilities.Hash.ComputeHash(data); #endif }
internal MeshDrawable(DXBuffer vertexBuffer, IEnumerable<TagGroup> tagGroups) { WorldMatrix = Matrix.Identity; VertexBuffer = vertexBuffer; TagGroups.AddRange(tagGroups.Select(tagGroup => new WeakReference<TagGroup>(tagGroup))); }
/// <summary> /// Creates device-based resources to store a constant buffer, cube /// geometry, and vertex and pixel shaders. In some cases this will also /// store a geometry shader. /// </summary> public async void CreateDeviceDependentResourcesAsync() { ReleaseDeviceDependentResources(); usingVprtShaders = deviceResources.D3DDeviceSupportsVprt; var folder = Windows.ApplicationModel.Package.Current.InstalledLocation; // On devices that do support the D3D11_FEATURE_D3D11_OPTIONS3:: // VPAndRTArrayIndexFromAnyShaderFeedingRasterizer optional feature // we can avoid using a pass-through geometry shader to set the render // target array index, thus avoiding any overhead that would be // incurred by setting the geometry shader stage. var vertexShaderFileName = usingVprtShaders ? "Content\\Shaders\\VPRTVertexShader.cso" : "Content\\Shaders\\VertexShader.cso"; // Load the compiled vertex shader. var vertexShaderByteCode = await DirectXHelper.ReadDataAsync(await folder.GetFileAsync(vertexShaderFileName)); // After the vertex shader file is loaded, create the shader and input layout. vertexShader = this.ToDispose(new SharpDX.Direct3D11.VertexShader( deviceResources.D3DDevice, vertexShaderByteCode)); //TODO: Change VertexDesc to use new structure: VertexPositionTextureCoordinates SharpDX.Direct3D11.InputElement[] vertexDesc = { new SharpDX.Direct3D11.InputElement("POSITION", 0, SharpDX.DXGI.Format.R32G32B32_Float, 0, 0, SharpDX.Direct3D11.InputClassification.PerVertexData, 0), new SharpDX.Direct3D11.InputElement("TEXCOORD", 0, SharpDX.DXGI.Format.R32G32B32_Float, 12, 0, SharpDX.Direct3D11.InputClassification.PerVertexData, 0), }; inputLayout = this.ToDispose(new SharpDX.Direct3D11.InputLayout( deviceResources.D3DDevice, vertexShaderByteCode, vertexDesc)); if (!usingVprtShaders) { // Load the compiled pass-through geometry shader. var geometryShaderByteCode = await DirectXHelper.ReadDataAsync(await folder.GetFileAsync("Content\\Shaders\\GeometryShader.cso")); // After the pass-through geometry shader file is loaded, create the shader. geometryShader = this.ToDispose(new SharpDX.Direct3D11.GeometryShader( deviceResources.D3DDevice, geometryShaderByteCode)); } // Load the compiled pixel shader. var pixelShaderByteCode = await DirectXHelper.ReadDataAsync(await folder.GetFileAsync("Content\\Shaders\\PixelShader.cso")); // After the pixel shader file is loaded, create the shader. pixelShader = this.ToDispose(new SharpDX.Direct3D11.PixelShader( deviceResources.D3DDevice, pixelShaderByteCode)); //TODO: Use a photo editing app to create a texture, like GIMP2 with DDS Plugin, make sure photo width & height divisible by 4, for a cube must be an exact square //used Gimp 2 with DDS Plugin to create a 2000x2000 image and export at .dds file. //in the export options I used BC3_UNorm format, along with automatic MIP levels string textureName2 = "Content\\Textures\\nuwaupian_holding_fire3.dds"; //TODO: Create the SamplerState var samplerStateDescription = new SharpDX.Direct3D11.SamplerStateDescription(); samplerStateDescription.Filter = SharpDX.Direct3D11.Filter.MinMagMipLinear; samplerStateDescription.AddressU = SharpDX.Direct3D11.TextureAddressMode.Wrap; samplerStateDescription.AddressV = SharpDX.Direct3D11.TextureAddressMode.Wrap; samplerStateDescription.AddressW = SharpDX.Direct3D11.TextureAddressMode.Wrap; samplerStateDescription.BorderColor = new SharpDX.Mathematics.Interop.RawColor4(0f, 0f, 0f, 1f); samplerState = new SharpDX.Direct3D11.SamplerState(deviceResources.D3DDevice, samplerStateDescription); //TODO: Use the TextureLoader class to create a bitmap source from a .DDS texture file //Retreived TextureLoader from DirectXTK or DirectText Tool var bitmapSource2 = TextureLoader.LoadBitmap(new SharpDX.WIC.ImagingFactory2(), textureName2); //TODO: Create a Texture Description to describe the texture you'll be using or converting to var textDesc = new SharpDX.Direct3D11.Texture2DDescription() { Width = bitmapSource2.Size.Width, Height = bitmapSource2.Size.Height, ArraySize = 6, BindFlags = SharpDX.Direct3D11.BindFlags.ShaderResource, Usage = SharpDX.Direct3D11.ResourceUsage.Default, CpuAccessFlags = SharpDX.Direct3D11.CpuAccessFlags.None, Format = SharpDX.DXGI.Format.R8G8B8A8_UNorm, MipLevels = 1, OptionFlags = SharpDX.Direct3D11.ResourceOptionFlags.TextureCube, SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0), }; //TODO: Create Shader Resource View var shaderResourceDesc = new SharpDX.Direct3D11.ShaderResourceViewDescription() { Format = textDesc.Format, Dimension = SharpDX.Direct3D.ShaderResourceViewDimension.TextureCube, TextureCube = new SharpDX.Direct3D11.ShaderResourceViewDescription.TextureCubeResource() { MipLevels = textDesc.MipLevels, MostDetailedMip = 0 } }; //TODO: Create 6 pointers for the 6 sides of the cube, each pointing to an 2000x2000 image you want to display IntPtr[] ptrImages = new IntPtr[6]; //TODO: Get the Stride of each image - stride is the size of 1 row pixels int stride = bitmapSource2.Size.Width * 4; //TODO: for each of the 6 pointers, create a buffer to hold the pixels using the DataStream object, using (var buffer = new SharpDX.DataStream(bitmapSource2.Size.Height * stride, true, true)) { //TODO: for each of the 6 data streams, copy the pixels into a buffer // Copy the content of the WIC to the buffer bitmapSource2.CopyPixels(stride, buffer); //TODO: for each of the 6 pointers get the IntPtr to the buffers, taking care not get rid of the buffers, pointers, or datastreams before we can create the texture cube ptrImages[0] = buffer.DataPointer; using (var buffer1 = new SharpDX.DataStream(bitmapSource2.Size.Height * stride, true, true)) { // Copy the content of the WIC to the buffer bitmapSource2.CopyPixels(stride, buffer1); ptrImages[1] = buffer1.DataPointer; using (var buffer2 = new SharpDX.DataStream(bitmapSource2.Size.Height * stride, true, true)) { // Copy the content of the WIC to the buffer bitmapSource2.CopyPixels(stride, buffer2); ptrImages[2] = buffer2.DataPointer; using (var buffer3 = new SharpDX.DataStream(bitmapSource2.Size.Height * stride, true, true)) { // Copy the content of the WIC to the buffer bitmapSource2.CopyPixels(stride, buffer3); ptrImages[3] = buffer3.DataPointer; using (var buffer4 = new SharpDX.DataStream(bitmapSource2.Size.Height * stride, true, true)) { // Copy the content of the WIC to the buffer bitmapSource2.CopyPixels(stride, buffer4); ptrImages[4] = buffer4.DataPointer; using (var buffer5 = new SharpDX.DataStream(bitmapSource2.Size.Height * stride, true, true)) { // Copy the content of the WIC to the buffer bitmapSource2.CopyPixels(stride, buffer5); ptrImages[5] = buffer5.DataPointer; //TODO: create a DataBox of the 6 pixel buffers. The DataBox is the typed array which we described in the TextureDescription and ShaderResource Description to hold the 6 sides var dataRects = new SharpDX.DataBox[] { new SharpDX.DataBox(ptrImages[0], stride, 0), new SharpDX.DataBox(ptrImages[1], stride, 0), new SharpDX.DataBox(ptrImages[2], stride, 0), new SharpDX.DataBox(ptrImages[3], stride, 0), new SharpDX.DataBox(ptrImages[4], stride, 0), new SharpDX.DataBox(ptrImages[5], stride, 0) }; //TODO: Now create the TextureCube var texture2D = new SharpDX.Direct3D11.Texture2D(deviceResources.D3DDevice, textDesc, dataRects); //TODO: Now create the TextureShaderResourceView - which will be used in the PixelShader, after this point we can release all the buffers textureResource = new SharpDX.Direct3D11.ShaderResourceView(deviceResources.D3DDevice, texture2D, shaderResourceDesc); } } } } } } //TODO: Change to VertexPositionCoordinate // Load mesh vertices. Each vertex has a position and a color. // Note that the cube size has changed from the default DirectX app // template. Windows Holographic is scaled in meters, so to draw the // cube at a comfortable size we made the cube width 0.2 m (20 cm). VertexPositionCoordinate[] cubeVertices = { new VertexPositionCoordinate(new Vector3(-0.1f, -0.1f, -0.1f), new Vector3(0.0f, 0.0f, 0.0f)), new VertexPositionCoordinate(new Vector3(-0.1f, -0.1f, 0.1f), new Vector3(0.0f, 0.0f, 1.0f)), new VertexPositionCoordinate(new Vector3(-0.1f, 0.1f, -0.1f), new Vector3(0.0f, 1.0f, 0.0f)), new VertexPositionCoordinate(new Vector3(-0.1f, 0.1f, 0.1f), new Vector3(0.0f, 1.0f, 1.0f)), new VertexPositionCoordinate(new Vector3(0.1f, -0.1f, -0.1f), new Vector3(1.0f, 0.0f, 0.0f)), new VertexPositionCoordinate(new Vector3(0.1f, -0.1f, 0.1f), new Vector3(1.0f, 0.0f, 1.0f)), new VertexPositionCoordinate(new Vector3(0.1f, 0.1f, -0.1f), new Vector3(1.0f, 1.0f, 0.0f)), new VertexPositionCoordinate(new Vector3(0.1f, 0.1f, 0.1f), new Vector3(1.0f, 1.0f, 1.0f)), }; vertexBuffer = this.ToDispose(SharpDX.Direct3D11.Buffer.Create( deviceResources.D3DDevice, SharpDX.Direct3D11.BindFlags.VertexBuffer, cubeVertices)); // Load mesh indices. Each trio of indices represents // a triangle to be rendered on the screen. // For example: 0,2,1 means that the vertices with indexes // 0, 2 and 1 from the vertex buffer compose the // first triangle of this mesh. ushort[] cubeIndices = { 2, 1, 0, // -x 2, 3, 1, 6, 4, 5, // +x 6, 5, 7, 0, 1, 5, // -y 0, 5, 4, 2, 6, 7, // +y 2, 7, 3, 0, 4, 6, // -z 0, 6, 2, 1, 3, 7, // +z 1, 7, 5, }; indexCount = cubeIndices.Length; indexBuffer = this.ToDispose(SharpDX.Direct3D11.Buffer.Create( deviceResources.D3DDevice, SharpDX.Direct3D11.BindFlags.IndexBuffer, cubeIndices)); // Create a constant buffer to store the model matrix. modelConstantBuffer = this.ToDispose(SharpDX.Direct3D11.Buffer.Create( deviceResources.D3DDevice, SharpDX.Direct3D11.BindFlags.ConstantBuffer, ref modelConstantBufferData)); // Once the cube is loaded, the object is ready to be rendered. loadingComplete = true; }
private void ComputeSphere(int tessellation, bool invertn) { if (tessellation < 3) { new Exception("tesselation parameter out of range"); } int verticalSegments = tessellation; int horizontalSegments = tessellation * 2; int vertCount = (verticalSegments + 1) * (horizontalSegments + 1); int idxCount = (verticalSegments) * (horizontalSegments + 1) * 6; float radius = 0.5f; // Diameter of the default Sphere will always be 1 to stay aligned VertexPositionTexture[] sphereVertArray = new VertexPositionTexture[vertCount]; int[] cubeIndices = new int[idxCount]; int writePos = 0; for (int i = 0; i <= verticalSegments; i++) { float v = 1 - (float)i / verticalSegments; float latitude = (float)(i * SharpDX.MathUtil.Pi / verticalSegments) - SharpDX.MathUtil.PiOverTwo; var dy = (float)Math.Sin(latitude); var dxz = (float)Math.Cos(latitude); // Create a single ring of vertices at this latitude. for (ushort j = 0; j <= horizontalSegments; j++) { float u = (float)j / horizontalSegments; float longitude = (float)(j * SharpDX.MathUtil.TwoPi / horizontalSegments); float dx = (float)Math.Cos(longitude); float dz = (float)Math.Sin(longitude); dx *= dxz; dz *= dxz; Vector3 vect3 = new Vector3(dx, dy, dz); VertexPositionTexture vert; vert.pos = vect3 * radius; vert.texture = new Vector2(u, v); sphereVertArray[writePos] = vert; writePos++; } } // Fill the index buffer with triangles joining each pair of latitude rings. int stride = horizontalSegments + 1; writePos = 0; for (int i = 0; i < verticalSegments; i++) { for (int j = 0; j <= horizontalSegments; j++) { int nextI = i + 1; int nextJ = (j + 1) % stride; cubeIndices[writePos] = i * stride + j; cubeIndices[++writePos] = nextI * stride + j; cubeIndices[++writePos] = i * stride + nextJ; cubeIndices[++writePos] = i * stride + nextJ; cubeIndices[++writePos] = nextI * stride + j; cubeIndices[++writePos] = nextI * stride + nextJ; writePos++; } } vertexBuffer = this.ToDispose(SharpDX.Direct3D11.Buffer.Create( deviceResources.D3DDevice, SharpDX.Direct3D11.BindFlags.VertexBuffer, sphereVertArray)); indexCount = idxCount; indexBuffer = this.ToDispose(SharpDX.Direct3D11.Buffer.Create( deviceResources.D3DDevice, SharpDX.Direct3D11.BindFlags.IndexBuffer, cubeIndices)); }
public void MakeSphere(SharpDX.Direct3D11.Device d3dDevice) { // Layout from VertexShader input signature texture = Texture11.FromFile(d3dDevice, "earthMap.jpg"); uint[] indexes = new uint[subDivisionsX * subDivisionsY * 6]; float[] verts = new float[((subDivisionsX + 1) * (subDivisionsY + 1)) * 6]; double lat, lng; uint index = 0; double latMin = 90; double latMax = -90; double lngMin = -180; double lngMax = 180; uint x1, y1; double latDegrees = latMax - latMin; double lngDegrees = lngMax - lngMin; double textureStepX = 1.0f / subDivisionsX; double textureStepY = 1.0f / subDivisionsY; for (y1 = 0; y1 <= subDivisionsY; y1++) { if (y1 != subDivisionsY) { lat = latMax - (textureStepY * latDegrees * (double)y1); } else { lat = latMin; } for (x1 = 0; x1 <= subDivisionsX; x1++) { if (x1 != subDivisionsX) { lng = lngMin + (textureStepX * lngDegrees * (double)x1); } else { lng = lngMax; } index = (y1 * (subDivisionsX + 1) + x1) * 6; GeoTo3d(verts, (int)index, lat, lng); } } triangleCount = (subDivisionsX) * (subDivisionsY) * 2; for (y1 = 0; y1 < subDivisionsY; y1++) { for (x1 = 0; x1 < subDivisionsX; x1++) { index = (y1 * subDivisionsX * 6) + 6 * x1; // First triangle in quad indexes[index] = (y1 * (subDivisionsX + 1) + x1); indexes[index + 1] = ((y1 + 1) * (subDivisionsX + 1) + x1); indexes[index + 2] = (y1 * (subDivisionsX + 1) + (x1 + 1)); // Second triangle in quad indexes[index + 3] = (y1 * (subDivisionsX + 1) + (x1 + 1)); indexes[index + 4] = ((y1 + 1) * (subDivisionsX + 1) + x1); indexes[index + 5] = ((y1 + 1) * (subDivisionsX + 1) + (x1 + 1)); } } vertices = SharpDX.Direct3D11.Buffer.Create(d3dDevice, SharpDX.Direct3D11.BindFlags.VertexBuffer, verts); vertexBufferBinding = new SharpDX.Direct3D11.VertexBufferBinding(vertices, sizeof(float) * 6, 0); indexBuffer = SharpDX.Direct3D11.Buffer.Create(d3dDevice, SharpDX.Direct3D11.BindFlags.IndexBuffer, indexes); }
private void PlatformSetDataInternal <T>(int offsetInBytes, T[] data, int startIndex, int elementCount, int vertexStride, SetDataOptions options, int bufferSize, int elementSizeInBytes) where T : struct { GenerateIfRequired(); if (_isDynamic) { // We assume discard by default. var mode = SharpDX.Direct3D11.MapMode.WriteDiscard; if ((options & SetDataOptions.NoOverwrite) == SetDataOptions.NoOverwrite) { mode = SharpDX.Direct3D11.MapMode.WriteNoOverwrite; } var d3dContext = GraphicsDevice._d3dContext; lock (d3dContext) { var dataBox = d3dContext.MapSubresource(_buffer, 0, mode, SharpDX.Direct3D11.MapFlags.None); if (vertexStride == elementSizeInBytes) { SharpDX.Utilities.Write(dataBox.DataPointer + offsetInBytes, data, startIndex, elementCount); } else { for (int i = 0; i < elementCount; i++) { SharpDX.Utilities.Write(dataBox.DataPointer + offsetInBytes + i * vertexStride, data, startIndex + i, 1); } } d3dContext.UnmapSubresource(_buffer, 0); } } else { var dataHandle = GCHandle.Alloc(data, GCHandleType.Pinned); try { var startBytes = startIndex * elementSizeInBytes; var dataPtr = (IntPtr)(dataHandle.AddrOfPinnedObject().ToInt64() + startBytes); var d3dContext = GraphicsDevice._d3dContext; if (vertexStride == elementSizeInBytes) { var box = new SharpDX.DataBox(dataPtr, elementCount * elementSizeInBytes, 0); var region = new SharpDX.Direct3D11.ResourceRegion(); region.Top = 0; region.Front = 0; region.Back = 1; region.Bottom = 1; region.Left = offsetInBytes; region.Right = offsetInBytes + (elementCount * elementSizeInBytes); lock (d3dContext) d3dContext.UpdateSubresource(box, _buffer, 0, region); } else { // Copy the buffer to a staging resource, so that any elements we don't write to will still be correct. var stagingDesc = _buffer.Description; stagingDesc.BindFlags = SharpDX.Direct3D11.BindFlags.None; stagingDesc.CpuAccessFlags = SharpDX.Direct3D11.CpuAccessFlags.Read | SharpDX.Direct3D11.CpuAccessFlags.Write; stagingDesc.Usage = SharpDX.Direct3D11.ResourceUsage.Staging; stagingDesc.OptionFlags = SharpDX.Direct3D11.ResourceOptionFlags.None; using (var stagingBuffer = new SharpDX.Direct3D11.Buffer(GraphicsDevice._d3dDevice, stagingDesc)) { lock (d3dContext) { d3dContext.CopyResource(_buffer, stagingBuffer); // Map the staging resource to a CPU accessible memory var box = d3dContext.MapSubresource(stagingBuffer, 0, SharpDX.Direct3D11.MapMode.Read, SharpDX.Direct3D11.MapFlags.None); for (int i = 0; i < elementCount; i++) { SharpDX.Utilities.CopyMemory( box.DataPointer + i * vertexStride + offsetInBytes, dataPtr + i * elementSizeInBytes, elementSizeInBytes); } // Make sure that we unmap the resource in case of an exception d3dContext.UnmapSubresource(stagingBuffer, 0); // Copy back from staging resource to real buffer. d3dContext.CopyResource(stagingBuffer, _buffer); } } } } finally { dataHandle.Free(); } } }
// Reduce give matrix to top PC components. public float[][] DoPca(float[][] A, int eigenCount) { GpuDevice gpu = new GpuDevice(); var cc = gpu.CreateConstBuffer <PcaConstants>(0); bool transposing = (A.Length > A[0].Length); cc.c.eigenCount = eigenCount; cc.c.rows = transposing ? A[0].Length : A.Length; cc.c.columns = (!transposing) ? A[0].Length : A.Length; var resultBuf = gpu.CreateBufferRW(3, 4, 1); // to receive the total changes. var resultStaging = gpu.CreateStagingBuffer(resultBuf); Buffer tableBuf = gpu.CreateBufferRO(cc.c.rows * cc.c.columns, 4, 0); double[] colMean = new double[A[0].Length]; Parallel.For(0, A[0].Length, col => { colMean[col] = 0.0; for (int row = 0; row < A.Length; row++) { colMean[col] += A[row][col]; } colMean[col] /= A.Length; }); using (var ds = gpu.NewWriteStream(tableBuf)) { float[] buf = new float[cc.c.rows * cc.c.columns]; if (transposing) { Parallel.For(0, cc.c.columns, col => { int offset = col * cc.c.rows; for (int row = 0; row < cc.c.rows; row++) { buf[offset + row] = (float)(A[col][row] - colMean[row]); } }); } else { Parallel.For(0, cc.c.columns, col => { int offset = col * cc.c.rows; for (int row = 0; row < cc.c.rows; row++) { buf[offset + row] = (float)(A[row][col] - colMean[col]); } }); } ds.WriteRange(buf); } cc.c.covFactor = transposing ? 1.0f / (cc.c.columns - 1) : 1.0f / (cc.c.rows - 1); Buffer covBuf = gpu.CreateBufferRW(cc.c.rows * cc.c.rows, 4, 0); using (var shader = gpu.LoadShader("TsneDx.PcaCreateCovMatrix.cso")) { gpu.SetShader(shader); cc.c.groupNumber = 256; for (int iBlock = 0; iBlock < cc.c.rows; iBlock += cc.c.groupNumber) { cc.c.iBlock = iBlock; cc.Upload(); gpu.Run(cc.c.groupNumber); } } var eVectorBuf = gpu.CreateBufferRW(cc.c.rows, 4, 2); var eVectorStaging = gpu.CreateStagingBuffer(eVectorBuf); var eVector2Buf = gpu.CreateBufferRW(cc.c.rows, 4, 3); var sdInit = gpu.LoadShader("TsneDx.PcaInitIteration.cso"); var sdStep = gpu.LoadShader("TsneDx.PcaIterateOneStep.cso"); var sdNorm = gpu.LoadShader("TsneDx.PcaCalculateNormal.cso"); var sdAdjCov = gpu.LoadShader("TsneDx.PcaAdjustCovMatrix.cso"); gpu.SetShader(sdInit); cc.c.eigenIdx = 0; cc.Upload(); gpu.Run(); float preEigen = 1e30f; float newEigen = 0; float[][] eVectors = new float[eigenCount][]; double[] eValues = new double[eigenCount]; for (int eigenIdx = 0; eigenIdx < eigenCount; eigenIdx++) { cc.c.groupNumber = 256; cc.Upload(); for (int repeat = 0; repeat < MAX_ITERATION; repeat++) { gpu.SetShader(sdStep); gpu.Run(cc.c.groupNumber); gpu.SetShader(sdNorm); gpu.Run(1); newEigen = gpu.ReadFloat(resultStaging, resultBuf); double delta = Math.Abs((newEigen - preEigen) / preEigen); if (delta < epsilon) { break; } preEigen = newEigen; } eValues[eigenIdx] = (double)newEigen; // Eigenvector with extrem small eigenvalue (i.e. 0.0) will be ignored and stop the calculation. if (Math.Abs(eValues[eigenIdx] / eValues[0]) < stopEpsilon) { Array.Resize(ref eValues, eigenIdx); Array.Resize(ref eVectors, eigenIdx); break; } eVectors[eigenIdx] = new float[cc.c.rows]; Array.Copy(gpu.ReadRange <float>(eVectorStaging, eVectorBuf, cc.c.rows), eVectors[eigenIdx], cc.c.rows); if (eigenIdx == (eigenCount - 1)) { break; } // Adjust the covariance matrix. gpu.SetShader(sdAdjCov); cc.c.groupNumber = 128; cc.Upload(); gpu.Run(cc.c.groupNumber); // Initialize the iteration loop for the next eigen-vector. gpu.SetShader(sdInit); cc.c.eigenIdx = eigenIdx + 1; cc.Upload(); gpu.Run(); //CmdSynchronize(); } if (!transposing) { using (var shader = gpu.LoadShader("TsneDx.PcaTransposeEigenvectors.cso")) { int eRows = eVectors.Length; int eColumns = eVectors[0].Length; Buffer eigenList1 = gpu.CreateBufferRO(eRows * eColumns, 4, 1); double[] S = eValues.Select(x => 1.0 / Math.Sqrt(Math.Abs(x * (eVectors[0].Length - 1)))).ToArray(); float[] eVector1 = new float[eRows * eColumns]; for (int row = 0; row < eRows; row++) { for (int col = 0; col < eColumns; col++) { eVector1[row * eColumns + col] = (float)(S[row] * eVectors[row][col]); } } using (var ds = gpu.NewWriteStream(eigenList1)) ds.WriteRange(eVector1); Buffer eigenList2 = gpu.CreateBufferRW(eVectors.Length * cc.c.columns, 4, 4); gpu.SetShader(shader); cc.c.groupNumber = 128; cc.c.eigenCount = eVectors.Length; cc.Upload(); gpu.Run(cc.c.groupNumber); float[] eVectors2 = gpu.ReadRange <float>(eigenList2, eVectors.Length * cc.c.columns); eVectors = new float[eVectors.Length][]; for (int row = 0; row < eVectors.Length; row++) { eVectors[row] = new float[cc.c.columns]; } Parallel.For(0, eVectors.Length, row => { Array.Copy(eVectors2, row * cc.c.columns, eVectors[row], 0, cc.c.columns); }); TsneDx.SafeDispose(eigenList1, eigenList2); } } float[][] B = null; cc.c.rows = A.Length; cc.c.columns = A[0].Length; cc.c.eigenCount = eVectors.Length; cc.Upload(); if (transposing) { // The tableBuf on GPU is in wrong matrix order. We need to upload the tableBuf in needed order here. TsneDx.SafeDispose(tableBuf); tableBuf = gpu.CreateBufferRO(cc.c.rows * cc.c.columns, 4, 0); Parallel.For(0, cc.c.rows, row => { for (int col = 0; col < cc.c.columns; col++) { A[row][col] -= (float)colMean[col]; } }); gpu.WriteMarix(tableBuf, A); } Buffer eigenTable = gpu.CreateBufferRO(cc.c.eigenCount * cc.c.columns, 4, 1); gpu.WriteMarix(eigenTable, eVectors); TsneDx.SafeDispose(resultBuf); resultBuf = gpu.CreateBufferRW(cc.c.rows * cc.c.eigenCount, 4, 1); using (var shader = gpu.LoadShader("TsneDx.PcaReduceMatrix.cso")) { try { gpu.SetShader(shader); const int GROUP_NR = 256; gpu.Run(GROUP_NR); float[] buf = gpu.ReadRange <float>(resultBuf, cc.c.rows * cc.c.eigenCount); B = new float[cc.c.rows][]; for (int row = 0; row < cc.c.rows; row++) { B[row] = new float[cc.c.eigenCount]; } Parallel.For(0, cc.c.rows, row => { Array.Copy(buf, row * cc.c.eigenCount, B[row], 0, cc.c.eigenCount); }); } catch (SharpDX.SharpDXException ex) { string msg = ex.Message; Console.WriteLine("GPU operation timeouted: Please try to enlarge the TDR value"); } } TsneDx.SafeDispose(eigenTable, sdInit, sdStep, sdNorm, sdAdjCov, eVectorBuf, eVectorStaging, eVector2Buf, resultBuf, resultStaging, covBuf, tableBuf, cc, gpu); return(B); }
public IndexBuffer(PPDDevice device, SharpDX.Direct3D11.Buffer buffer) : base(device) { _Buffer = buffer; }