public override void SetResourceSet(uint slot, ResourceSet rs) { if (_resourceSets[slot] == rs) { return; } D3D11ResourceSet d3d11RS = Util.AssertSubtype <ResourceSet, D3D11ResourceSet>(rs); _resourceSets[slot] = d3d11RS; int cbBase = GetConstantBufferBase(slot); int textureBase = GetTextureBase(slot); int samplerBase = GetSamplerBase(slot); D3D11ResourceLayout layout = d3d11RS.Layout; BindableResource[] resources = d3d11RS.Resources; for (int i = 0; i < resources.Length; i++) { BindableResource resource = resources[i]; D3D11ResourceLayout.ResourceBindingInfo rbi = layout.GetDeviceSlotIndex(i); if (resource is D3D11UniformBuffer ub) { BindUniformBuffer(ub, cbBase + rbi.Slot, rbi.Stages); } else if (resource is D3D11TextureView texView) { BindTextureView(texView, textureBase + rbi.Slot, rbi.Stages); } else if (resource is D3D11Sampler sampler) { BindSampler(sampler, samplerBase + rbi.Slot, rbi.Stages); } } }
private List <IDisposable> createTransformationPipelineUniform() { _transformationPipelineBuffer = _factory.CreateBuffer(new BufferDescription(192, BufferUsage.UniformBuffer | BufferUsage.Dynamic)); ResourceLayoutElementDescription resourceLayoutElementDescription = new ResourceLayoutElementDescription("transformPipeline", ResourceKind.UniformBuffer, ShaderStages.Vertex); ResourceLayoutElementDescription[] resourceLayoutElementDescriptions = { resourceLayoutElementDescription }; ResourceLayoutDescription resourceLayoutDescription = new ResourceLayoutDescription(resourceLayoutElementDescriptions); BindableResource[] bindableResources = new BindableResource[] { _transformationPipelineBuffer }; _transformationPipelineResourceLayout = _factory.CreateResourceLayout(resourceLayoutDescription); ResourceSetDescription resourceSetDescription = new ResourceSetDescription(_transformationPipelineResourceLayout, bindableResources); _transformationPipelineResourceSet = _factory.CreateResourceSet(resourceSetDescription); //_graphicsDevice.UpdateBuffer(_transformationPipelineBuffer,0,_camera.ViewMatrix); GraphicsDevice.UpdateBuffer(_transformationPipelineBuffer, 64, Camera.ProjectionMatrix); return(new List <IDisposable>() { _transformationPipelineBuffer, _transformationPipelineResourceLayout, _transformationPipelineResourceSet }); }
public ResourceSetCache(ResourceFactory resourceFactory) { _factory = resourceFactory; _cache = new Dictionary <ResourceSetKey, CacheEntry>(512); _entriesToEvict = new List <ResourceSetKey>(); _array1 = new BindableResource[1]; _array2 = new BindableResource[2]; _array3 = new BindableResource[3]; _array4 = new BindableResource[4]; }
public static DeviceBufferRange GetBufferRange(BindableResource resource, uint additionalOffset) { if (resource is DeviceBufferRange range) { return(new DeviceBufferRange(range.Buffer, range.Offset + additionalOffset, range.SizeInBytes)); } else { DeviceBuffer buffer = (DeviceBuffer)resource; return(new DeviceBufferRange(buffer, additionalOffset, buffer.SizeInBytes)); } }
private void ActivateResourceSet(uint slot, D3D11ResourceSet d3d11RS, bool graphics) { int cbBase = GetConstantBufferBase(slot, graphics); int uaBase = GetUnorderedAccessBase(slot, graphics); int textureBase = GetTextureBase(slot, graphics); int samplerBase = GetSamplerBase(slot, graphics); D3D11ResourceLayout layout = d3d11RS.Layout; BindableResource[] resources = d3d11RS.Resources; for (int i = 0; i < resources.Length; i++) { BindableResource resource = resources[i]; D3D11ResourceLayout.ResourceBindingInfo rbi = layout.GetDeviceSlotIndex(i); switch (rbi.Kind) { case ResourceKind.UniformBuffer: D3D11Buffer uniformBuffer = Util.AssertSubtype <BindableResource, D3D11Buffer>(resource); BindUniformBuffer(uniformBuffer, cbBase + rbi.Slot, rbi.Stages); break; case ResourceKind.StructuredBufferReadOnly: D3D11Buffer storageBufferRO = Util.AssertSubtype <BindableResource, D3D11Buffer>(resource); BindStorageBufferView(storageBufferRO, textureBase + rbi.Slot, rbi.Stages); break; case ResourceKind.StructuredBufferReadWrite: D3D11Buffer storageBuffer = Util.AssertSubtype <BindableResource, D3D11Buffer>(resource); BindUnorderedAccessView(null, storageBuffer.UnorderedAccessView, uaBase + rbi.Slot, rbi.Stages, slot); break; case ResourceKind.TextureReadOnly: D3D11TextureView texView = Util.AssertSubtype <BindableResource, D3D11TextureView>(resource); UnbindUAVTexture(texView.Target); BindTextureView(texView, textureBase + rbi.Slot, rbi.Stages, slot); break; case ResourceKind.TextureReadWrite: D3D11TextureView rwTexView = Util.AssertSubtype <BindableResource, D3D11TextureView>(resource); UnbindSRVTexture(rwTexView.Target); BindUnorderedAccessView(rwTexView.Target, rwTexView.UnorderedAccessView, uaBase + rbi.Slot, rbi.Stages, slot); break; case ResourceKind.Sampler: D3D11Sampler sampler = Util.AssertSubtype <BindableResource, D3D11Sampler>(resource); BindSampler(sampler, samplerBase + rbi.Slot, rbi.Stages); break; default: throw Illegal.Value <ResourceKind>(); } } }
public void SetData(BindableResource resource) { if (resource == null) { throw new ArgumentNullException(nameof(resource)); } if (!_cachedResourceSets.TryGetValue(resource, out var result)) { _cachedResourceSets.Add(resource, result = AddDisposable(_graphicsDevice.ResourceFactory.CreateResourceSet( new ResourceSetDescription(Parameter.ResourceLayout, resource)))); } Data = result; }
private void CreateSizeDependentResources() { renderTargetColorTexture = factory.CreateTexture(TextureDescription.Texture2D( width, height, 1, 1, PixelFormat.R8_G8_B8_A8_UNorm, TextureUsage.RenderTarget | TextureUsage.Sampled)); renderTargetColorTextureView = factory.CreateTextureView(renderTargetColorTexture); renderTargetDepthTexture = factory.CreateTexture(TextureDescription.Texture2D( width, height, 1, 1, PixelFormat.R32_Float, TextureUsage.DepthStencil)); renderTargetFramebuffer = factory.CreateFramebuffer(new FramebufferDescription(renderTargetDepthTexture, renderTargetColorTexture)); // final render pipeline ResourceLayoutElementDescription[] layoutDescriptions = new ResourceLayoutElementDescription[] { new ResourceLayoutElementDescription("ScreenMap", ResourceKind.TextureReadOnly, ShaderStages.Fragment), new ResourceLayoutElementDescription("ScreenMapSampler", ResourceKind.Sampler, ShaderStages.Fragment), }; BindableResource[] bindableResources = new BindableResource[] { renderTargetColorTextureView, graphicsDevice.PointSampler, }; resourceLayout = factory.CreateResourceLayout(new ResourceLayoutDescription(layoutDescriptions)); pipeline = factory.CreateGraphicsPipeline( new GraphicsPipelineDescription( BlendStateDescription.SingleOverrideBlend, new DepthStencilStateDescription( depthTestEnabled: false, depthWriteEnabled: false, comparisonKind: ComparisonKind.Always), new RasterizerStateDescription( cullMode: FaceCullMode.Back, fillMode: PolygonFillMode.Solid, frontFace: FrontFace.Clockwise, depthClipEnabled: false, scissorTestEnabled: false), PrimitiveTopology.TriangleList, new ShaderSetDescription( vertexLayouts: new VertexLayoutDescription[] { new VertexLayoutDescription( new VertexElementDescription("Position", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float3) ) }, shaders: CreateShaders(finalVertexCode, finalFragmentCode)), new ResourceLayout[] { resourceLayout }, swapchain.Framebuffer.OutputDescription) ); resourceSet = factory.CreateResourceSet(new ResourceSetDescription(resourceLayout, bindableResources)); }
internal static TextureView GetTextureView(GraphicsDevice gd, BindableResource resource) { if (resource is TextureView view) { return(view); } else if (resource is Texture tex) { return(tex.GetFullTextureView(gd)); } else { throw new VeldridException( $"Unexpected resource type. Expected Texture or TextureView but found {resource.GetType().Name}"); } }
public static bool GetDeviceBuffer(BindableResource resource, out DeviceBuffer buffer) { if (resource is DeviceBuffer db) { buffer = db; return(true); } else if (resource is DeviceBufferRange range) { buffer = range.Buffer; return(true); } buffer = null; return(false); }
public void SetProperty(string name, BindableResource resource) { var property = EnsureProperty(name); if (resource == null) { switch (property.Parameter.ResourceBinding.Type) { case ResourceKind.StructuredBufferReadOnly: resource = _contentManager.GetNullStructuredBuffer(property.Parameter.ResourceBinding.Size); break; default: throw new InvalidOperationException(); } } property.SetData(resource); }
public void RegenerateDescriptorTables() { Renderer.AddBackgroundUploadTask((d, cl) => { lock (_allocationLock) { if (TextureCount == 0) { return; } if (_poolLayout != null) { //_poolLayout.Dispose(); } if (_poolResourceSet != null) { _poolResourceSet.Dispose(); } //var layoutdesc = new ResourceLayoutDescription( // new ResourceLayoutElementDescription(_resourceName, ResourceKind.TextureReadOnly, ShaderStages.Fragment, TextureCount)); //_poolLayout = d.ResourceFactory.CreateResourceLayout(layoutdesc); BindableResource[] resources = new BindableResource[TextureCount]; for (int i = 0; i < TextureCount; i++) { if (i >= _handles.Count) { resources[i] = _handles[0]._texture; continue; } resources[i] = _handles[i]._texture; if (_handles[i]._texture == null) { resources[i] = _handles[0]._texture; } } _poolResourceSet = d.ResourceFactory.CreateResourceSet(new ResourceSetDescription(_poolLayout, resources)); DescriptorTableDirty = false; } }); }
public void SetProperty(string name, BindableResource resource) { var property = EnsureProperty(name); if (resource == null) { switch (property.Parameter.ResourceBinding.Kind) { case ResourceKind.StructuredBufferReadOnly: resource = _contentManager.GetNullStructuredBuffer(property.Parameter.ResourceBinding.Type.Size); break; case ResourceKind.TextureReadOnly: case ResourceKind.TextureReadWrite: // TODO: This only supports Texture2D shader parameters. resource = _contentManager.NullTexture; break; default: throw new InvalidOperationException(); } } property.SetData(resource); }
private static void ValidateResourceKind(ResourceKind kind, BindableResource resource, uint slot) { switch (kind) { case ResourceKind.UniformBuffer: { if (!Util.GetDeviceBuffer(resource, out DeviceBuffer b) || (b.Usage & BufferUsage.UniformBuffer) == 0) { throw new VeldridException( $"Resource in slot {slot} does not match {nameof(ResourceKind)}.{kind} specified in the {nameof(ResourceLayout)}. " + $"It must be a {nameof(DeviceBuffer)} or {nameof(DeviceBufferRange)} with {nameof(BufferUsage)}.{nameof(BufferUsage.UniformBuffer)}."); } break; } case ResourceKind.StructuredBufferReadOnly: { if (!Util.GetDeviceBuffer(resource, out DeviceBuffer b) || (b.Usage & (BufferUsage.StructuredBufferReadOnly | BufferUsage.StructuredBufferReadWrite)) == 0) { throw new VeldridException( $"Resource in slot {slot} does not match {nameof(ResourceKind)}.{kind} specified in the {nameof(ResourceLayout)}. It must be a {nameof(DeviceBuffer)} with {nameof(BufferUsage)}.{nameof(BufferUsage.StructuredBufferReadOnly)}."); } break; } case ResourceKind.StructuredBufferReadWrite: { if (!Util.GetDeviceBuffer(resource, out DeviceBuffer b) || (b.Usage & BufferUsage.StructuredBufferReadWrite) == 0) { throw new VeldridException( $"Resource in slot {slot} does not match {nameof(ResourceKind)} specified in the {nameof(ResourceLayout)}. It must be a {nameof(DeviceBuffer)} with {nameof(BufferUsage)}.{nameof(BufferUsage.StructuredBufferReadWrite)}."); } break; } case ResourceKind.TextureReadOnly: { if (!(resource is TextureView tv && (tv.Target.Usage & TextureUsage.Sampled) != 0) && !(resource is Texture t && (t.Usage & TextureUsage.Sampled) != 0)) { throw new VeldridException( $"Resource in slot {slot} does not match {nameof(ResourceKind)}.{kind} specified in the " + $"{nameof(ResourceLayout)}. It must be a {nameof(Texture)} or {nameof(TextureView)} whose target " + $"has {nameof(TextureUsage)}.{nameof(TextureUsage.Sampled)}."); } break; } case ResourceKind.TextureReadWrite: { if (!(resource is TextureView tv && (tv.Target.Usage & TextureUsage.Storage) != 0) && !(resource is Texture t && (t.Usage & TextureUsage.Storage) != 0)) { throw new VeldridException( $"Resource in slot {slot} does not match {nameof(ResourceKind)}.{kind} specified in the " + $"{nameof(ResourceLayout)}. It must be a {nameof(Texture)} or {nameof(TextureView)} whose target " + $"has {nameof(TextureUsage)}.{nameof(TextureUsage.Storage)}."); } break; } case ResourceKind.Sampler: { if (!(resource is Sampler s)) { throw new VeldridException( $"Resource in slot {slot} does not match {nameof(ResourceKind)}.{kind} specified in the {nameof(ResourceLayout)}. It must be a {nameof(Sampler)}."); } break; } default: throw Illegal.Value <ResourceKind>(); } }
// TODO: Abstract Resource Crreation for Uniforms, Vertex Layouts, Disposing override protected void CreateResources() { RgbaFloat lightColor = RgbaFloat.LightGrey; var lightLookAt = new Vector4(0, 0, 0, 1); var lightCam = new OrthographicCamera(35, 35, Light.DEFAULT_POSITION, lightLookAt); _sceneRuntimeState.Light = new Light(lightCam, lightColor, 0.1f); // string filePath = Path.Combine(AppContext.BaseDirectory, "Models/sphere.obj"); //string filePath = Path.Combine(AppContext.BaseDirectory, "Models/300_polygon_sphere_100mm.STL"); // string filePath = "Models/sphere_centered.obj"; string filePath = "Models/chinesedragon.dae"; // string filePath = "Models/Box.dae"; _model = AssimpLoader.LoadFromFileWithRealtimeMaterial <VertexPositionNormal>(AppContext.BaseDirectory, filePath, VertexPositionNormal.HenzaiType); //GeometryUtils.GenerateSphericalTextureCoordinatesFor(_model.meshes[0]); /// Uniform 1 - Camera _cameraProjViewBuffer = _factory.CreateBuffer(new BufferDescription(Camera.SizeInBytes, BufferUsage.UniformBuffer | BufferUsage.Dynamic)); var resourceLayoutElementDescription = new ResourceLayoutElementDescription("projViewWorld", ResourceKind.UniformBuffer, ShaderStages.Vertex); ResourceLayoutElementDescription[] resourceLayoutElementDescriptions = { resourceLayoutElementDescription }; var resourceLayoutDescription = new ResourceLayoutDescription(resourceLayoutElementDescriptions); BindableResource[] bindableResources = new BindableResource[] { _cameraProjViewBuffer }; _cameraResourceLayout = _factory.CreateResourceLayout(resourceLayoutDescription); var resourceSetDescription = new ResourceSetDescription(_cameraResourceLayout, bindableResources); _cameraResourceSet = _factory.CreateResourceSet(resourceSetDescription); // Uniform 2 - Material _materialBuffer = _factory.CreateBuffer(new BufferDescription(RealtimeMaterial.SizeInBytes, BufferUsage.UniformBuffer)); var resourceLayoutElementDescriptionMaterial = new ResourceLayoutElementDescription("material", ResourceKind.UniformBuffer, ShaderStages.Fragment); ResourceLayoutElementDescription[] resourceLayoutElementDescriptionsMaterial = { resourceLayoutElementDescriptionMaterial }; var resourceLayoutDescriptionMaterial = new ResourceLayoutDescription(resourceLayoutElementDescriptionsMaterial); BindableResource[] bindableResourcesMaterial = new BindableResource[] { _materialBuffer }; _materialResourceLayout = _factory.CreateResourceLayout(resourceLayoutDescriptionMaterial); var resourceSetDescriptionMaterial = new ResourceSetDescription(_materialResourceLayout, bindableResourcesMaterial); _materialResourceSet = _factory.CreateResourceSet(resourceSetDescriptionMaterial); // Uniform 3 - Light _lightBuffer = _factory.CreateBuffer(new BufferDescription(Light.SizeInBytes, BufferUsage.UniformBuffer)); var resourceLayoutElementDescriptionLight = new ResourceLayoutElementDescription("light", ResourceKind.UniformBuffer, ShaderStages.Fragment); ResourceLayoutElementDescription[] resourceLayoutElementDescriptionsLight = { resourceLayoutElementDescriptionLight }; var resourceLayoutDescriptionLight = new ResourceLayoutDescription(resourceLayoutElementDescriptionsLight); BindableResource[] bindableResourcesLight = new BindableResource[] { _lightBuffer }; _lightResourceLayout = _factory.CreateResourceLayout(resourceLayoutDescriptionLight); var resourceSetDescriptionLight = new ResourceSetDescription(_lightResourceLayout, bindableResourcesLight); _lightResourceSet = _factory.CreateResourceSet(resourceSetDescriptionLight); for (int i = 0; i < _model.MeshCount; i++) { var mesh = _model.GetMesh(i); DeviceBuffer vertexBuffer = _factory.CreateBuffer(new BufferDescription(mesh.Vertices.LengthUnsigned() * VertexPositionNormal.SizeInBytes, BufferUsage.VertexBuffer)); DeviceBuffer indexBuffer = _factory.CreateBuffer(new BufferDescription(mesh.Indices.LengthUnsigned() * sizeof(ushort), BufferUsage.IndexBuffer)); _vertexBuffers.Add(vertexBuffer); _indexBuffers.Add(indexBuffer); GraphicsDevice.UpdateBuffer(vertexBuffer, 0, mesh.Vertices); GraphicsDevice.UpdateBuffer(indexBuffer, 0, mesh.Indices); } VertexLayoutDescription vertexLayout = new VertexLayoutDescription( new VertexElementDescription("Position", VertexElementSemantic.Position, VertexElementFormat.Float3), new VertexElementDescription("Normal", VertexElementSemantic.Normal, VertexElementFormat.Float3) //new VertexElementDescription("UV",VertexElementSemantic.TextureCoordinate,VertexElementFormat.Float2) ); _vertexShader = IO.LoadShader("Phong", ShaderStages.Vertex, GraphicsDevice); _fragmentShader = IO.LoadShader("Phong", ShaderStages.Fragment, GraphicsDevice); GraphicsPipelineDescription pipelineDescription = new GraphicsPipelineDescription() { BlendState = BlendStateDescription.SingleOverrideBlend, DepthStencilState = DepthStencilStateDescription.DepthOnlyLessEqual, RasterizerState = new RasterizerStateDescription( cullMode: FaceCullMode.Back, fillMode: PolygonFillMode.Solid, // Wireframe doesnt seem to work with metal frontFace: FrontFace.Clockwise, depthClipEnabled: true, scissorTestEnabled: false ), PrimitiveTopology = PrimitiveTopology.TriangleList, //ResourceLayouts = new ResourceLayout[] {_cameraResourceLayout,_materialResourceLayout,_lightResourceLayout}, ResourceLayouts = new ResourceLayout[] { _cameraResourceLayout, _lightResourceLayout, _materialResourceLayout }, ShaderSet = new ShaderSetDescription( vertexLayouts: new VertexLayoutDescription[] { vertexLayout }, shaders: new Shader[] { _vertexShader, _fragmentShader } ), Outputs = GraphicsDevice.SwapchainFramebuffer.OutputDescription }; _pipeline = _factory.CreateGraphicsPipeline(pipelineDescription); }
private void ValidateResourceKind(ResourceKind kind, BindableResource resource, uint slot) { switch (kind) { case ResourceKind.UniformBuffer: { if (!(resource is DeviceBuffer b && (b.Usage & BufferUsage.UniformBuffer) == BufferUsage.UniformBuffer)) { throw new VeldridException( $"Resource in slot {slot} does not match {nameof(ResourceKind)}.{kind} specified in the {nameof(ResourceLayout)}. It must be a {nameof(DeviceBuffer)} with {nameof(BufferUsage)}.{nameof(BufferUsage.UniformBuffer)}."); } break; } case ResourceKind.StructuredBufferReadOnly: { if (!(resource is DeviceBuffer b && (b.Usage & (BufferUsage.StructuredBufferReadOnly | BufferUsage.StructuredBufferReadWrite)) != 0)) { throw new VeldridException( $"Resource in slot {slot} does not match {nameof(ResourceKind)}.{kind} specified in the {nameof(ResourceLayout)}. It must be a {nameof(DeviceBuffer)} with {nameof(BufferUsage)}.{nameof(BufferUsage.StructuredBufferReadOnly)}."); } break; } case ResourceKind.StructuredBufferReadWrite: { if (!(resource is DeviceBuffer b && (b.Usage & BufferUsage.StructuredBufferReadWrite) == BufferUsage.StructuredBufferReadWrite)) { throw new VeldridException( $"Resource in slot {slot} does not match {nameof(ResourceKind)} specified in the {nameof(ResourceLayout)}. It must be a {nameof(DeviceBuffer)} with {nameof(BufferUsage)}.{nameof(BufferUsage.StructuredBufferReadWrite)}."); } break; } case ResourceKind.TextureReadOnly: { if (!(resource is TextureView tv && (tv.Target.Usage & TextureUsage.Sampled) == TextureUsage.Sampled)) { throw new VeldridException( $"Resource in slot {slot} does not match {nameof(ResourceKind)}.{kind} specified in the {nameof(ResourceLayout)}. It must be a {nameof(TextureView)} whose target has {nameof(TextureUsage)}.{nameof(TextureUsage.Sampled)}."); } break; } case ResourceKind.TextureReadWrite: { if (!(resource is TextureView tv && (tv.Target.Usage & TextureUsage.Storage) == TextureUsage.Storage)) { throw new VeldridException( $"Resource in slot {slot} does not match {nameof(ResourceKind)}.{kind} specified in the {nameof(ResourceLayout)}. It must be a {nameof(TextureView)} whose target has {nameof(TextureUsage)}.{nameof(TextureUsage.Storage)}."); } break; } case ResourceKind.Sampler: { if (!(resource is Sampler s)) { throw new VeldridException( $"Resource in slot {slot} does not match {nameof(ResourceKind)}.{kind} specified in the {nameof(ResourceLayout)}. It must be a {nameof(Sampler)}."); } break; } default: Debug.Fail($"Unexpected ResourceKind: {kind}."); break; } }
override protected void CreateResources() { _cameraProjViewBuffer = _factory.CreateBuffer(new BufferDescription(Camera.SizeInBytes, BufferUsage.UniformBuffer | BufferUsage.Dynamic)); ResourceLayoutElementDescription resourceLayoutElementDescription = new ResourceLayoutElementDescription("projView", ResourceKind.UniformBuffer, ShaderStages.Vertex); ResourceLayoutElementDescription[] resourceLayoutElementDescriptions = { resourceLayoutElementDescription }; ResourceLayoutDescription resourceLayoutDescription = new ResourceLayoutDescription(resourceLayoutElementDescriptions); BindableResource[] bindableResources = new BindableResource[] { _cameraProjViewBuffer }; _resourceLayout = _factory.CreateResourceLayout(resourceLayoutDescription); ResourceSetDescription resourceSetDescription = new ResourceSetDescription(_resourceLayout, bindableResources); _cameraResourceSet = _factory.CreateResourceSet(resourceSetDescription); ImageSharpTexture NameImage = new ImageSharpTexture(Path.Combine(AppContext.BaseDirectory, "Textures", "Name.png")); Texture cubeTexture = NameImage.CreateDeviceTexture(GraphicsDevice, _factory); TextureView cubeTextureView = _factory.CreateTextureView(cubeTexture); ResourceLayout textureLayout = _factory.CreateResourceLayout( new ResourceLayoutDescription( new ResourceLayoutElementDescription("Texture", ResourceKind.TextureReadOnly, ShaderStages.Fragment), new ResourceLayoutElementDescription("Sampler", ResourceKind.Sampler, ShaderStages.Fragment))); _textureResourceSet = _factory.CreateResourceSet(new ResourceSetDescription( textureLayout, cubeTextureView, GraphicsDevice.LinearSampler)); Mesh <VertexPositionTexture> texturedCube = GeometryFactory.GenerateTexturedCube(false); ushort[] cubeIndicies = GeometryFactory.generateCubeIndicies_TriangleList_CW(); // declare (VBO) buffers _vertexBuffer = _factory.CreateBuffer(new BufferDescription(texturedCube.Vertices.LengthUnsigned() * VertexPositionTexture.SizeInBytes, BufferUsage.VertexBuffer)); _indexBuffer = _factory.CreateBuffer(new BufferDescription(cubeIndicies.LengthUnsigned() * sizeof(ushort), BufferUsage.IndexBuffer)); // fill buffers with data GraphicsDevice.UpdateBuffer(_vertexBuffer, 0, texturedCube.Vertices); GraphicsDevice.UpdateBuffer(_indexBuffer, 0, cubeIndicies); //graphicsDevice.UpdateBuffer(_cameraProjViewBuffer,0,camera.ViewMatrix); //graphicsDevice.UpdateBuffer(_cameraProjViewBuffer,64,camera.ProjectionMatrix); VertexLayoutDescription vertexLayout = new VertexLayoutDescription( new VertexElementDescription("Position", VertexElementSemantic.Position, VertexElementFormat.Float3), new VertexElementDescription("UV", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2) ); _vertexShader = IO.LoadShader("Texture", ShaderStages.Vertex, GraphicsDevice); _fragmentShader = IO.LoadShader("Texture", ShaderStages.Fragment, GraphicsDevice); GraphicsPipelineDescription pipelineDescription = new GraphicsPipelineDescription() { BlendState = BlendStateDescription.SingleOverrideBlend, DepthStencilState = DepthStencilStateDescription.DepthOnlyLessEqual, RasterizerState = new RasterizerStateDescription( cullMode: FaceCullMode.Back, fillMode: PolygonFillMode.Solid, frontFace: FrontFace.Clockwise, depthClipEnabled: true, scissorTestEnabled: false ), PrimitiveTopology = PrimitiveTopology.TriangleList, ResourceLayouts = new ResourceLayout[] { _resourceLayout, textureLayout }, ShaderSet = new ShaderSetDescription( vertexLayouts: new VertexLayoutDescription[] { vertexLayout }, shaders: new Shader[] { _vertexShader, _fragmentShader } ), Outputs = GraphicsDevice.SwapchainFramebuffer.OutputDescription }; _pipeline = _factory.CreateGraphicsPipeline(pipelineDescription); }
private void LoadMesh(GraphicsDevice device, int index) { var factory = device.ResourceFactory; var mesh = meshes[index]; var vertexBuffer = vertexBuffers[index] = factory.CreateBuffer(new BufferDescription((uint)(mesh.Vertices.Length * typeof(VertexPositionNormalTexture).Size()), BufferUsage.VertexBuffer)); device.UpdateBuffer(vertexBuffer, 0, mesh.Vertices); var indexBuffer = indexBuffers[index] = factory.CreateBuffer(new BufferDescription((uint)(mesh.Indices.Length * typeof(ushort).Size()), BufferUsage.IndexBuffer)); device.UpdateBuffer(indexBuffer, 0, mesh.Indices); var mapNames = meshMapNames[index]; var texturesToLoad = mapNames .Values .Distinct() .Where(path => !textureViews.ContainsKey(path)) .ToArray(); for (var j = 0; j < texturesToLoad.Length; j++) { var path = texturesToLoad[j]; if (!textures.ContainsKey(path)) { var decoder = MediaType.GuessByFileName(path) .Where(ImageDecoderSet.Default.ContainsKey) .Select(type => ImageDecoderSet.Default[type]) .FirstOrDefault(); using var stream = dataSource.GetStream(path); var image = decoder.Deserialize(stream); var imageData = image.GetData(); var imageWidth = (uint)image.Info.Dimensions.Width; var imageHeight = (uint)image.Info.Dimensions.Height; var texture = factory.CreateTexture(new TextureDescription( imageWidth, imageHeight, 1, 1, 1, PixelFormat.R8_G8_B8_A8_UNorm, TextureUsage.Sampled, TextureType.Texture2D)); textures[path] = texture; textureViews[path] = factory.CreateTextureView(texture); device.UpdateTexture( texture, imageData, 0, 0, 0, imageWidth, imageHeight, 1, 0, 0); } } var elements = mapNames.Keys.Select(name => new ResourceLayoutElementDescription() { Name = name, Kind = ResourceKind.TextureReadOnly, Stages = ShaderStages.Fragment }).ToArray(); var layout = factory.CreateResourceLayout(new ResourceLayoutDescription(elements)); var resources = new BindableResource[elements.Length]; for (var i = 0; i < elements.Length; ++i) { resources[i] = textureViews[mapNames[elements[i].Name]]; } resourceSets[index] = factory.CreateResourceSet(new ResourceSetDescription(layout, resources)); }
public void AddResource(string name, ResourceKind kind, BindableResource resource) { AddResource(name, kind, resource, ShaderStages.Compute); }
protected override void CreateResources(ResourceFactory factory) { _instanceCount = 8000u; _camera.Position = new Vector3(-36f, 20f, 100f); _camera.Pitch = -0.3f; _camera.Yaw = 0.1f; _cameraProjViewBuffer = factory.CreateBuffer( new BufferDescription((uint)(Unsafe.SizeOf <Matrix4x4>() * 2), BufferUsage.UniformBuffer | BufferUsage.Dynamic)); _lightInfoBuffer = factory.CreateBuffer(new BufferDescription(32, BufferUsage.UniformBuffer | BufferUsage.Dynamic)); _rotationInfoBuffer = factory.CreateBuffer(new BufferDescription(16, BufferUsage.UniformBuffer | BufferUsage.Dynamic)); _lightDir = Vector3.Normalize(new Vector3(0.3f, -0.75f, -0.3f)); VertexLayoutDescription sharedVertexLayout = new VertexLayoutDescription( new VertexElementDescription("Position", VertexElementSemantic.Position, VertexElementFormat.Float3), new VertexElementDescription("Normal", VertexElementSemantic.Normal, VertexElementFormat.Float3), new VertexElementDescription("TexCoord", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2)); bool etc2Supported = GraphicsDevice.GetPixelFormatSupport( PixelFormat.ETC2_R8_G8_B8_UNorm, TextureType.Texture2D, TextureUsage.Sampled); PixelFormat pixelFormat = etc2Supported ? PixelFormat.ETC2_R8_G8_B8_UNorm : PixelFormat.BC3_UNorm; byte[] rockTextureData = LoadEmbeddedAsset <byte[]>( etc2Supported ? "texturearray_rocks_etc2_unorm.binary" : "texturearray_rocks_bc3_unorm.binary"); Texture rockTexture = KtxFile.LoadTexture( GraphicsDevice, ResourceFactory, rockTextureData, pixelFormat); TextureView rockTextureView = ResourceFactory.CreateTextureView(rockTexture); ResourceLayoutElementDescription[] resourceLayoutElementDescriptions = { new ResourceLayoutElementDescription("ProjView", ResourceKind.UniformBuffer, ShaderStages.Vertex), new ResourceLayoutElementDescription("RotationInfo", ResourceKind.UniformBuffer, ShaderStages.Vertex), new ResourceLayoutElementDescription("LightInfo", ResourceKind.UniformBuffer, ShaderStages.Fragment), }; ResourceLayoutDescription resourceLayoutDescription = new ResourceLayoutDescription(resourceLayoutElementDescriptions); ResourceLayout sharedLayout = factory.CreateResourceLayout(resourceLayoutDescription); ResourceLayoutElementDescription[] textureLayoutDescriptions = { new ResourceLayoutElementDescription("Tex", ResourceKind.TextureReadOnly, ShaderStages.Fragment), new ResourceLayoutElementDescription("Samp", ResourceKind.Sampler, ShaderStages.Fragment) }; ResourceLayout textureLayout = factory.CreateResourceLayout(new ResourceLayoutDescription(textureLayoutDescriptions)); BindableResource[] bindableResources = new BindableResource[] { _cameraProjViewBuffer, _rotationInfoBuffer, _lightInfoBuffer }; ResourceSetDescription resourceSetDescription = new ResourceSetDescription(sharedLayout, bindableResources); _sharedResourceSet = factory.CreateResourceSet(resourceSetDescription); BindableResource[] instanceBindableResources = { rockTextureView, GraphicsDevice.LinearSampler }; _instanceTextureSet = factory.CreateResourceSet(new ResourceSetDescription(textureLayout, instanceBindableResources)); ProcessedModel rock = LoadEmbeddedAsset <ProcessedModel>("rock01.binary"); _rockModel = rock.MeshParts[0].CreateDeviceResources(GraphicsDevice, ResourceFactory); VertexLayoutDescription vertexLayoutPerInstance = new VertexLayoutDescription( new VertexElementDescription("InstancePosition", VertexElementSemantic.Position, VertexElementFormat.Float3), new VertexElementDescription("InstanceRotation", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float3), new VertexElementDescription("InstanceScale", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float3), new VertexElementDescription("InstanceTexArrayIndex", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Int1)); vertexLayoutPerInstance.InstanceStepRate = 1; _instanceVB = ResourceFactory.CreateBuffer(new BufferDescription(InstanceInfo.Size * _instanceCount, BufferUsage.VertexBuffer)); InstanceInfo[] infos = new InstanceInfo[_instanceCount]; Random r = new Random(); float orbitDistance = 50f; for (uint i = 0; i < _instanceCount / 2; i++) { float angle = (float)(r.NextDouble() * Math.PI * 2); infos[i] = new InstanceInfo( new Vector3( ((float)Math.Cos(angle) * orbitDistance) + (float)(-10 + r.NextDouble() * 20), (float)(-1.5 + r.NextDouble() * 3), ((float)Math.Sin(angle) * orbitDistance) + (float)(-10 + r.NextDouble() * 20)), new Vector3( (float)(r.NextDouble() * Math.PI * 2), (float)(r.NextDouble() * Math.PI * 2), (float)(r.NextDouble() * Math.PI * 2)), new Vector3((float)(0.65 + r.NextDouble() * 0.35)), r.Next(0, (int)rockTexture.ArrayLayers)); } orbitDistance = 100f; for (uint i = _instanceCount / 2; i < _instanceCount; i++) { float angle = (float)(r.NextDouble() * Math.PI * 2); infos[i] = new InstanceInfo( new Vector3( ((float)Math.Cos(angle) * orbitDistance) + (float)(-10 + r.NextDouble() * 20), (float)(-1.5 + r.NextDouble() * 3), ((float)Math.Sin(angle) * orbitDistance) + (float)(-10 + r.NextDouble() * 20)), new Vector3( (float)(r.NextDouble() * Math.PI * 2), (float)(r.NextDouble() * Math.PI * 2), (float)(r.NextDouble() * Math.PI * 2)), new Vector3((float)(0.65 + r.NextDouble() * 0.35)), r.Next(0, (int)rockTexture.ArrayLayers)); } GraphicsDevice.UpdateBuffer(_instanceVB, 0, infos); Shader instanceVS = LoadShader(ResourceFactory, "Instance", ShaderStages.Vertex, "VS"); Shader instanceFS = LoadShader(ResourceFactory, "Instance", ShaderStages.Fragment, "FS"); GraphicsPipelineDescription pipelineDescription = new GraphicsPipelineDescription() { BlendState = BlendStateDescription.SingleOverrideBlend, DepthStencilState = new DepthStencilStateDescription( depthTestEnabled: true, depthWriteEnabled: true, comparisonKind: ComparisonKind.LessEqual), RasterizerState = new RasterizerStateDescription( cullMode: FaceCullMode.Back, fillMode: PolygonFillMode.Solid, frontFace: FrontFace.Clockwise, depthClipEnabled: true, scissorTestEnabled: false ), PrimitiveTopology = PrimitiveTopology.TriangleList, ResourceLayouts = new ResourceLayout[] { sharedLayout, textureLayout }, ShaderSet = new ShaderSetDescription( // The ordering of layouts directly impacts shader layout schemes vertexLayouts: new VertexLayoutDescription[] { sharedVertexLayout, vertexLayoutPerInstance }, shaders: new Shader[] { instanceVS, instanceFS } ), Outputs = MainSwapchain.Framebuffer.OutputDescription }; _instancePipeline = factory.CreateGraphicsPipeline(pipelineDescription); // Create planet Pipeline // Almost everything is the same as the rock Pipeline, // except no instance vertex buffer is needed, and different shaders are used. pipelineDescription.ShaderSet = new ShaderSetDescription( new[] { sharedVertexLayout }, new[] { LoadShader(ResourceFactory, "Planet", ShaderStages.Vertex, "VS"), LoadShader(ResourceFactory, "Planet", ShaderStages.Fragment, "FS"), }); _planetPipeline = ResourceFactory.CreateGraphicsPipeline(pipelineDescription); ProcessedModel planet = LoadEmbeddedAsset <ProcessedModel>("sphere.binary"); _planetModel = planet.MeshParts[0].CreateDeviceResources(GraphicsDevice, ResourceFactory); byte[] planetTexData = LoadEmbeddedAsset <byte[]>( etc2Supported ? "lavaplanet_etc2_unorm.binary" : "lavaplanet_bc3_unorm.binary"); Texture planetTexture = KtxFile.LoadTexture(GraphicsDevice, ResourceFactory, planetTexData, pixelFormat); TextureView planetTextureView = ResourceFactory.CreateTextureView(planetTexture); _planetTextureSet = ResourceFactory.CreateResourceSet(new ResourceSetDescription(textureLayout, planetTextureView, GraphicsDevice.Aniso4xSampler)); // Starfield resources ResourceLayout invCameraInfoLayout = ResourceFactory.CreateResourceLayout(new ResourceLayoutDescription( new ResourceLayoutElementDescription("InvCameraInfo", ResourceKind.UniformBuffer, ShaderStages.Fragment))); _viewInfoBuffer = ResourceFactory.CreateBuffer(new BufferDescription((uint)Unsafe.SizeOf <InvCameraInfo>(), BufferUsage.UniformBuffer | BufferUsage.Dynamic)); _viewInfoSet = ResourceFactory.CreateResourceSet(new ResourceSetDescription(invCameraInfoLayout, _viewInfoBuffer)); ShaderSetDescription starfieldShaders = new ShaderSetDescription( Array.Empty <VertexLayoutDescription>(), new[] { LoadShader(ResourceFactory, "Starfield", ShaderStages.Vertex, "VS"), LoadShader(ResourceFactory, "Starfield", ShaderStages.Fragment, "FS"), }); _starfieldPipeline = ResourceFactory.CreateGraphicsPipeline(new GraphicsPipelineDescription( BlendStateDescription.SingleOverrideBlend, DepthStencilStateDescription.Disabled, RasterizerStateDescription.CullNone, PrimitiveTopology.TriangleList, starfieldShaders, new[] { invCameraInfoLayout }, MainSwapchain.Framebuffer.OutputDescription)); _commandList = factory.CreateCommandList(); }
protected void AddResource(string name, ResourceKind kind, BindableResource resource, ShaderStages stage) { LayoutElements.Add(new ResourceLayoutElementDescription(name, kind, stage)); ResourceElements.Add(resource); ResourceNames[name] = ResourceElements.Count - 1; }
public new void AddResource(string name, ResourceKind kind, BindableResource resource, ShaderStages stage = ShaderStages.Fragment) { base.AddResource(name, kind, resource, stage); }
protected override void CreateResources(ResourceFactory factory) { _instanceCount = 1 << 14; _camera.Position = new Vector3(-36f, 20f, 100f); _camera.Pitch = -0.3f; _camera.Yaw = 0.1f; _cameraProjViewBuffer = factory.CreateBuffer( new BufferDescription((uint)(Unsafe.SizeOf <Matrix4x4>() * 2), BufferUsage.UniformBuffer | BufferUsage.Dynamic)); _lightInfoBuffer = factory.CreateBuffer(new BufferDescription(32, BufferUsage.UniformBuffer | BufferUsage.Dynamic)); _rotationInfoBuffer = factory.CreateBuffer(new BufferDescription(16, BufferUsage.UniformBuffer | BufferUsage.Dynamic)); _lightDir = Vector3.Normalize(new Vector3(0.3f, -0.75f, -0.3f)); VertexLayoutDescription sharedVertexLayout = new VertexLayoutDescription( new VertexElementDescription("Position", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float3), new VertexElementDescription("Normal", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float3), new VertexElementDescription("TexCoord", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2)); bool etc2Supported = GraphicsDevice.GetPixelFormatSupport( PixelFormat.ETC2_R8_G8_B8_UNorm, TextureType.Texture2D, TextureUsage.Sampled); PixelFormat pixelFormat = etc2Supported ? PixelFormat.ETC2_R8_G8_B8_UNorm : PixelFormat.BC3_UNorm; byte[] rockTextureData = LoadEmbeddedAsset <byte[]>( etc2Supported ? "texturearray_rocks_etc2_unorm.binary" : "texturearray_rocks_bc3_unorm.binary"); Texture rockTexture = KtxFile.LoadTexture( GraphicsDevice, ResourceFactory, rockTextureData, pixelFormat); TextureView rockTextureView = ResourceFactory.CreateTextureView(rockTexture); ResourceLayoutElementDescription[] resourceLayoutElementDescriptions = { new ResourceLayoutElementDescription("LightInfo", ResourceKind.UniformBuffer, ShaderStages.Fragment), new ResourceLayoutElementDescription("ProjView", ResourceKind.UniformBuffer, ShaderStages.Vertex), new ResourceLayoutElementDescription("RotationInfo", ResourceKind.UniformBuffer, ShaderStages.Vertex), }; ResourceLayoutDescription resourceLayoutDescription = new ResourceLayoutDescription(resourceLayoutElementDescriptions); ResourceLayout sharedLayout = factory.CreateResourceLayout(resourceLayoutDescription); ResourceLayoutElementDescription[] textureLayoutDescriptions = { new ResourceLayoutElementDescription("Tex", ResourceKind.TextureReadOnly, ShaderStages.Fragment), new ResourceLayoutElementDescription("Samp", ResourceKind.Sampler, ShaderStages.Fragment) }; ResourceLayout textureLayout = factory.CreateResourceLayout(new ResourceLayoutDescription(textureLayoutDescriptions)); BindableResource[] bindableResources = new BindableResource[] { _lightInfoBuffer, _cameraProjViewBuffer, _rotationInfoBuffer }; ResourceSetDescription resourceSetDescription = new ResourceSetDescription(sharedLayout, bindableResources); _sharedResourceSet = factory.CreateResourceSet(resourceSetDescription); BindableResource[] instanceBindableResources = { rockTextureView, GraphicsDevice.LinearSampler }; _instanceTextureSet = factory.CreateResourceSet(new ResourceSetDescription(textureLayout, instanceBindableResources)); ProcessedModel rock = LoadEmbeddedAsset <ProcessedModel>("sphere.binary"); _rockModel = rock.MeshParts[0].CreateDeviceResources(GraphicsDevice, ResourceFactory); VertexLayoutDescription vertexLayoutPerInstancePos = new VertexLayoutDescription( new VertexElementDescription("InstancePosition", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float3)); VertexLayoutDescription vertexLayoutPerInstanceScale = new VertexLayoutDescription( new VertexElementDescription("InstanceScale", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float3)); VertexLayoutDescription vertexLayoutPerInstanceColor = new VertexLayoutDescription( new VertexElementDescription("InstanceColor", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float3)); vertexLayoutPerInstancePos.InstanceStepRate = 1; vertexLayoutPerInstanceScale.InstanceStepRate = 1; vertexLayoutPerInstanceColor.InstanceStepRate = 1; _instanceVBPos = ResourceFactory.CreateBuffer(new BufferDescription(Vector3.Size * _instanceCount, BufferUsage.VertexBuffer)); _instanceVBScale = ResourceFactory.CreateBuffer(new BufferDescription(Vector3.Size * _instanceCount, BufferUsage.VertexBuffer)); _instanceVBColor = ResourceFactory.CreateBuffer(new BufferDescription(Vector3.Size * _instanceCount, BufferUsage.VertexBuffer)); Vector3[] instancePos = new Vector3[_instanceCount]; Vector3[] instanceScale = new Vector3[_instanceCount]; Vector3[] instanceColors = new Vector3[_instanceCount]; Random r = new Random(); for (uint i = 0; i < _instanceCount; i++) { instancePos[i] = new Vector3( 1000.0f * ((float)r.NextDouble() - 0.5f), 200.0f * ((float)r.NextDouble() - 0.5f), 1000.0f * ((float)r.NextDouble() - 0.5f)); instanceScale[i] = new Vector3((float)(r.NextDouble() * 0.3)); instanceColors[i] = new Vector3((float)r.NextDouble() * 0.5f + 0.5f, (float)r.NextDouble() * 0.5f + 0.5f, (float)r.NextDouble() * 0.5f + 0.5f); } GraphicsDevice.UpdateBuffer(_instanceVBPos, 0, instancePos); GraphicsDevice.UpdateBuffer(_instanceVBScale, 0, instanceScale); GraphicsDevice.UpdateBuffer(_instanceVBColor, 0, instanceColors); GraphicsPipelineDescription pipelineDescriptionRocks = new GraphicsPipelineDescription() { BlendState = BlendStateDescription.SingleOverrideBlend, DepthStencilState = new DepthStencilStateDescription( depthTestEnabled: true, depthWriteEnabled: true, comparisonKind: ComparisonKind.LessEqual), RasterizerState = new RasterizerStateDescription( cullMode: FaceCullMode.Back, fillMode: PolygonFillMode.Solid, frontFace: FrontFace.Clockwise, depthClipEnabled: true, scissorTestEnabled: false ), PrimitiveTopology = PrimitiveTopology.TriangleList, ResourceLayouts = new ResourceLayout[] { sharedLayout, textureLayout }, ShaderSet = new ShaderSetDescription( // The ordering of layouts directly impacts shader layout schemes vertexLayouts: new VertexLayoutDescription[] { sharedVertexLayout, vertexLayoutPerInstancePos, vertexLayoutPerInstanceScale, vertexLayoutPerInstanceColor }, shaders: LoadShaders("Instance") ), Outputs = MainSwapchain.Framebuffer.OutputDescription }; _instancePipeline = factory.CreateGraphicsPipeline(pipelineDescriptionRocks); // Starfield resources ResourceLayout invCameraInfoLayout = ResourceFactory.CreateResourceLayout(new ResourceLayoutDescription( new ResourceLayoutElementDescription("InvCameraInfo", ResourceKind.UniformBuffer, ShaderStages.Fragment))); _viewInfoBuffer = ResourceFactory.CreateBuffer(new BufferDescription((uint)Unsafe.SizeOf <MatrixPair>(), BufferUsage.UniformBuffer | BufferUsage.Dynamic)); _commandList = factory.CreateCommandList(); }
// TODO: Abstract Resource Crreation for Uniforms, Vertex Layouts, Disposing override protected void CreateResources() { //string filePath = Path.Combine(AppContext.BaseDirectory, "Models/sphere.obj"); // huge //string filePath = Path.Combine(AppContext.BaseDirectory, "Models/sphere_centered.obj"); // no texture coordiantes string filePath = "armor/armor.dae"; _model = AssimpLoader.LoadFromFileWithRealtimeMaterial <VertexPositionNormalTextureTangent>(AppContext.BaseDirectory, filePath, VertexPositionNormalTextureTangent.HenzaiType); //GeometryUtils.GenerateSphericalTextureCoordinatesFor(_model.meshes[0], UVMappingTypes.Spherical_Coordinates,true); GeometryUtils.GenerateTangentSpaceFor(_model); // _model = new Model<VertexPositionNormalTextureTangent>(GeometryFactory.generateSphere(100,100,1.0f)); /// Uniform 1 - Camera _cameraProjViewBuffer = _factory.CreateBuffer(new BufferDescription(192, BufferUsage.UniformBuffer | BufferUsage.Dynamic)); var resourceLayoutElementDescription = new ResourceLayoutElementDescription("projViewWorld", ResourceKind.UniformBuffer, ShaderStages.Vertex); ResourceLayoutElementDescription[] resourceLayoutElementDescriptions = { resourceLayoutElementDescription }; var resourceLayoutDescription = new ResourceLayoutDescription(resourceLayoutElementDescriptions); BindableResource[] bindableResources = new BindableResource[] { _cameraProjViewBuffer }; _cameraResourceLayout = _factory.CreateResourceLayout(resourceLayoutDescription); var resourceSetDescription = new ResourceSetDescription(_cameraResourceLayout, bindableResources); _cameraResourceSet = _factory.CreateResourceSet(resourceSetDescription); // Uniform 2 - Material _materialBuffer = _factory.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer)); var resourceLayoutElementDescriptionMaterial = new ResourceLayoutElementDescription("material", ResourceKind.UniformBuffer, ShaderStages.Fragment); ResourceLayoutElementDescription[] resourceLayoutElementDescriptionsMaterial = { resourceLayoutElementDescriptionMaterial }; var resourceLayoutDescriptionMaterial = new ResourceLayoutDescription(resourceLayoutElementDescriptionsMaterial); BindableResource[] bindableResourcesMaterial = new BindableResource[] { _materialBuffer }; _materialResourceLayout = _factory.CreateResourceLayout(resourceLayoutDescriptionMaterial); var resourceSetDescriptionMaterial = new ResourceSetDescription(_materialResourceLayout, bindableResourcesMaterial); _materialResourceSet = _factory.CreateResourceSet(resourceSetDescriptionMaterial); // Uniform 3 - Light _lightBuffer = _factory.CreateBuffer(new BufferDescription(16, BufferUsage.UniformBuffer)); var resourceLayoutElementDescriptionLight = new ResourceLayoutElementDescription("light", ResourceKind.UniformBuffer, ShaderStages.Vertex); ResourceLayoutElementDescription[] resourceLayoutElementDescriptionsLight = { resourceLayoutElementDescriptionLight }; var resourceLayoutDescriptionLight = new ResourceLayoutDescription(resourceLayoutElementDescriptionsLight); BindableResource[] bindableResourcesLight = new BindableResource[] { _lightBuffer }; _lightResourceLayout = _factory.CreateResourceLayout(resourceLayoutDescriptionLight); var resourceSetDescriptionLight = new ResourceSetDescription(_lightResourceLayout, bindableResourcesLight); _lightResourceSet = _factory.CreateResourceSet(resourceSetDescriptionLight); for (int i = 0; i < _model.MeshCount; i++) { var mesh = _model.GetMesh(i); DeviceBuffer vertexBuffer = _factory.CreateBuffer(new BufferDescription(mesh.Vertices.LengthUnsigned() * VertexPositionNormalTextureTangent.SizeInBytes, BufferUsage.VertexBuffer)); DeviceBuffer indexBuffer = _factory.CreateBuffer(new BufferDescription(mesh.Indices.LengthUnsigned() * sizeof(ushort), BufferUsage.IndexBuffer)); _vertexBuffers.Add(vertexBuffer); _indexBuffers.Add(indexBuffer); GraphicsDevice.UpdateBuffer(vertexBuffer, 0, mesh.Vertices); GraphicsDevice.UpdateBuffer(indexBuffer, 0, mesh.Indices); } //Texture Samper // ImageSharpTexture diffuseTexture = new ImageSharpTexture(Path.Combine(AppContext.BaseDirectory, "Textures", "earth.jpg")); // ImageSharpTexture diffuseTexture = new ImageSharpTexture(Path.Combine(AppContext.BaseDirectory, "Textures", "Water.jpg")); ImageSharpTexture diffuseTexture = new ImageSharpTexture(Path.Combine(AppContext.BaseDirectory, "armor", "diffuse.png")); Texture sphereDiffuseTexture = diffuseTexture.CreateDeviceTexture(GraphicsDevice, _factory); TextureView sphereDiffuseTextureView = _factory.CreateTextureView(sphereDiffuseTexture); // ImageSharpTexture normalTexture = new ImageSharpTexture(Path.Combine(AppContext.BaseDirectory, "Textures", "WaterNorm.jpg")); ImageSharpTexture normalTexture = new ImageSharpTexture(Path.Combine(AppContext.BaseDirectory, "armor", "normal.png")); Texture sphereNormalTexture = normalTexture.CreateDeviceTexture(GraphicsDevice, _factory); TextureView sphereNormalTextureView = _factory.CreateTextureView(sphereNormalTexture); ResourceLayout textureLayout = _factory.CreateResourceLayout( new ResourceLayoutDescription( new ResourceLayoutElementDescription("DiffuseTexture", ResourceKind.TextureReadOnly, ShaderStages.Fragment), new ResourceLayoutElementDescription("DiffuseSampler", ResourceKind.Sampler, ShaderStages.Fragment), new ResourceLayoutElementDescription("NormTexture", ResourceKind.TextureReadOnly, ShaderStages.Fragment), new ResourceLayoutElementDescription("NormSampler", ResourceKind.Sampler, ShaderStages.Fragment) )); var sampler = _factory.CreateSampler(new SamplerDescription { AddressModeU = SamplerAddressMode.Wrap, AddressModeV = SamplerAddressMode.Wrap, AddressModeW = SamplerAddressMode.Wrap, Filter = SamplerFilter.MinLinear_MagLinear_MipLinear, LodBias = 0, MinimumLod = 0, MaximumLod = uint.MaxValue, MaximumAnisotropy = 0, }); _textureResourceSet = _factory.CreateResourceSet(new ResourceSetDescription( textureLayout, sphereDiffuseTextureView, GraphicsDevice.LinearSampler, sphereNormalTextureView, sampler )); VertexLayoutDescription vertexLayout = new VertexLayoutDescription( new VertexElementDescription("Position", VertexElementSemantic.Position, VertexElementFormat.Float3), new VertexElementDescription("Normal", VertexElementSemantic.Normal, VertexElementFormat.Float3), new VertexElementDescription("UV", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2), new VertexElementDescription("Tangent", VertexElementSemantic.Normal, VertexElementFormat.Float3) ); _vertexShader = IO.LoadShader("PhongTexture", ShaderStages.Vertex, GraphicsDevice); _fragmentShader = IO.LoadShader("PhongTexture", ShaderStages.Fragment, GraphicsDevice); GraphicsPipelineDescription pipelineDescription = new GraphicsPipelineDescription() { BlendState = BlendStateDescription.SingleOverrideBlend, DepthStencilState = DepthStencilStateDescription.DepthOnlyLessEqual, RasterizerState = new RasterizerStateDescription( cullMode: FaceCullMode.Back, fillMode: PolygonFillMode.Solid, frontFace: FrontFace.Clockwise, depthClipEnabled: true, scissorTestEnabled: false ), PrimitiveTopology = PrimitiveTopology.TriangleList, ResourceLayouts = new ResourceLayout[] { _cameraResourceLayout, _lightResourceLayout, _materialResourceLayout, textureLayout }, ShaderSet = new ShaderSetDescription( vertexLayouts: new VertexLayoutDescription[] { vertexLayout }, shaders: new Shader[] { _vertexShader, _fragmentShader } ), Outputs = GraphicsDevice.SwapchainFramebuffer.OutputDescription }; _pipeline = _factory.CreateGraphicsPipeline(pipelineDescription); }
public ResourceSetKey(ResourceLayout layout, BindableResource res) : this() => (ResourceLayout, Resource0) = (layout, res);
public void Begin(GraphicsDevice device, Framebuffer framebuffer) { if (IsRunning) { throw new InvalidOperationException("The program is already running."); } if (device is null) { throw new ArgumentNullException(nameof(device)); } if (framebuffer is null) { throw new ArgumentNullException(nameof(framebuffer)); } var factory = device.ResourceFactory; if (factory is null) { throw new ArgumentException("GraphicsDevice is not ready. It has no ResourceFactory", nameof(device)); } var vertex = programDescription.VertexShader; var fragment = programDescription.FragmentShader; var pipelineOptions = programDescription.PipelineOptions; pipelineOptions.ResourceLayouts = layouts = new ResourceLayout[] { factory.CreateResourceLayout(new ResourceLayoutDescription( new ResourceLayoutElementDescription("ProjectionBuffer", ResourceKind.UniformBuffer, ShaderStages.Vertex), new ResourceLayoutElementDescription("DiffuseSampler", ResourceKind.Sampler, ShaderStages.Fragment))), factory.CreateResourceLayout(new ResourceLayoutDescription( new ResourceLayoutElementDescription("WorldBuffer", ResourceKind.UniformBuffer, ShaderStages.Vertex))), factory.CreateResourceLayout(new ResourceLayoutDescription( new ResourceLayoutElementDescription("DiffuseTexture", ResourceKind.TextureReadOnly, ShaderStages.Fragment))) }; var vertexResources = new BindableResource[] { cameraBuffer = factory.CreateBuffer(new BufferDescription(vertex.Resources[0].Size, BufferUsage.UniformBuffer)), device.Aniso4xSampler }; disposableResources = vertexResources .Where(r => r != null && r != device.Aniso4xSampler) .OfType <IDisposable>() .ToArray(); resourceSet = factory.CreateResourceSet(new ResourceSetDescription(layouts[0], vertexResources)); var layout = programDescription.VertexLayout; if (device.BackendType == GraphicsBackend.Direct3D11 || programDescription.UseSpirV) { for (var i = 0; i < programDescription.VertexLayout.Elements.Length; ++i) { programDescription.VertexLayout.Elements[i].Semantic = VertexElementSemantic.TextureCoordinate; } } pipelineOptions.ShaderSet = new ShaderSetDescription { VertexLayouts = new VertexLayoutDescription[] { layout }, Shaders = CreateShaders(factory, programDescription) }; pipelineOptions.Outputs = framebuffer.OutputDescription; pipeline = factory.CreateGraphicsPipeline(pipelineOptions); IsRunning = true; }
override protected void CreateResources() { _cameraProjViewBuffer = _factory.CreateBuffer(new BufferDescription(128, BufferUsage.UniformBuffer | BufferUsage.Dynamic)); ResourceLayoutElementDescription resourceLayoutElementDescription = new ResourceLayoutElementDescription("projView", ResourceKind.UniformBuffer, ShaderStages.Vertex); ResourceLayoutElementDescription[] resourceLayoutElementDescriptions = { resourceLayoutElementDescription }; ResourceLayoutDescription resourceLayoutDescription = new ResourceLayoutDescription(resourceLayoutElementDescriptions); BindableResource[] bindableResources = new BindableResource[] { _cameraProjViewBuffer }; _resourceLayout = _factory.CreateResourceLayout(resourceLayoutDescription); ResourceSetDescription resourceSetDescription = new ResourceSetDescription(_resourceLayout, bindableResources); _resourceSet = _factory.CreateResourceSet(resourceSetDescription); Mesh <VertexPositionNDCColor> coloredQuad = GeometryFactory.GenerateColorQuadNDC_XY(RgbaFloat.Red, RgbaFloat.Green, RgbaFloat.Blue, RgbaFloat.Yellow); ushort[] quadIndicies = GeometryFactory.GenerateQuadIndicies_TriangleStrip_CW(); float[] _xOffset = { -2f, 2f }; // declare (VBO) buffers _vertexBuffer = _factory.CreateBuffer(new BufferDescription(coloredQuad.Vertices.LengthUnsigned() * VertexPositionNDCColor.SizeInBytes, BufferUsage.VertexBuffer)); _indexBuffer = _factory.CreateBuffer(new BufferDescription(quadIndicies.LengthUnsigned() * sizeof(ushort), BufferUsage.IndexBuffer)); _xOffsetBuffer = _factory.CreateBuffer(new BufferDescription(_xOffset.LengthUnsigned() * sizeof(float), BufferUsage.VertexBuffer)); // fill buffers with data GraphicsDevice.UpdateBuffer(_vertexBuffer, 0, coloredQuad.Vertices); GraphicsDevice.UpdateBuffer(_indexBuffer, 0, quadIndicies); GraphicsDevice.UpdateBuffer(_xOffsetBuffer, 0, _xOffset); GraphicsDevice.UpdateBuffer(_cameraProjViewBuffer, 0, Camera.ViewMatrix); GraphicsDevice.UpdateBuffer(_cameraProjViewBuffer, 64, Camera.ProjectionMatrix); VertexLayoutDescription vertexLayout = new VertexLayoutDescription( new VertexElementDescription("Position", VertexElementSemantic.Position, VertexElementFormat.Float2), new VertexElementDescription("Color", VertexElementSemantic.Color, VertexElementFormat.Float4) ); VertexElementDescription vertexElementPerInstance = new VertexElementDescription("xOff", VertexElementSemantic.Position, VertexElementFormat.Float1); VertexLayoutDescription vertexLayoutPerInstance = new VertexLayoutDescription( stride: 4, instanceStepRate: 1, elements: new VertexElementDescription[] { vertexElementPerInstance } ); _vertexShader = IO.LoadShader("OffsetXNDCColor", ShaderStages.Vertex, GraphicsDevice); _fragmentShader = IO.LoadShader("Color", ShaderStages.Fragment, GraphicsDevice); GraphicsPipelineDescription pipelineDescription = new GraphicsPipelineDescription() { BlendState = BlendStateDescription.SingleOverrideBlend, DepthStencilState = new DepthStencilStateDescription( depthTestEnabled: true, depthWriteEnabled: true, comparisonKind: ComparisonKind.LessEqual), RasterizerState = new RasterizerStateDescription( cullMode: FaceCullMode.Back, fillMode: PolygonFillMode.Solid, frontFace: FrontFace.Clockwise, depthClipEnabled: true, scissorTestEnabled: false ), PrimitiveTopology = PrimitiveTopology.TriangleStrip, ResourceLayouts = new ResourceLayout[] { _resourceLayout }, ShaderSet = new ShaderSetDescription( vertexLayouts: new VertexLayoutDescription[] { vertexLayout, vertexLayoutPerInstance }, shaders: new Shader[] { _vertexShader, _fragmentShader } ), Outputs = GraphicsDevice.SwapchainFramebuffer.OutputDescription }; _pipeline = _factory.CreateGraphicsPipeline(pipelineDescription); }
public TextArrayRenderer(GraphicsDevice gd, FontAtlas charAtlas, BindableResource projectionBuffer) { var factory = gd.ResourceFactory; var surfaceTextureView = factory.CreateTextureView(charAtlas.Texture); // create the vertex buffer _vertexBuffer = factory.CreateBuffer(new BufferDescription( (uint)charAtlas.Count * 4 * VertexPositionColor.SizeInBytes, BufferUsage.VertexBuffer)); var quadVertices = new VertexPositionColor[charAtlas.Count * 4]; for (int i = 0; i < charAtlas.Count; ++i) { var cell = charAtlas[(char)i]; quadVertices[i * 4 + 0].Position.X = 0; quadVertices[i * 4 + 1].Position.X = 1; quadVertices[i * 4 + 2].Position.X = 0; quadVertices[i * 4 + 3].Position.X = 1; quadVertices[i * 4 + 0].Position.Y = 0; quadVertices[i * 4 + 1].Position.Y = 0; quadVertices[i * 4 + 2].Position.Y = 1; quadVertices[i * 4 + 3].Position.Y = 1; quadVertices[i * 4 + 0].Texture = cell.TopLeft; quadVertices[i * 4 + 1].Texture = cell.TopRight; quadVertices[i * 4 + 2].Texture = cell.BottomLeft; quadVertices[i * 4 + 3].Texture = cell.BottomRight; quadVertices[i * 4 + 0].Color = RgbaFloat.White; quadVertices[i * 4 + 1].Color = RgbaFloat.White; quadVertices[i * 4 + 2].Color = RgbaFloat.White; quadVertices[i * 4 + 3].Color = RgbaFloat.White; } gd.UpdateBuffer(_vertexBuffer, 0, quadVertices); // setup the index buffer ushort[] quadIndices = { 0, 1, 2, 3 }; _indexBuffer = factory.CreateBuffer(new BufferDescription((uint)quadIndices.Length * sizeof(ushort), BufferUsage.IndexBuffer)); gd.UpdateBuffer(_indexBuffer, 0, quadIndices); // create the world matrix buffer _worldBuffer = factory.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer)); // create the color buffer _colorBuffer = factory.CreateBuffer(new BufferDescription(16, BufferUsage.UniformBuffer)); // create vertex layout var vertexLayout = new VertexLayoutDescription( new VertexElementDescription("Position", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2), new VertexElementDescription("Texture", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2), new VertexElementDescription("Color", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float4)); // create vertex and pixel shaders var vertexShaderDesc = new ShaderDescription( ShaderStages.Vertex, Encoding.UTF8.GetBytes(VertexCode), "main"); var fragmentShaderDesc = new ShaderDescription( ShaderStages.Fragment, Encoding.UTF8.GetBytes(FragmentCode), "main"); var shaders = factory.CreateFromSpirv(vertexShaderDesc, fragmentShaderDesc); // create resource layout and resource set for projection buffer and texture var projectionTextureResourceLayout = factory.CreateResourceLayout(new ResourceLayoutDescription( new ResourceLayoutElementDescription("ProjectionBuffer", ResourceKind.UniformBuffer, ShaderStages.Vertex), new ResourceLayoutElementDescription("WorldBuffer", ResourceKind.UniformBuffer, ShaderStages.Vertex), new ResourceLayoutElementDescription("SurfaceTexture", ResourceKind.TextureReadOnly, ShaderStages.Fragment), new ResourceLayoutElementDescription("SurfaceSampler", ResourceKind.Sampler, ShaderStages.Fragment), new ResourceLayoutElementDescription("ColorBuffer", ResourceKind.UniformBuffer, ShaderStages.Fragment))); _projectionTextureResourceSet = factory.CreateResourceSet(new ResourceSetDescription( projectionTextureResourceLayout, projectionBuffer, _worldBuffer, surfaceTextureView, factory.CreateSampler(new SamplerDescription { AddressModeU = SamplerAddressMode.Clamp, AddressModeV = SamplerAddressMode.Clamp, AddressModeW = SamplerAddressMode.Clamp, Filter = SamplerFilter.Anisotropic, LodBias = 0, MinimumLod = 0, MaximumLod = uint.MaxValue, MaximumAnisotropy = 4 }), _colorBuffer)); // create pipeline _pipeline = factory.CreateGraphicsPipeline(new GraphicsPipelineDescription { BlendState = BlendStateDescription.SingleOverrideBlend, DepthStencilState = new DepthStencilStateDescription( depthTestEnabled: true, depthWriteEnabled: true, comparisonKind: ComparisonKind.LessEqual), RasterizerState = new RasterizerStateDescription( cullMode: FaceCullMode.Back, fillMode: PolygonFillMode.Solid, frontFace: FrontFace.Clockwise, depthClipEnabled: true, scissorTestEnabled: false), PrimitiveTopology = PrimitiveTopology.TriangleStrip, ResourceLayouts = new[] { projectionTextureResourceLayout }, ShaderSet = new ShaderSetDescription( vertexLayouts: new[] { vertexLayout }, shaders: shaders), Outputs = gd.SwapchainFramebuffer.OutputDescription }); }