public void Bind(ProgramAttribute attribute, GraphicsBuffer buffer, int offsetInBytes, Format format, int stride) { if (attribute == null) throw new ArgumentNullException("attribute"); throw new NotImplementedException(); //GLExt.VertexAttribFormat(attribute.Index, format.ComponentCount, format.VertexAttribPonterType, format.IsNormalized, offsetInBytes); }
public ModelAttribute(string name, GraphicsBuffer buffer, int offsetInBytes, Format format, int stride, ModelAttributeChannel channel, int index) { this.Channel = channel; this.Index = index; this.Name = name; this.Buffer = buffer; this.OffsetInBytes = offsetInBytes; this.Format = format; this.Stride = stride; }
public Model(GraphicsBuffer elementBuffer, ElementType elementType, Sphere3d bounds) { if (elementBuffer == null) throw new ArgumentNullException("elementBuffer"); this.elementBuffer = elementBuffer; this.elementType = elementType; this.bounds = bounds; bones = new ModelBoneCollection(this); meshes = new ModelMeshCollection(this); }
static GraphicsMemoryRegion <GraphicsResource> CreateConstantBufferRegion(GraphicsContext graphicsContext, GraphicsBuffer constantBuffer) { var constantBufferRegion = constantBuffer.Allocate(SizeOf <Matrix4x4>(), alignment: 256); var pConstantBuffer = constantBuffer.Map <Matrix4x4>(in constantBufferRegion); pConstantBuffer[0] = Matrix4x4.Identity; constantBuffer.UnmapAndWrite(in constantBufferRegion); return(constantBufferRegion); }
extern private void SetGraphicsBuffer(int nameID, [NotNull] GraphicsBuffer buffer);
static GraphicsBufferView CreateIndexBufferView(GraphicsCopyContext copyContext, GraphicsBuffer indexBuffer, GraphicsBuffer uploadBuffer, in UnmanagedValueList <uint> indices)
public void Accept(ShaderGeneratorContext context) { valueBuffer ??= GraphicsBuffer.Create(context.GraphicsDevice, Value, ResourceFlags.None, GraphicsHeapType.Upload); context.ConstantBufferViews.Add(valueBuffer); }
private void ChessBoard_Paint(object sender, PaintEventArgs e) { GraphicsBuffer graphicsBuffer = new GraphicsBuffer(); graphicsBuffer.CreateGraphicsBuffer(e.Graphics, Width, Height); Graphics g = graphicsBuffer.Graphics; SolidBrush solidWhiteBrush = new SolidBrush(Color.White); SolidBrush solidBlackBrush = new SolidBrush(Color.Black); Pen penBlack = new Pen(Color.Black, 1); Pen penHightlight = new Pen(Color.Black, 2); Pen penDestination = new Pen(Color.Yellow, 2); Pen penValidMove = new Pen(Color.Black, 2); Pen penEnPassant = new Pen(Color.DeepPink, 1); const int buffer = 10; if (Width < Height) { maxHeight = Width - 5 - buffer; boxHeight = maxHeight / 8; } else { maxHeight = Height - 5 - buffer; boxHeight = maxHeight / 8; } g.Clear(BackColor); try { int selectedX; int selectedY; //Draw Chess Board for (byte y = 0; y < 8; y++) { for (byte x = 0; x < 8; x++) { if ((x + y) % 2 == 0) { g.FillRectangle(solidWhiteBrush, (x * boxHeight) + buffer, (y * boxHeight), boxHeight, boxHeight); } else { Rectangle drawArea1 = new Rectangle((x * boxHeight) + buffer, (y * boxHeight), boxHeight, boxHeight); LinearGradientBrush linearBrush = new LinearGradientBrush( drawArea1, Color.Gainsboro, Color.Silver, LinearGradientMode.ForwardDiagonal); g.FillRectangle(linearBrush, (x * boxHeight) + buffer, (y * boxHeight), boxHeight, boxHeight); } g.DrawRectangle(penBlack, (x * boxHeight) + buffer, (y * boxHeight), boxHeight, boxHeight); } } for (byte i = 0; i < 8; i++) { g.DrawString((8 - i).ToString(), new Font("Verdana", 8), solidBlackBrush, 0, (i * boxHeight) + buffer); g.DrawString(GetColumnFromInt(i + 1).ToString(), new Font("Verdana", 8), solidBlackBrush, (i * boxHeight) + (boxHeight / 2) + 3, maxHeight - 1); } //Draw Pieces for (byte column = 0; column < 8; column++) { for (byte row = 0; row < 8; row++) { ChessPieceType chessPieceType = engine.GetPieceTypeAt(column, row); if (chessPieceType != ChessPieceType.None) { ChessPieceColor chessPieceColor = engine.GetPieceColorAt(column, row); bool selected = engine.GetChessPieceSelected(column, row); int x = (column) * boxHeight; int y = (row) * boxHeight; if (chessPieceColor == ChessPieceColor.White) { if (chessPieceType == ChessPieceType.Pawn) { g.DrawImage(Resources.WPawn, x + buffer, y, boxHeight, boxHeight); } else if (chessPieceType == ChessPieceType.Rook) { g.DrawImage(Resources.WRook, x + buffer, y, boxHeight, boxHeight); } else if (chessPieceType == ChessPieceType.Knight) { g.DrawImage(Resources.WKnight, x + buffer, y, boxHeight, boxHeight); } else if (chessPieceType == ChessPieceType.Bishop) { g.DrawImage(Resources.WBishop, x + buffer, y, boxHeight, boxHeight); } else if (chessPieceType == ChessPieceType.Queen) { g.DrawImage(Resources.WQueen, x + buffer, y, boxHeight, boxHeight); } else if (chessPieceType == ChessPieceType.King) { g.DrawImage(Resources.WKing, x + buffer, y, boxHeight, boxHeight); } } else { if (chessPieceType == ChessPieceType.Pawn) { g.DrawImage(Resources.BPawn, x + buffer, y, boxHeight, boxHeight); } else if (chessPieceType == ChessPieceType.Rook) { g.DrawImage(Resources.BRook, x + buffer, y, boxHeight, boxHeight); } else if (chessPieceType == ChessPieceType.Knight) { g.DrawImage(Resources.BKnight, x + buffer, y, boxHeight, boxHeight); } else if (chessPieceType == ChessPieceType.Bishop) { g.DrawImage(Resources.BBishop, x + buffer, y, boxHeight, boxHeight); } else if (chessPieceType == ChessPieceType.Queen) { g.DrawImage(Resources.BQueen, x + buffer, y, boxHeight, boxHeight); } else if (chessPieceType == ChessPieceType.King) { g.DrawImage(Resources.BKing, x + buffer, y, boxHeight, boxHeight); } } if (selected) { selectedX = ((column) * boxHeight) + buffer; //selectedY = (8 - row - 1)*boxHeight; //selectedX = ((8-column-1) * boxHeight) + buffer; selectedY = (row) * boxHeight; g.DrawRectangle(penHightlight, selectedX, selectedY, boxHeight - 1, boxHeight - 1); //Draw Valid Moves if (engine.GetValidMoves(column, row) != null) { foreach (byte[] sqr in engine.GetValidMoves(column, row)) { int moveY = (sqr[1]) * boxHeight; int moveX = (sqr[0] * boxHeight) + buffer; g.DrawRectangle(penValidMove, moveX, moveY, boxHeight - 1, boxHeight - 1); } } } if (engine.GetEnPassantMoves()[0] > 0) { int moveY = (engine.GetEnPassantMoves()[1]) * boxHeight; int moveX = (engine.GetEnPassantMoves()[0] * boxHeight) + buffer; g.DrawRectangle(penEnPassant, moveX, moveY, boxHeight - 1, boxHeight - 1); } } } } if (currentDestination.Selected) { selectedY = (currentDestination.Row) * boxHeight; selectedX = ((currentDestination.Column) * boxHeight) + buffer; g.DrawRectangle(penDestination, selectedX, selectedY, boxHeight - 1, boxHeight - 1); } graphicsBuffer.Render(CreateGraphics()); g.Dispose(); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error Drawing Chess Board", MessageBoxButtons.OK); } }
static GraphicsBufferView CreateVertexBufferView(GraphicsCopyContext copyContext, GraphicsBuffer vertexBuffer, GraphicsBuffer uploadBuffer, float aspectRatio) { var uploadBufferView = uploadBuffer.CreateBufferView <Texture3DVertex>(4); var vertexBufferSpan = uploadBufferView.Map <Texture3DVertex>(); { vertexBufferSpan[0] = new Texture3DVertex { // Position = Vector3.Create(-0.5f, 0.5f, 0.0f), // y in this setup UVW = Vector3.Create(0, 1, 0.5f), // ^ z the origin o }; // | / is in the middle // | / of the rendered scene vertexBufferSpan[1] = new Texture3DVertex { // o------>x Position = Vector3.Create(0.5f, 0.5f, 0.0f), // UVW = Vector3.Create(1, 1, 0.5f), // 0 ----- 1 }; // | \ | // | \ | vertexBufferSpan[2] = new Texture3DVertex { // | \ | Position = Vector3.Create(0.5f, -0.5f, 0.0f), // 3-------2 UVW = Vector3.Create(1, 0, 0.5f), // }; vertexBufferSpan[3] = new Texture3DVertex { Position = Vector3.Create(-0.5f, -0.5f, 0.0f), UVW = Vector3.Create(0, 0, 0.5f), }; } uploadBufferView.UnmapAndWrite(); var vertexBufferView = vertexBuffer.CreateBufferView <Texture3DVertex>(4); copyContext.Copy(vertexBufferView, uploadBufferView); return(vertexBufferView); }
static GraphicsBufferView CreateIndexBufferView(GraphicsCopyContext copyContext, GraphicsBuffer indexBuffer, GraphicsBuffer uploadBuffer) { var uploadBufferView = uploadBuffer.CreateBufferView <ushort>(6); var indexBufferSpan = uploadBufferView.Map <ushort>(); { // clockwise when looking at the triangle from the outside indexBufferSpan[0] = 0; indexBufferSpan[1] = 1; indexBufferSpan[2] = 2; indexBufferSpan[3] = 0; indexBufferSpan[4] = 2; indexBufferSpan[5] = 3; } uploadBufferView.UnmapAndWrite(); var indexBufferView = indexBuffer.CreateBufferView <ushort>(6); copyContext.Copy(indexBufferView, uploadBufferView); return(indexBufferView); }
public static async Task RunAsync(GraphicsDevice device) { bool generateWithDelegate = false; // Create graphics buffer int width = 10; int height = 10; float[] array = new float[width * height]; for (int i = 0; i < array.Length; i++) { array[i] = i; } float[] outputArray = new float[width * height]; using GraphicsBuffer <float> sourceBuffer = GraphicsBuffer.Create <float>(device, array, ResourceFlags.None); using GraphicsBuffer <float> destinationBuffer = GraphicsBuffer.Create <float>(device, array.Length * 2, ResourceFlags.AllowUnorderedAccess); GraphicsBuffer <float> slicedDestinationBuffer = destinationBuffer.Slice(20, 60); slicedDestinationBuffer = slicedDestinationBuffer.Slice(10, 50); DescriptorSet descriptorSet = new DescriptorSet(device, 2); descriptorSet.AddUnorderedAccessViews(slicedDestinationBuffer); descriptorSet.AddShaderResourceViews(sourceBuffer); // Generate computer shader ShaderGenerator shaderGenerator = generateWithDelegate ? CreateShaderGeneratorWithDelegate(sourceBuffer, destinationBuffer) : CreateShaderGeneratorWithClass(); ShaderGeneratorResult result = shaderGenerator.GenerateShader(); // Compile shader byte[] shaderBytecode = ShaderCompiler.Compile(ShaderStage.ComputeShader, result.ShaderSource, result.EntryPoints["compute"]); DescriptorRange[] descriptorRanges = new DescriptorRange[] { new DescriptorRange(DescriptorRangeType.UnorderedAccessView, 1, 0), new DescriptorRange(DescriptorRangeType.ShaderResourceView, 1, 0) }; RootParameter rootParameter = new RootParameter(new RootDescriptorTable(descriptorRanges), ShaderVisibility.All); RootSignatureDescription rootSignatureDescription = new RootSignatureDescription(RootSignatureFlags.None, new[] { rootParameter }); RootSignature rootSignature = new RootSignature(device, rootSignatureDescription); PipelineState pipelineState = new PipelineState(device, rootSignature, shaderBytecode); // Execute computer shader using (CommandList commandList = new CommandList(device, CommandListType.Compute)) { commandList.SetPipelineState(pipelineState); commandList.SetComputeRootDescriptorTable(0, descriptorSet); commandList.Dispatch(1, 1, 1); await commandList.FlushAsync(); } // Print matrix Console.WriteLine("Before:"); PrintMatrix(array, width, height); destinationBuffer.GetData(outputArray.AsSpan()); Console.WriteLine(); Console.WriteLine("After:"); PrintMatrix(outputArray, width, height); }
static GraphicsBufferView CreateVertexBufferView(GraphicsCopyContext copyContext, GraphicsBuffer vertexBuffer, GraphicsBuffer uploadBuffer, float aspectRatio) { var uploadBufferView = uploadBuffer.CreateBufferView <IdentityVertex>(3); var vertexBufferSpan = uploadBufferView.Map <IdentityVertex>(); { vertexBufferSpan[0] = new IdentityVertex { Color = Colors.Red, Position = Vector3.Create(0.0f, 0.25f * aspectRatio, 0.0f), }; vertexBufferSpan[1] = new IdentityVertex { Color = Colors.Lime, Position = Vector3.Create(0.25f, -0.25f * aspectRatio, 0.0f), }; vertexBufferSpan[2] = new IdentityVertex { Color = Colors.Blue, Position = Vector3.Create(-0.25f, -0.25f * aspectRatio, 0.0f), }; } uploadBufferView.UnmapAndWrite(); var vertexBufferView = vertexBuffer.CreateBufferView <IdentityVertex>(3); copyContext.Copy(vertexBufferView, uploadBufferView); return(vertexBufferView); }
public void ReleaseIndexBuffer(GraphicsBuffer buffer) { _indexPool.ReleaseBuffer(buffer); }
public void Visit(MaterialGeneratorContext context) { valueBuffer ??= GraphicsBuffer.New(context.GraphicsDevice, Value, ResourceFlags.ConstantBuffer, GraphicsHeapType.Upload).DisposeBy(context.GraphicsDevice); context.ConstantBufferViews.Add(valueBuffer); }
static GraphicsMemoryRegion <GraphicsResource> CreateVertexBufferRegion(GraphicsContext graphicsContext, GraphicsBuffer vertexBuffer, GraphicsBuffer vertexStagingBuffer, float aspectRatio) { var vertexBufferRegion = vertexBuffer.Allocate(SizeOf <Texture3DVertex>() * 4, alignment: 16); var pVertexBuffer = vertexStagingBuffer.Map <Texture3DVertex>(in vertexBufferRegion); pVertexBuffer[0] = new Texture3DVertex { // Position = new Vector3(-0.5f, 0.5f, 0.0f), // y in this setup UVW = new Vector3(0, 1, 0.5f), // ^ z the origin o }; // | / is in the middle // | / of the rendered scene pVertexBuffer[1] = new Texture3DVertex { // o------>x Position = new Vector3(0.5f, 0.5f, 0.0f), // UVW = new Vector3(1, 1, 0.5f), // 0 ----- 1 }; // | \ | // | \ | pVertexBuffer[2] = new Texture3DVertex { // | \ | Position = new Vector3(0.5f, -0.5f, 0.0f), // 3-------2 UVW = new Vector3(1, 0, 0.5f), // }; pVertexBuffer[3] = new Texture3DVertex { Position = new Vector3(-0.5f, -0.5f, 0.0f), UVW = new Vector3(0, 0, 0.5f), }; vertexStagingBuffer.UnmapAndWrite(in vertexBufferRegion); return(vertexBufferRegion); }
static GraphicsMemoryRegion <GraphicsResource> CreateTexture3DRegion(GraphicsContext graphicsContext, GraphicsBuffer textureStagingBuffer) { const uint TextureWidth = 256; const uint TextureHeight = 256; const ushort TextureDepth = 256; const uint TextureDz = TextureWidth * TextureHeight; const uint TexturePixels = TextureDz * TextureDepth; var texture3D = graphicsContext.Device.MemoryAllocator.CreateTexture(GraphicsTextureKind.ThreeDimensional, GraphicsResourceCpuAccess.None, TextureWidth, TextureHeight, TextureDepth); var texture3DRegion = texture3D.Allocate(texture3D.Size, alignment: 4); var pTextureData = textureStagingBuffer.Map <uint>(in texture3DRegion); for (uint n = 0; n < TexturePixels; n++) { var x = n % TextureWidth; var y = n % TextureDz / TextureWidth; var z = n / TextureDz; pTextureData[n] = 0xFF000000 | (z << 16) | (y << 8) | (x << 0); } textureStagingBuffer.UnmapAndWrite(in texture3DRegion); graphicsContext.Copy(texture3D, textureStagingBuffer); return(texture3DRegion); }
internal Model(AssetLoader loader) : base(loader) { Asset context = loader.Context; string name = loader.Name; BinaryReader reader = loader.Reader; FolderAsset textureArchive = null; FolderAsset bonesFolder = new FolderAsset(this, "Bones"); FolderAsset materialsFolder = new FolderAsset(this, "Materials"); FolderAsset meshesFolder = new FolderAsset(this, "Meshes"); FolderAsset vertexDeclarationsFolder = new FolderAsset(this, "Vertex declarations"); ArrayBackedList<byte> bufferData = new ArrayBackedList<byte>(); if (context != null && context.Parent is FolderAsset) { // @"/map/m##_##_##_##/m*.flver.dcx" for DS1; textures are in the @"/map/m##/" folder. if (name.StartsWith(@"map/m")) { string folderName = name.Substring(4, 3); FolderAsset maps = (FolderAsset)context.Parent.Parent; foreach (FolderAsset child in maps.Children) { if (child.Name == folderName) { textureArchive = child; break; } } } else textureArchive = (FolderAsset)context.Parent; } #if Marking MarkingStream markingStream = loader.StartMarking(out reader); #endif loader.ExpectMagic(Magic); char endian = (char)reader.ReadByte(); switch (endian) { case 'L': ByteOrder = ByteOrder.LittleEndian; break; case 'B': reader = loader.MakeBigEndian(); ByteOrder = ByteOrder.BigEndian; break; default: throw new Exception(); } using (reader) { // Read header. loader.Expect((byte)0); Version = (ModelVersion)reader.ReadInt32(); if (Version != ModelVersion.DarkSouls && Version != ModelVersion.DarkSouls2) loader.AddError(loader.Position - 4, "Unknown model version " + VersionString + "; will try to load it anyway."); int dataOffset = reader.ReadInt32(); int dataSize = reader.ReadInt32(); if (((dataOffset + dataSize + 31) & ~31) != reader.BaseStream.Length) loader.AddError(loader.Position - 4, "Data size and offset aren't correct."); int boneUnknownCount = reader.ReadInt32(); int materialCount = reader.ReadInt32(); int boneCount = reader.ReadInt32(); int meshCount = reader.ReadInt32(); int meshCount2 = reader.ReadInt32(); if (meshCount != meshCount2) loader.AddError(loader.Position - 4, "Mesh count 1 and 2 aren't the same."); Bounds = new Box3f(reader.ReadVector3f(), reader.ReadVector3f()); Unknowns.ReadInt32s(reader, 1); // Possible the non-degenerate triangle count. Seems related. int triangleCount = reader.ReadInt32(); loader.Expect(IsDS1 ? 272 : 0x10010100); loader.Expect(IsDS1 ? 0 : 0xFFFF); int partCount = reader.ReadInt32(); int vertexDeclarationCount = reader.ReadInt32(); int materialParameterCount = reader.ReadInt32(); loader.Expect(IsDS1 ? 0 : 0x1000000); loader.ExpectZeroes(4, 8); // Calculate offsets. long boneUnknownsOffset = HeaderSize; long materialsOffset = boneUnknownsOffset + boneUnknownCount * ModelBoneUnknown.DataSize; long bonesOffset = materialsOffset + materialCount * ModelMaterial.DataSize; long meshesOffset = bonesOffset + boneCount * ModelBone.DataSize; long detailLevelsOffset = meshesOffset + meshCount * ModelMesh.DataSize; long meshVerticesOffset = detailLevelsOffset + partCount * ModelDetailLevel.DataSize; long vertexDeclarationsOffset = meshVerticesOffset + meshCount * ModelMesh.DataSizeVertexHeader; long materialParametersOffset = vertexDeclarationsOffset + vertexDeclarationCount * ModelVertexDeclaration.DataSize; long postHeaderOffset = materialParametersOffset + materialParameterCount * ModelMaterialParameter.DataSize; // BoneUnknowns ExpectedOffset(loader, boneUnknownsOffset, typeof(ModelBoneUnknown).Name); for (int index = 0; index < boneUnknownCount; index++) boneUnknowns.Add(new ModelBoneUnknown(bonesFolder, index, loader)); // Materials ExpectedOffset(loader, materialsOffset, typeof(ModelMaterial).Name); for (int index = 0; index < materialCount; index++) materials.Add(new ModelMaterial(materialsFolder, index, loader)); int expectedMaterialParameterCount = materialCount > 0 ? materials[materialCount - 1].ParameterEndIndex : 0; if (expectedMaterialParameterCount != materialParameterCount) loader.AddError(null, "Expected material parameter count {0} doesn't match actual count {1}.", expectedMaterialParameterCount, materialParameterCount); // Bones ExpectedOffset(loader, bonesOffset, typeof(ModelBone).Name); for (int index = 0; index < boneCount; index++) bones.Add(new ModelBone(bonesFolder, index, loader)); // Meshes ExpectedOffset(loader, meshesOffset, typeof(ModelMesh).Name); for (int index = 0; index < meshCount; index++) meshes.Add(new ModelMesh(meshesFolder, index, loader)); int expectedPartCount = meshCount > 0 ? meshes[meshCount - 1].PartEndIndex : 0; if (expectedPartCount != partCount) throw new InvalidDataException("Expected part count doesn't match actual count."); // Detail levels ExpectedOffset(loader, detailLevelsOffset, typeof(ModelDetailLevel).Name); foreach (ModelMesh mesh in meshes) { mesh.ReadDetailLevels(loader, dataOffset, bufferData); detailLevels.AddRange(mesh.DetailLevels); } // Mesh vertices ExpectedOffset(loader, meshVerticesOffset, typeof(ModelMesh).Name + " vertex header"); foreach (ModelMesh mesh in meshes) mesh.ReadVertexHeaders(reader, dataOffset, bufferData); // Vertex declarations ExpectedOffset(loader, vertexDeclarationsOffset, typeof(ModelVertexDeclaration).Name); for (int index = 0; index < vertexDeclarationCount; index++) vertexDeclarations.Add(new ModelVertexDeclaration(vertexDeclarationsFolder, index, loader)); // Material parameters ExpectedOffset(loader, materialParametersOffset, typeof(ModelMaterialParameter).Name); foreach (ModelMaterial material in materials) { material.ReadParameters(loader, textureArchive); materialParameters.AddRange(material.Parameters); } ExpectedOffset(loader, postHeaderOffset, "Post-header"); #if Marking if (markingStream != null) { markingStream.Report(loader); } #endif // Marking #if SkippedChecks /*int vertexDataSize = 0, indexCount = 0, indexSize = 0, vertexCount = 0, expectedTriangleCount = 0, nondegenerateTriangleCount = 0; foreach (var mesh in Meshes) { vertexDataSize += mesh.VertexCount * mesh.VertexSize; vertexCount += mesh.VertexCount; foreach (var part in mesh.Parts) { indexCount += part.Indices.Length; indexSize += part.Indices.Length * 2; expectedTriangleCount += part.Indices.Length - 2; for (int index = 0; index < part.Indices.Length - 2; index++) { if (part.Indices[index] != part.Indices[index + 1] && part.Indices[index + 1] != part.Indices[index + 2] && part.Indices[index] != part.Indices[index + 2]) nondegenerateTriangleCount++; } } } if (Math.Abs(expectedTriangleCount - triangleCount) > partCount) throw new InvalidDataException("Expected triangle count doesn't match the read value.");*/ #endif } Buffer = new GraphicsBuffer(bufferData.Count == 0 ? 1 : bufferData.Count); Buffer.Write(0, bufferData.Array, 0, bufferData.Count); }
/// <summary> /// Bind the specified <see cref="GraphicsBuffer"/> to this Vertex Array with specified <see cref="VertexDeclaration"/> /// </summary> /// <param name="buffer"><see cref="GraphicsBuffer"/> to bind</param> /// <param name="vertexDeclaration"><see cref="VertexDeclaration"/> to use for binding</param> public void BindBuffer(GraphicsBuffer buffer, VertexDeclaration vertexDeclaration) { for (int i = 0; i < vertexDeclaration.Elements.Length; i++) { VertexElement element = vertexDeclaration.Elements[i]; BindBuffer(buffer, element.Index, element.Size, element.Type, element.Normalized, vertexDeclaration.Stride, element.Offset); } }
/// <summary> /// Bind the specified <see cref="GraphicsBuffer"/> to this Vertex Array with specified parameters /// </summary> /// <param name="buffer"><see cref="GraphicsBuffer"/> to bind</param> /// <param name="index">Index of the Vertex Attribute to bind</param> /// <param name="size">Number of components per vertex atribute. Must be 1-4</param> /// <param name="type"><see cref="VertexAttribPointerType"/></param> /// <param name="normalized">Normalized</param> /// <param name="stride">Byte offset between consecutive vertex attributes</param> /// <param name="offset">Offset</param> public void BindBuffer(GraphicsBuffer buffer, int index, int size, VertexAttribPointerType type, bool normalized, int stride, int offset) { BindBuffer(buffer); GL.EnableVertexAttribArray(index); GL.VertexAttribPointer(index, size, type, normalized, stride, offset); }
static GraphicsMemoryRegion <GraphicsResource> CreateVertexBufferRegion(GraphicsContext graphicsContext, GraphicsBuffer vertexBuffer, GraphicsBuffer vertexStagingBuffer, float aspectRatio) { var vertexBufferRegion = vertexBuffer.Allocate(SizeOf <IdentityVertex>() * 3, alignment: 16); var pVertexBuffer = vertexStagingBuffer.Map <IdentityVertex>(in vertexBufferRegion); pVertexBuffer[0] = new IdentityVertex { Position = new Vector3(0.0f, 0.25f * aspectRatio, 0.0f), Color = new Vector4(1.0f, 0.0f, 0.0f, 1.0f) }; pVertexBuffer[1] = new IdentityVertex { Position = new Vector3(0.25f, -0.25f * aspectRatio, 0.0f), Color = new Vector4(0.0f, 1.0f, 0.0f, 1.0f) }; pVertexBuffer[2] = new IdentityVertex { Position = new Vector3(-0.25f, -0.25f * aspectRatio, 0.0f), Color = new Vector4(0.0f, 0.0f, 1.0f, 1.0f) }; vertexStagingBuffer.UnmapAndWrite(in vertexBufferRegion); return(vertexBufferRegion); }
// During initialization, we will allocate all required objects, and set up our custom instance data. void Start() { // Create the BatchRendererGroup and register assets m_BRG = new BatchRendererGroup(this.OnPerformCulling, IntPtr.Zero); m_MeshID = m_BRG.RegisterMesh(mesh); m_MaterialID = m_BRG.RegisterMaterial(material); // Create the buffer that holds our instance data m_InstanceData = new GraphicsBuffer(GraphicsBuffer.Target.Raw, (kExtraBytes + kBytesPerInstance * kNumInstances) / sizeof(int), sizeof(int)); // Place one zero matrix at the start of the instance data buffer, so loads from address 0 will return zero var zero = new Matrix4x4[1] { Matrix4x4.zero }; // Create transform matrices for our three example instances var matrices = new Matrix4x4[kNumInstances] { Matrix4x4.Translate(new Vector3(-2, 0, 0)), Matrix4x4.Translate(new Vector3(0, 0, 0)), Matrix4x4.Translate(new Vector3(2, 0, 0)), }; // Convert the transform matrices into the packed format expected by the shader var objectToWorld = new PackedMatrix[kNumInstances] { new PackedMatrix(matrices[0]), new PackedMatrix(matrices[1]), new PackedMatrix(matrices[2]), }; // Also create packed inverse matrices var worldToObject = new PackedMatrix[kNumInstances] { new PackedMatrix(matrices[0].inverse), new PackedMatrix(matrices[1].inverse), new PackedMatrix(matrices[2].inverse), }; // Make all instances have unique colors var colors = new Vector4[kNumInstances] { new Vector4(1, 0, 0, 1), new Vector4(0, 1, 0, 1), new Vector4(0, 0, 1, 1), }; // In this simple example, the instance data is placed into the buffer like this: // Offset | Description // 0 | 64 bytes of zeroes, so loads from address 0 return zeroes // 64 | 32 uninitialized bytes to make working with SetData easier, otherwise unnecessary // 96 | unity_ObjectToWorld, three packed float3x4 matrices // 240 | unity_WorldToObject, three packed float3x4 matrices // 384 | _BaseColor, three float4s // Compute start addresses for the different instanced properties. unity_ObjectToWorld starts // at address 96 instead of 64, because the computeBufferStartIndex parameter of SetData // is expressed as source array elements, so it is easier to work in multiples of sizeof(PackedMatrix). uint byteAddressObjectToWorld = kSizeOfPackedMatrix * 2; uint byteAddressWorldToObject = byteAddressObjectToWorld + kSizeOfPackedMatrix * kNumInstances; uint byteAddressColor = byteAddressWorldToObject + kSizeOfPackedMatrix * kNumInstances; // Upload our instance data to the GraphicsBuffer, from where the shader can load them. m_InstanceData.SetData(zero, 0, 0, 1); m_InstanceData.SetData(objectToWorld, 0, (int)(byteAddressObjectToWorld / kSizeOfPackedMatrix), objectToWorld.Length); m_InstanceData.SetData(worldToObject, 0, (int)(byteAddressWorldToObject / kSizeOfPackedMatrix), worldToObject.Length); m_InstanceData.SetData(colors, 0, (int)(byteAddressColor / kSizeOfFloat4), colors.Length); // Set up metadata values to point to the instance data. Set the most significant bit 0x80000000 in each, // which instructs the shader that the data is an array with one value per instance, indexed by the instance index. // Any metadata values used by the shader and not set here will be zero. When such a value is used with // UNITY_ACCESS_DOTS_INSTANCED_PROP (i.e. without a default), the shader will interpret the // 0x00000000 metadata value so that the value will be loaded from the start of the buffer, which is // where we uploaded the matrix "zero" to, so such loads are guaranteed to return zero, which is a reasonable // default value. var metadata = new NativeArray <MetadataValue>(3, Allocator.Temp); metadata[0] = new MetadataValue { NameID = Shader.PropertyToID("unity_ObjectToWorld"), Value = 0x80000000 | byteAddressObjectToWorld, }; metadata[1] = new MetadataValue { NameID = Shader.PropertyToID("unity_WorldToObject"), Value = 0x80000000 | byteAddressWorldToObject, }; metadata[2] = new MetadataValue { NameID = Shader.PropertyToID("_BaseColor"), Value = 0x80000000 | byteAddressColor, }; // Finally, create a batch for our instances, and make the batch use the GraphicsBuffer with our // instance data, and the metadata values that specify where the properties are. Note that // we do not need to pass any batch size here. m_BatchID = m_BRG.AddBatch(metadata, m_InstanceData.bufferHandle); }
private unsafe GraphicsPrimitive CreateTrianglePrimitive(GraphicsContext graphicsContext, GraphicsBuffer vertexStagingBuffer) { var graphicsDevice = GraphicsDevice; var graphicsSurface = graphicsDevice.Surface; var graphicsPipeline = CreateGraphicsPipeline(graphicsDevice, "Transform", "main", "main"); var constantBuffer = _constantBuffer; var vertexBuffer = _vertexBuffer; var vertexBufferRegion = CreateVertexBufferRegion(graphicsContext, vertexBuffer, vertexStagingBuffer, aspectRatio: graphicsSurface.Width / graphicsSurface.Height); graphicsContext.Copy(vertexBuffer, vertexStagingBuffer); var inputResourceRegions = new GraphicsMemoryRegion <GraphicsResource>[2] { CreateConstantBufferRegion(graphicsContext, constantBuffer), CreateConstantBufferRegion(graphicsContext, constantBuffer), }; return(graphicsDevice.CreatePrimitive(graphicsPipeline, vertexBufferRegion, SizeOf <IdentityVertex>(), inputResourceRegions: inputResourceRegions));
static GraphicsTextureView CreateTexture3DView(GraphicsCopyContext copyContext, GraphicsTexture texture3D, GraphicsBuffer uploadBuffer) { var uploadBufferView = uploadBuffer.CreateBufferView <byte>(checked ((uint)texture3D.ByteLength)); var textureDataSpan = uploadBufferView.Map <byte>(); { var width = texture3D.PixelWidth; var height = texture3D.PixelHeight; var bytesPerRow = texture3D.BytesPerRow; var depth = texture3D.PixelDepth; var bytesPerLayer = texture3D.BytesPerLayer; for (var z = 0u; z < depth; z++) { var layerIndex = z * bytesPerLayer; for (var y = 0u; y < height; y++) { var rowIndex = layerIndex + (y * bytesPerRow); var row = (uint *)textureDataSpan.GetPointer(rowIndex); for (var x = 0u; x < width; x++) { var red = x * 256u / width; var blue = y * 256u / height; var green = z * 256u / depth; var alpha = 0xFFu; row[x] = (alpha << 24) | (green << 16) | (blue << 8) | (red << 0); } } } } uploadBufferView.UnmapAndWrite(); var texture3DView = texture3D.CreateView(0, 1); copyContext.Copy(texture3DView, uploadBufferView); return(texture3DView); }
public SkyFace(string textureName, SkyFaceSide faceSide) { this.vertexBuffer = VertexBuffer.CreateGeneric <PositionNormalTextured>( GameEngine.Device, 4, Usage.WriteOnly, PositionNormalTextured.Format, Pool.Managed, null); this.corners = this.vertexBuffer.Lock <PositionNormalTextured>(0, 0, LockFlags.None); PositionNormalTextured[] data = new PositionNormalTextured[4]; switch (faceSide) { case SkyFaceSide.Top: //Y always 100; //back x -100; front X +100; //back Z -100; front Z +100 data[0].X = -100f; data[0].Y = 100f; data[0].Z = -100f; data[0].U = 0f; data[0].V = 1f; data[0].Nx = 0f; data[0].Ny = -1f; data[0].Nz = 0f; data[1].X = 100f; data[1].Y = 100f; data[1].Z = -100f; data[1].U = 0f; data[1].V = 0f; data[1].Nx = 0f; data[1].Ny = -1f; data[1].Nz = 0f; data[2].X = -100f; data[2].Y = 100f; data[2].Z = 100f; data[2].U = 1f; data[2].V = 1f; data[2].Nx = 0; data[2].Ny = -1f; data[2].Nz = 0f; data[3].X = 100f; data[2].Y = 100f; data[3].Z = 100f; data[3].U = 1f; data[3].V = 0f; data[3].Nx = 0f; data[3].Ny = -1f; data[3].Nz = 0f; break; case SkyFaceSide.Bottom: data[0].X = -100.0f; // nw data[0].Y = -100.0f; data[0].Z = 100.0f; data[0].U = 0.0f; data[0].V = 0.0f; data[0].Nx = 0.0f; data[0].Ny = 1.0f; data[0].Nz = 0.0f; data[1].X = 100.0f; // ne data[1].Y = -100.0f; data[1].Z = 100.0f; data[1].U = 1.0f; data[1].V = 1.0f; data[1].Nx = 0.0f; data[1].Ny = 1.0f; data[1].Nz = 0.0f; data[2].X = -100.0f; // sw data[2].Y = -100.0f; data[2].Z = -100.0f; data[2].U = 1.0f; data[2].V = 0.0f; data[2].Nx = 0.0f; data[2].Ny = 1.0f; data[2].Nz = 0.0f; data[3].X = 100.0f; // se data[3].Y = -100.0f; data[3].Z = -100.0f; data[3].U = 0.0f; data[3].V = 1.0f; data[3].Nx = 0.0f; data[3].Ny = 1.0f; data[3].Nz = 0.0f; break; case SkyFaceSide.Left: data[0].X = -100.0f; // upper south data[0].Y = 100.0f; data[0].Z = -100.0f; data[0].U = 0.0f; data[0].V = 0.0f; data[0].Nx = 1.0f; data[0].Ny = 0.0f; data[0].Nz = 0.0f; data[1].X = -100.0f; // upper north data[1].Y = 100.0f; data[1].Z = 100.0f; data[1].U = 1.0f; data[1].V = 0.0f; data[1].Nx = 1.0f; data[1].Ny = 0.0f; data[1].Nz = 0.0f; data[2].X = -100.0f; // lower south data[2].Y = -100.0f; data[2].Z = -100.0f; data[2].U = 0.0f; data[2].V = 1.0f; data[2].Nx = 1.0f; data[2].Ny = 0.0f; data[2].Nz = 0.0f; data[3].X = -100.0f; // lower north data[3].Y = -100.0f; data[3].Z = 100.0f; data[3].U = 1.0f; data[3].V = 1.0f; data[3].Nx = 1.0f; data[3].Ny = 0.0f; data[3].Nz = 0.0f; break; case SkyFaceSide.Right: data[0].X = 100.0f; // upper ne data[0].Y = 100.0f; data[0].Z = 100.0f; data[0].U = 0.0f; data[0].V = 0.0f; data[0].Nx = -1.0f; data[0].Ny = 0.0f; data[0].Nz = 0.0f; data[1].X = 100.0f; // upper se data[1].Y = 100.0f; data[1].Z = -100.0f; data[1].U = 1.0f; data[1].V = 0.0f; data[1].Nx = -1.0f; data[1].Ny = 0.0f; data[1].Nz = 0.0f; data[2].X = 100.0f; // lower ne data[2].Y = -100.0f; data[2].Z = 100.0f; data[2].U = 0.0f; data[2].V = 1.0f; data[2].Nx = -1.0f; data[2].Ny = 0.0f; data[2].Nz = 0.0f; data[3].X = 100.0f; // lower se data[3].Y = -100.0f; data[3].Z = -100.0f; data[3].U = 1.0f; data[3].V = 1.0f; data[3].Nx = -1.0f; data[3].Ny = 0.0f; data[3].Nz = 0.0f; break; case SkyFaceSide.Front: data[0].X = -100.0f; // upper nw data[0].Y = 100.0f; data[0].Z = 100.0f; data[0].U = 0.0f; data[0].V = 0.0f; data[0].Nx = 0.0f; data[0].Ny = 0.0f; data[0].Nz = -1.0f; data[1].X = 100.0f; // upper ne data[1].Y = 100.0f; data[1].Z = 100.0f; data[1].U = 1.0f; data[1].V = 0.0f; data[1].Nx = 0.0f; data[1].Ny = 0.0f; data[1].Nz = -1.0f; data[2].X = -100.0f; // lower nw data[2].Y = -100.0f; data[2].Z = 100.0f; data[2].U = 0.0f; data[2].V = 1.0f; data[2].Nx = 0.0f; data[2].Ny = 0.0f; data[2].Nz = -1.0f; data[3].X = 100.0f; // lower ne data[3].Y = -100.0f; data[3].Z = 100.0f; data[3].U = 1.0f; data[3].V = 1.0f; data[3].Nx = 0.0f; data[3].Ny = 0.0f; data[3].Nz = -1.0f; break; case SkyFaceSide.Back: data[0].X = 100.0f; // upper se data[0].Y = 100.0f; data[0].Z = -100.0f; data[0].U = 0.0f; data[0].V = 0.0f; data[0].Nx = 0.0f; data[0].Ny = 0.0f; data[0].Nz = -1.0f; data[1].X = -100.0f; // upper sw data[1].Y = 100.0f; data[1].Z = -100.0f; data[1].U = 1.0f; data[1].V = 0.0f; data[1].Nx = 0.0f; data[1].Ny = 0.0f; data[1].Nz = -1.0f; data[2].X = 100.0f; // lower se data[2].Y = -100.0f; data[2].Z = -100.0f; data[2].U = 0.0f; data[2].V = 1.0f; data[2].Nx = 0.0f; data[2].Ny = 0.0f; data[2].Nz = -1.0f; data[3].X = -100.0f; // lower sw data[3].Y = -100.0f; data[3].Z = -100.0f; data[3].U = 1.0f; data[3].V = 1.0f; data[3].Nx = 0.0f; data[3].Ny = 0.0f; data[3].Nz = -1.0f; break; } this.corners.Write(data); this.vertexBuffer.Unlock(); this.texture = new Texture(GameEngine.Device, textureName); this.valid = true; }
/// <inheritdoc /> public override void Copy(GraphicsBuffer destination, GraphicsBuffer source) => Copy((D3D12GraphicsBuffer)destination, (D3D12GraphicsBuffer)source);
internal static global::System.Runtime.InteropServices.HandleRef getCPtr(GraphicsBuffer obj) { return((obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr); }
/// <inheritdoc /> public override void Copy(GraphicsTexture destination, GraphicsBuffer source) => Copy((VulkanGraphicsTexture)destination, (VulkanGraphicsBuffer)source);
public void FillLightAndReflectionProbeIndices(GraphicsBuffer buffer) { Validate(); FillLightAndReflectionProbeIndicesGraphicsBuffer(ptr, buffer); }
public abstract void Write(byte[] data, ref int offset, Model model, GraphicsBuffer buffer);
public void DrawProcedural(GraphicsBuffer indexBuffer, Matrix4x4 matrix, Material material, int shaderPass, MeshTopology topology, int indexCount) { DrawProcedural(indexBuffer, matrix, material, shaderPass, topology, indexCount, 1); }
public TestShader(GraphicsBuffer <float> buffer, Func <float, float> f) { DestinationBuffer = buffer; this.f = f; }
public void DrawProceduralIndirect(GraphicsBuffer indexBuffer, Matrix4x4 matrix, Material material, int shaderPass, MeshTopology topology, ComputeBuffer bufferWithArgs) { DrawProceduralIndirect(indexBuffer, matrix, material, shaderPass, topology, bufferWithArgs, 0); }
public void SetBuffer(int nameID, GraphicsBuffer buffer) { SetGraphicsBuffer(nameID, buffer); }
public static bool Run(GrassBakeSettings settings, int lod, out Mesh generatedMesh) { GrassLODLevelSettings currentLOD; try { currentLOD = settings.grassLODLevelSettings[lod]; } catch (Exception e) { Console.WriteLine(e); generatedMesh = null; return(false); } DecomposeMesh(currentLOD.grassBladeMesh, 0, out SourceVertex[] sourceGrassBladeVertices, out int[] sourceGrassBladeIndices); int numBlades = (int)((settings.extents.x / settings.numTiles.x) * (settings.extents.y / settings.numTiles.y) / (currentLOD.density * currentLOD.density)); GeneratedVertex[] generatedVertices = new GeneratedVertex[numBlades * sourceGrassBladeVertices.Length]; int[] generatedIndices = new int[numBlades * sourceGrassBladeIndices.Length]; GraphicsBuffer sourceGrassBladeVertexBuffer = new GraphicsBuffer(GraphicsBuffer.Target.Structured, sourceGrassBladeIndices.Length, SOURCE_VERTEX_STRIDE); GraphicsBuffer sourceGrassBladeIndexBuffer = new GraphicsBuffer(GraphicsBuffer.Target.Structured, sourceGrassBladeIndices.Length, SOURCE_INDEX_STRIDE); GraphicsBuffer generatedVertexBuffer = new GraphicsBuffer(GraphicsBuffer.Target.Structured, generatedVertices.Length, GENERATED_VERTEX_STRIDE); GraphicsBuffer generatedIndexBuffer = new GraphicsBuffer(GraphicsBuffer.Target.Structured, generatedIndices.Length, GENERATED_INDEX_STRIDE); ComputeShader shader = settings.computeShader; int idGrassKernel = shader.FindKernel("CSMain"); shader.SetBuffer(idGrassKernel, "_SourceGrassBladeVertices", sourceGrassBladeVertexBuffer); shader.SetBuffer(idGrassKernel, "_SourceGrassBladeIndices", sourceGrassBladeIndexBuffer); shader.SetBuffer(idGrassKernel, "_GeneratedVertices", generatedVertexBuffer); shader.SetBuffer(idGrassKernel, "_GeneratedIndices", generatedIndexBuffer); shader.SetVector("_MinMaxRandomScale", currentLOD.minMaxScale); shader.SetVector("_TileSize", settings.extents / settings.numTiles); shader.SetFloat("_Density", currentLOD.density); shader.SetFloat("_MaxRandomPositionShift", currentLOD.maxRandomPositionShift); shader.SetInt("_NumGrassBladeVertices", sourceGrassBladeVertices.Length); shader.SetInt("_NumGrassBladeIndices", sourceGrassBladeIndices.Length); sourceGrassBladeVertexBuffer.SetData(sourceGrassBladeVertices); sourceGrassBladeIndexBuffer.SetData(sourceGrassBladeIndices); int numBladesRemaining = numBlades; for (int i = 0; i <= generatedVertices.Length / MAX_VERTS_PER_DISPATCH; ++i) { int maxBlades = MAX_VERTS_PER_DISPATCH / sourceGrassBladeVertices.Length; int numBladesToCalculate = numBladesRemaining > maxBlades ? maxBlades : numBladesRemaining; if (numBladesRemaining == 0) { break; } shader.SetInt("_NumBlades", numBladesToCalculate); shader.SetInt("_StartBladeIndex", i * maxBlades); shader.SetInt("_StartVertexIndex", i * Mathf.FloorToInt((float)MAX_VERTS_PER_DISPATCH / sourceGrassBladeVertices.Length) * sourceGrassBladeVertices.Length); shader.GetKernelThreadGroupSizes(idGrassKernel, out uint threadGroupSize, out _, out _); int dispatchSize = Mathf.CeilToInt((float)numBladesToCalculate / threadGroupSize); shader.Dispatch(idGrassKernel, dispatchSize, 1, 1); generatedVertexBuffer.GetData(generatedVertices, i * maxBlades * sourceGrassBladeVertices.Length, 0, numBladesToCalculate * sourceGrassBladeVertices.Length); generatedIndexBuffer.GetData(generatedIndices, i * maxBlades * sourceGrassBladeIndices.Length, 0, numBladesToCalculate * sourceGrassBladeIndices.Length); numBladesRemaining -= numBladesToCalculate; } generatedMesh = ComposeMesh(generatedVertices, generatedIndices); sourceGrassBladeVertexBuffer.Release(); sourceGrassBladeIndexBuffer.Release(); generatedVertexBuffer.Release(); generatedIndexBuffer.Release(); return(true); }
public ModelAttribute(GraphicsBuffer buffer, int offsetInBytes, Format format, int stride, ModelAttributeChannel channel, int index) : this(GetName(channel, index), buffer, offsetInBytes, format, stride, channel, index) { }
private static ShaderGenerator CreateShaderGeneratorWithDelegate(GraphicsBuffer <float> sourceBuffer, GraphicsBuffer <float> destinationBuffer) { StructuredBufferResource <float> source = sourceBuffer.GetStructuredBuffer(); RWStructuredBufferResource <float> destination = destinationBuffer.GetRWStructuredBuffer(); Action <CSInput> action = input => { destination[input.DispatchThreadId.X] = Math.Max(source[input.DispatchThreadId.X], 45); }; return(new ShaderGenerator(action, new ShaderAttribute("compute"), new NumThreadsAttribute(100, 1, 1))); }
public static RWStructuredBufferResource <T> GetRWStructuredBuffer <T>(this GraphicsBuffer <T> buffer) where T : unmanaged { return(new RWStructuredBufferResource <T>()); }
/// <summary> /// Bind the specified <see cref="GraphicsBuffer"/> to this Vertex Array /// </summary> /// <param name="buffer"><see cref="GraphicsBuffer"/> to bind</param> public void BindBuffer(GraphicsBuffer buffer) { Bind(); buffer.Bind(); }