public GeometryShaderBox(AssetDatabase ad, RenderContext rc, Camera camera, string geometryShaderName = "cube-geometry") { _geometryShaderName = geometryShaderName; InitializeContextObjects(ad, rc); Matrix4x4 m = Matrix4x4.CreateTranslation(Position); _worldMatrixBuffer.SetData(ref m, 64); _camera = camera; }
/// <summary> /// Renders fog look-up table /// </summary> public void RenderFogTable() { var sunPos = GetSunDirection(); var sunColor = GetSunLightColor(); var rotation = Matrix.Identity; var projection = MathUtil.ComputeCubemapProjectionMatrixLH(0.125f, 10.0f); var cubeWVPS = MathUtil.ComputeCubemapViewMatriciesLH(Vector3.Zero, rotation, projection); var flags = SkyFlags.FOG; ApplyColorSpace(ref flags); rs.PipelineState = factory[(int)flags]; // rs.DepthStencilState = DepthStencilState.None ; skyConstsData.SunPosition = sunPos; skyConstsData.SunColor = sunColor; skyConstsData.Turbidity = Params.SkyTurbidity; skyConstsData.Temperature = Temperature.Get(Params.SunTemperature); skyConstsData.SkyIntensity = Params.SkyIntensity; for (int i = 0; i < 6; ++i) { rs.SetTargets(null, SkyCube.GetSurface(0, (CubeFace)i)); SkyCube.SetViewport(); skyConstsData.MatrixWVP = cubeWVPS[i]; skyConstsCB.SetData(skyConstsData); rs.VertexShaderConstants[0] = skyConstsCB; rs.PixelShaderConstants[0] = skyConstsCB; for (int j = 0; j < skySphere.Meshes.Count; j++) { var mesh = skySphere.Meshes[j]; rs.SetupVertexInput(vertexBuffers[j], indexBuffers[j]); rs.DrawIndexed(mesh.IndexCount, 0, 0); } } rs.ResetStates(); SkyCube.BuildMipmaps(); }
public static void Main(string[] args) { WindowCreateInfo windowCI = new WindowCreateInfo() { X = 100, Y = 100, WindowWidth = 960, WindowHeight = 540, WindowTitle = "Veldrid TinyDemo", }; RenderContextCreateInfo contextCI = new RenderContextCreateInfo(); VeldridStartup.CreateWindowAndRenderContext(ref windowCI, ref contextCI, out var window, out RenderContext rc); VertexBuffer vb = rc.ResourceFactory.CreateVertexBuffer(Cube.Vertices, new VertexDescriptor(VertexPositionColor.SizeInBytes, 2), false); IndexBuffer ib = rc.ResourceFactory.CreateIndexBuffer(Cube.Indices, false); string folder = rc.BackendType == GraphicsBackend.Direct3D11 ? "HLSL" : "GLSL"; string extension = rc.BackendType == GraphicsBackend.Direct3D11 ? "hlsl" : "glsl"; VertexInputLayout inputLayout = rc.ResourceFactory.CreateInputLayout(new VertexInputDescription[] { new VertexInputDescription( new VertexInputElement("Position", VertexSemanticType.Position, VertexElementFormat.Float3), new VertexInputElement("Color", VertexSemanticType.Color, VertexElementFormat.Float4)) }); string vsPath = Path.Combine(AppContext.BaseDirectory, folder, $"vertex.{extension}"); string fsPath = Path.Combine(AppContext.BaseDirectory, folder, $"fragment.{extension}"); Shader vs = rc.ResourceFactory.CreateShader(ShaderStages.Vertex, File.ReadAllText(vsPath)); Shader fs = rc.ResourceFactory.CreateShader(ShaderStages.Fragment, File.ReadAllText(fsPath)); ShaderSet shaderSet = rc.ResourceFactory.CreateShaderSet(inputLayout, vs, fs); ShaderResourceBindingSlots bindingSlots = rc.ResourceFactory.CreateShaderResourceBindingSlots( shaderSet, new ShaderResourceDescription("ViewProjectionMatrix", ShaderConstantType.Matrix4x4)); ConstantBuffer viewProjectionBuffer = rc.ResourceFactory.CreateConstantBuffer(ShaderConstantType.Matrix4x4); while (window.Exists) { InputSnapshot snapshot = window.PumpEvents(); rc.ClearBuffer(); rc.SetViewport(0, 0, window.Width, window.Height); float timeFactor = Environment.TickCount / 1000f; viewProjectionBuffer.SetData( Matrix4x4.CreateLookAt( new Vector3(2 * (float)Math.Sin(timeFactor), (float)Math.Sin(timeFactor), 2 * (float)Math.Cos(timeFactor)), Vector3.Zero, Vector3.UnitY) * Matrix4x4.CreatePerspectiveFieldOfView(1.05f, (float)window.Width / window.Height, .5f, 10f)); rc.SetVertexBuffer(0, vb); rc.IndexBuffer = ib; rc.ShaderSet = shaderSet; rc.ShaderResourceBindingSlots = bindingSlots; rc.SetConstantBuffer(0, viewProjectionBuffer); rc.DrawIndexedPrimitives(Cube.Indices.Length); rc.SwapBuffers(); } }
/// <summary> /// /// </summary> internal void Draw(GameTime gameTime, StereoEye stereoEye) { if (spriteCount == 0) { return; } if (dirty) { // realloc buffers in necessary if (vertices.Count > capacity * VertexPerSprite) { var newCapacity = MathUtil.IntDivRoundUp(vertices.Count / VertexPerSprite, 64) * 64; ReallocGpuBuffers(newCapacity); } vertexBuffer.SetData(vertices.ToArray()); framesBuffer.SetData(framesData); dirty = false; } rs.Device.PixelShaderConstants[1] = framesBuffer; rs.Device.SetupVertexInput(vertexBuffer, null); foreach (var group in groups) { rs.Device.PixelShaderResources[0] = group.Texture.Srv; rs.Device.Draw(group.SpriteCount * VertexPerSprite, group.StartSprite * VertexPerSprite); } }
/// <summary> /// Updates page table using GPU /// </summary> void UpdatePageTable() { int tableSize = VTConfig.VirtualPageCount; using (new PixEvent("UpdatePageTable")) { var pages = tileCache.GetGpuPageData(); if (pages.Any()) { PageData.SetData(pages); } for (int mip = 0; mip < VTConfig.MipCount; mip++) { Params.SetData(new Int4(pages.Length, mip, 0, 0)); var device = Game.GraphicsDevice; device.ResetStates(); device.PipelineState = factory[0]; device.ComputeShaderConstants[0] = Params; device.ComputeShaderResources[0] = PageData; device.SetCSRWTexture(0, PageTable.GetSurface(mip)); int targetSize = tableSize >> mip; int groupCountX = MathUtil.IntDivUp(targetSize, BlockSizeX); int groupCountY = MathUtil.IntDivUp(targetSize, BlockSizeX); device.Dispatch(groupCountX, groupCountY, 1); } } }
public void Render(RenderContext rc, string pipelineStage) { float rotationAmount = (float)DateTime.Now.TimeOfDay.TotalMilliseconds / 1000; Matrix4x4 worldMat = Matrix4x4.CreateScale(Scale) * Matrix4x4.CreateTranslation(Position); _worldBuffer.SetData(ref worldMat, 64); Matrix4x4 inverseTransposeWorld = Utilities.CalculateInverseTranspose(worldMat); _inverseTransposeWorldBuffer.SetData(ref inverseTransposeWorld, 64); rc.VertexBuffer = _vb; rc.IndexBuffer = _ib; _material.Apply(rc); rc.SetConstantBuffer(0, SharedDataProviders.ProjectionMatrixBuffer); rc.SetConstantBuffer(1, SharedDataProviders.ViewMatrixBuffer); rc.SetConstantBuffer(2, SharedDataProviders.DirectionalLightBuffer); rc.SetConstantBuffer(3, _worldBuffer); rc.SetConstantBuffer(4, _inverseTransposeWorldBuffer); rc.SetTexture(5, _textureBinding); rc.SetSamplerState(6, rc.PointSampler); rc.DrawIndexedPrimitives(_indices.Length, 0); }
public void Render(RenderContext rc, string pipelineStage) { Matrix4x4 orthoProjection = Matrix4x4.CreateOrthographicOffCenter( 0f, rc.Viewport.Width, rc.Viewport.Height, 0f, -1.0f, 1.0f); Matrix4x4 proj = orthoProjection; _projectionMatrixBuffer.SetData(ref proj, 64); float width = _imageWidth; Matrix4x4 world = Matrix4x4.CreateScale(width) * Matrix4x4.CreateTranslation(rc.Viewport.Width - width - 20, 20, 0); _worldMatrixBuffer.SetData(ref world, 64); rc.VertexBuffer = _vertexBuffer; rc.IndexBuffer = _indexBuffer; _material.Apply(rc); rc.SetConstantBuffer(0, _worldMatrixBuffer); rc.SetConstantBuffer(1, _projectionMatrixBuffer); rc.SetTexture(2, SharedTextures.GetTextureBinding("ShadowMap")); rc.SetDepthStencilState(_depthDisabledState); rc.DrawIndexedPrimitives(6, 0); rc.SetDepthStencilState(rc.DefaultDepthStencilState); }
private void InitializeContextObjects(AssetDatabase ad, RenderContext rc) { ResourceFactory factory = rc.ResourceFactory; _vb = factory.CreateVertexBuffer(1024, true); _ib = factory.CreateIndexBuffer(1024, true); Shader vs = factory.CreateShader(ShaderStages.Vertex, ShaderHelper.LoadShaderCode("wireframe-vertex", ShaderStages.Vertex, rc.ResourceFactory)); Shader fs = factory.CreateShader(ShaderStages.Fragment, ShaderHelper.LoadShaderCode("wireframe-frag", ShaderStages.Fragment, rc.ResourceFactory)); VertexInputLayout inputLayout = factory.CreateInputLayout( new VertexInputElement("in_position", VertexSemanticType.Position, VertexElementFormat.Float3), new VertexInputElement("in_color", VertexSemanticType.Color, VertexElementFormat.Byte4)); ShaderSet shaderSet = factory.CreateShaderSet(inputLayout, vs, fs); ShaderResourceBindingSlots cbs = factory.CreateShaderResourceBindingSlots( shaderSet, new ShaderResourceDescription("ProjectionMatrixBuffer", ShaderConstantType.Matrix4x4), new ShaderResourceDescription("ViewMatrixBuffer", ShaderConstantType.Matrix4x4), new ShaderResourceDescription("WorldMatrixBuffer", ShaderConstantType.Matrix4x4)); _material = new Material(shaderSet, cbs); _worldBuffer = factory.CreateConstantBuffer(ShaderConstantType.Matrix4x4); Matrix4x4 identity = Matrix4x4.Identity; _worldBuffer.SetData(ref identity, 64); _wireframeState = factory.CreateRasterizerState(FaceCullingMode.None, TriangleFillMode.Solid, true, true); }
/// <summary> /// Applies DOF effect /// </summary> public void Render(GameTime gameTime, RenderTarget2D temp, RenderTarget2D hdrImage, ShaderResource depthBuffer, RenderWorld renderWorld) { if (!renderWorld.DofSettings.Enabled) { return; } var device = Game.GraphicsDevice; var filter = Game.RenderSystem.Filter; device.ResetStates(); // // Setup parameters : // var paramsData = new Params(); paramsData.LinearDepthBias = renderWorld.Camera.LinearizeDepthBias; paramsData.LinearDepthScale = renderWorld.Camera.LinearizeDepthScale; paramsData.CocBias = renderWorld.DofSettings.CocBias; paramsData.CocScale = renderWorld.DofSettings.CocScale; paramsCB.SetData(paramsData); device.PixelShaderConstants[0] = paramsCB; // // Compute COC and write it in alpha channel : // device.SetTargets((DepthStencilSurface)null, hdrImage.Surface); device.PixelShaderResources[0] = depthBuffer; device.PipelineState = factory[(int)(Flags.COC_TO_ALPHA)]; device.Draw(3, 0); // // Perform DOF : // device.SetTargets(null, temp); device.PixelShaderResources[0] = hdrImage; device.PixelShaderSamplers[0] = SamplerState.LinearClamp; device.VertexShaderResources[0] = hdrImage; device.VertexShaderSamplers[0] = SamplerState.LinearClamp; device.PipelineState = factory[(int)(Flags.DEPTH_OF_FIELD)]; device.Draw(3, 0); device.ResetStates(); // // Copy DOFed image back to source : // filter.Copy(hdrImage.Surface, temp); }
/// <summary> /// /// </summary> /// <param name="srcDst"></param> /// <param name="temporary"></param> /// <param name="sigma"></param> /// <param name="kernelSize"></param> void GaussBlurInternal(RenderTarget2D src, RenderTarget2D dst, RenderTarget2D temporary, float sigma, float sharpness, int mipLevel, ShaderResource depthData, ShaderResource normalData) { var taps = GetGaussWeightsBuffer(sigma, mipLevel); SetDefaultRenderStates(); gaussWeightsCB.SetData(taps); int combination = (int)ShaderFlags.GAUSS_BLUR; if (depthData != null && normalData != null) { combination |= (int)ShaderFlags.BILATERAL; } using (new PixEvent("GaussBlur")) { SetViewport(temporary.GetSurface(mipLevel)); device.SetTargets(null, temporary.GetSurface(mipLevel)); device.PipelineState = factory[combination | (int)ShaderFlags.PASS1]; device.VertexShaderResources[0] = src; device.PixelShaderResources[0] = src; device.PixelShaderResources[1] = depthData; device.PixelShaderResources[2] = normalData; device.PixelShaderConstants[0] = gaussWeightsCB; device.PixelShaderSamplers[0] = SamplerState.LinearPointClamp; device.PixelShaderSamplers[1] = SamplerState.PointClamp; device.Draw(3, 0); device.VertexShaderResources[0] = null; device.PixelShaderResources[0] = null; SetViewport(dst.GetSurface(mipLevel)); device.SetTargets(null, dst.GetSurface(mipLevel)); device.PipelineState = factory[combination | (int)ShaderFlags.PASS2]; device.VertexShaderResources[0] = temporary; device.PixelShaderResources[0] = temporary; device.PixelShaderResources[1] = depthData; device.PixelShaderResources[2] = normalData; device.PixelShaderConstants[0] = gaussWeightsCB; device.PixelShaderSamplers[0] = SamplerState.LinearPointClamp; device.PixelShaderSamplers[1] = SamplerState.PointClamp; device.Draw(3, 0); } device.ResetStates(); }
/// <summary> /// Renders fog look-up table /// </summary> internal void RenderFogTable(SkySettings settings) { using (new PixEvent("Fog Table")) { var sunPos = settings.SunPosition; var sunColor = settings.SunLightColor; var rotation = Matrix.Identity; var projection = MathUtil.ComputeCubemapProjectionMatrixLH(0.125f, 10.0f); var cubeWVPS = MathUtil.ComputeCubemapViewMatriciesLH(Vector3.Zero, rotation, projection); var flags = SkyFlags.FOG; ApplyColorSpace(ref flags, settings); device.PipelineState = factory[(int)flags]; // rs.DepthStencilState = DepthStencilState.None ; skyConstsData.SunPosition = sunPos; skyConstsData.SunColor = sunColor; skyConstsData.Turbidity = settings.SkyTurbidity; skyConstsData.Temperature = Temperature.Get(settings.SunTemperature); skyConstsData.SkyIntensity = settings.SkyIntensity; for (int i = 0; i < 6; ++i) { device.SetTargets(null, SkyCube.GetSurface(0, (CubeFace)i)); SkyCube.SetViewport(); skyConstsData.MatrixWVP = cubeWVPS[i]; skyConstsCB.SetData(skyConstsData); device.VertexShaderConstants[0] = skyConstsCB; device.PixelShaderConstants[0] = skyConstsCB; device.SetupVertexInput(skyVB, null); device.Draw(skyVB.Capacity, 0); } device.ResetStates(); SkyCube.BuildMipmaps(); } }
public void RenderBlank(Matrix view, Matrix projection, ShaderResource depthBuffer, ShaderResource wsNormals) { var device = Game.GraphicsDevice; var filter = Game.RenderSystem.Filter; filter.StretchRect(downsampledDepth.Surface, depthBuffer); filter.StretchRect(downsampledNormals.Surface, wsNormals); // // Setup parameters : // var paramsData = new Params(); paramsData.ProjMatrix = projection; paramsData.View = view; paramsData.ViewProj = view * projection; paramsData.InvViewProj = Matrix.Invert(view * projection); paramsData.InvProj = Matrix.Invert(projection); //paramsData.TraceStep = Config.TraceStep; //paramsData.DecayRate = Config.DecayRate; paramsData.MaxSampleRadius = MaxSamplingRadius; paramsData.MaxDepthJump = MaxDepthJump; paramsCB.SetData(paramsData); sampleDirectionsCB.SetData(sampleDirectionData); device.PixelShaderConstants[0] = paramsCB; device.PixelShaderConstants[1] = sampleDirectionsCB; // // Measure and adapt : // device.SetTargets(null, occlusionMapFull); device.PixelShaderResources[0] = downsampledDepth; device.PixelShaderResources[1] = downsampledNormals; device.PixelShaderResources[2] = randomDir; device.PixelShaderSamplers[0] = SamplerState.LinearClamp; device.PipelineState = factory[(int)Flags.BLANK]; device.Draw(3, 0); device.ResetStates(); }
/// <summary> /// Draws game /// </summary> /// <param name="gameTime"></param> /// <param name="stereoEye"></param> protected override void Draw(GameTime gameTime, StereoEye stereoEye) { var cam = GetService <Camera>(); GraphicsDevice.ClearBackbuffer(new Color(50, 70, 100, 255), 1, 0); constData.World = Matrix.Identity; constData.ViewProj = cam.GetViewMatrix(stereoEye) * cam.GetProjectionMatrix(stereoEye); constData.ViewPos = new Vector4(cam.GetCameraMatrix(stereoEye).TranslationVector, 1); constData.World = Matrix.Identity; constData.LodDist = new Vector4(minLOD, maxLOD, minDistance, maxDistance); constData.ScaleSharp = new Vector4(textureScale, blendSharpness, 0, 0); GraphicsDevice.PipelineState = factory[wireframe ? (int)RenderFlags.Wireframe : 0]; GraphicsDevice.PixelShaderSamplers[0] = SamplerState.LinearPointWrap; GraphicsDevice.DomainShaderSamplers[0] = SamplerState.LinearPointWrap; GraphicsDevice.PixelShaderConstants[0] = constBuffer; GraphicsDevice.VertexShaderConstants[0] = constBuffer; GraphicsDevice.HullShaderConstants[0] = constBuffer; GraphicsDevice.DomainShaderConstants[0] = constBuffer; for (int i = 0; i < scene.Nodes.Count; i++) { int meshId = scene.Nodes[i].MeshIndex; if (meshId < 0) { continue; } constData.World = worldMatricies[i]; constBuffer.SetData(constData); GraphicsDevice.SetupVertexInput(vertexBuffers[meshId], indexBuffers[meshId]); foreach (var subset in scene.Meshes[meshId].Subsets) { GraphicsDevice.PixelShaderResources[0] = textures[3]; GraphicsDevice.PixelShaderResources[1] = textures[4]; GraphicsDevice.PixelShaderResources[2] = textures[1]; GraphicsDevice.PixelShaderResources[3] = textures[2]; GraphicsDevice.DomainShaderResources[0] = textures[3]; GraphicsDevice.DomainShaderResources[1] = textures[4]; GraphicsDevice.DomainShaderResources[2] = textures[1]; GraphicsDevice.DomainShaderResources[3] = textures[2]; GraphicsDevice.DrawIndexed(subset.PrimitiveCount * 3, subset.StartPrimitive * 3, 0); } } base.Draw(gameTime, stereoEye); }
/// <summary> /// /// </summary> /// <param name="iLevel"></param> /// <param name="iLevelMask"></param> /// <param name="iWidth"></param> /// <param name="iHeight"></param> void SetConstants(uint iLevel, uint iLevelMask, uint iWidth, uint iHeight) { Params p = new Params() { Level = iLevel, LevelMask = iLevelMask, Width = iWidth, Height = iHeight }; paramsCB.SetData(p); device.ComputeShaderConstants[0] = paramsCB; }
/// <summary> /// /// </summary> void RenderGeneric(string passName, GameTime gameTime, Camera camera, Viewport viewport, Matrix view, Matrix projection, RenderTargetSurface colorTarget, DepthStencilSurface depthTarget, ShaderResource depthValues, Flags flags) { var device = Game.GraphicsDevice; using (new PixEvent(passName)) { device.ResetStates(); // // Setup images : // if (Images != null && !Images.IsDisposed) { imagesCB.SetData(Images.GetNormalizedRectangles(MaxImages)); } SetupGPUParameters(0, renderWorld, view, projection, flags); device.ComputeShaderConstants[0] = paramsCB; // // Render // using (new PixEvent("Drawing")) { // target and viewport : device.SetTargets(depthTarget, colorTarget); device.SetViewport(viewport); // params CB : device.ComputeShaderConstants[0] = paramsCB; device.VertexShaderConstants[0] = paramsCB; device.GeometryShaderConstants[0] = paramsCB; device.PixelShaderConstants[0] = paramsCB; // atlas CB : device.VertexShaderConstants[1] = imagesCB; device.GeometryShaderConstants[1] = imagesCB; device.PixelShaderConstants[1] = imagesCB; // sampler & textures : device.PixelShaderSamplers[0] = SamplerState.LinearClamp4Mips; device.PixelShaderResources[0] = Images == null? rs.WhiteTexture.Srv : Images.Texture.Srv; device.PixelShaderResources[5] = depthValues; device.GeometryShaderResources[1] = simulationBuffer; device.GeometryShaderResources[2] = simulationBuffer; device.GeometryShaderResources[3] = sortParticlesBuffer; device.GeometryShaderResources[4] = particleLighting; // setup PS : device.PipelineState = factory[(int)flags]; // GPU time : 0.81 ms -> 0.91 ms device.Draw(MaxSimulatedParticles, 0); } } }
/// <summary> /// Initializes Filter service /// </summary> public override void Initialize() { paramsCB = new ConstantBuffer( device, typeof(SsaoParams) ); randomDirsCB = new ConstantBuffer( device, typeof(Vector4), MaxSamples ); randomDirsCB.SetData( Enumerable.Range(0,MaxSamples).Select( i => new Vector4(rand.UniformRadialDistribution(0,1), 0) ).ToArray() ); LoadContent(); Game.Reloading += (s,e) => LoadContent(); }
/// <summary> /// Draw stuff here /// </summary> /// <param name="gameTime"></param> /// <param name="stereoEye"></param> protected override void Draw(GameTime gameTime, StereoEye stereoEye) { // Clear back buffer : GraphicsDevice.ClearBackbuffer(new Color4(0, 0, 0, 1)); // Update constant buffer and bound it to pipeline: cbData.Transform = Matrix.OrthoRH(4, 3, -2, 2); cbData.Time = 0.001f * (float)gameTime.Total.TotalMilliseconds; cb.SetData(cbData); GraphicsDevice.VertexShaderConstants[0] = cb; GraphicsDevice.PixelShaderConstants[0] = cb; // Fill vertex buffer : var v0 = new Vertex { Position = new Vector3(-1.0f, -1.0f, 0), Color = Color.Red, TexCoord = new Vector2(0, 1) }; var v1 = new Vertex { Position = new Vector3(1.0f, 1.0f, 0), Color = Color.White, TexCoord = new Vector2(1, 0) }; var v2 = new Vertex { Position = new Vector3(-1.0f, 1.0f, 0), Color = Color.Blue, TexCoord = new Vector2(0, 0) }; var v3 = new Vertex { Position = new Vector3(-1.0f, -1.0f, 0), Color = Color.Red, TexCoord = new Vector2(0, 1) }; var v4 = new Vertex { Position = new Vector3(1.0f, -1.0f, 0), Color = Color.Lime, TexCoord = new Vector2(1, 1) }; var v5 = new Vertex { Position = new Vector3(1.0f, 1.0f, 0), Color = Color.White, TexCoord = new Vector2(1, 0) }; //*/ var data = new Vertex[] { v0, v1, v2, v3, v4, v5 }; vb.SetData(data, 0, 6); // Set required ubershader : // Set device states : GraphicsDevice.PipelineState = factory[0]; GraphicsDevice.PixelShaderSamplers[0] = SamplerState.LinearWrap; // Setup texture : GraphicsDevice.PixelShaderResources[0] = tex; GraphicsDevice.VertexShaderResources[1] = instDataGpu; // Setup vertex data and draw : GraphicsDevice.SetupVertexInput(vb, null); GraphicsDevice.DrawInstanced(6, InstanceCount, 0, 0); base.Draw(gameTime, stereoEye); }
private static void ConstantBufferSetGeneric <T>(RenderContext rc, T value) where T : struct, IEquatable <T> { int sizeOfT = Unsafe.SizeOf <T>(); ConstantBuffer cb = rc.ResourceFactory.CreateConstantBuffer(sizeOfT); cb.SetData(ref value, sizeOfT); T returnedValue = default(T); cb.GetData(ref returnedValue, sizeOfT); Assert.Equal(value, returnedValue); }
/// <summary> /// Add services : /// </summary> protected override void Initialize() { // initialize services : base.Initialize(); // create structured buffers and shaders : argA = new StructuredBuffer(GraphicsDevice, typeof(float), BufferSize, StructuredBufferFlags.None); argB = new StructuredBuffer(GraphicsDevice, typeof(float), BufferSize, StructuredBufferFlags.None); result = new StructuredBuffer(GraphicsDevice, typeof(Result), BufferSize, StructuredBufferFlags.None); paramsCB = new ConstantBuffer(GraphicsDevice, typeof(Params)); shader = Content.Load <Ubershader>("test"); factory = new StateFactory(shader, typeof(ShaderFlags), Primitive.TriangleList, VertexInputElement.Empty); // write data : var rand = new Random(); var a = Enumerable.Range(0, BufferSize).Select(i => rand.NextFloat(-1000, 1000)).ToArray(); var b = Enumerable.Range(0, BufferSize).Select(i => rand.NextFloat(-1000, 1000)).ToArray(); var r = Enumerable.Range(0, BufferSize).Select(i => new Result()).ToArray(); argA.SetData(a); argB.SetData(b); paramsCB.SetData(new Params() { Size = BufferSize }); // bind objects : GraphicsDevice.SetCSRWBuffer(0, argA); GraphicsDevice.SetCSRWBuffer(1, argB); GraphicsDevice.SetCSRWBuffer(2, result); GraphicsDevice.ComputeShaderConstants[0] = paramsCB; // set compute shader and dispatch threadblocks : GraphicsDevice.PipelineState = factory[0]; GraphicsDevice.Dispatch(MathUtil.IntDivUp(BufferSize, 256)); // get data : result.GetData(r); Log.Message(" id : Sum Product gID gtID dtID gIdx"); for (int i = 0; i < BufferSize; i++) { Log.Message("[{0,4}] : {1}", i, r[i]); } // add keyboard handler : InputDevice.KeyDown += InputDevice_KeyDown; }
public void SetData_GetData() { VkRenderContext rc = TestData.CreateVulkanContext(); ConstantBuffer cb = rc.ResourceFactory.CreateConstantBuffer(ShaderConstantType.Matrix4x4); Matrix4x4 mat = Matrix4x4.Identity; cb.SetData(ref mat, Unsafe.SizeOf <Matrix4x4>()); Matrix4x4 ret = new Matrix4x4(); cb.GetData(ref ret, Unsafe.SizeOf <Matrix4x4>()); Assert.Equal(mat, ret); }
public void ConstantBufferSetRangeData() { float[] array = Enumerable.Range(0, 256).Select(i => (float)i).ToArray(); using ConstantBuffer <float> sourceBuffer = Gpu.Default.AllocateConstantBuffer(array); array.AsSpan(56, 100).Clear(); sourceBuffer.SetData(new float[100], 56, 100); float[] sourceResult = sourceBuffer.GetData(); Assert.IsTrue(array.AsSpan().ContentEquals(sourceResult)); }
private void UpdateCamera() { float timeFactor = (float)DateTime.Now.TimeOfDay.TotalMilliseconds / 1000; if (AutoRotateCamera) { _cameraPosition = new Vector3( (float)(Math.Cos(timeFactor) * _circleWidth), 6 + (float)Math.Sin(timeFactor) * 2, (float)(Math.Sin(timeFactor) * _circleWidth)); _view.SetData(Matrix4x4.CreateLookAt(_cameraPosition, -_cameraPosition, Vector3.UnitY)); } }
private void InitializeContextObjects(AssetDatabase ad, RenderContext rc) { ResourceFactory factory = rc.ResourceFactory; MeshData sphere = ad.LoadAsset <ObjFile>(new AssetID("Models/Sphere.obj")).GetFirstMesh(); Vector3[] spherePositions = sphere.GetVertexPositions(); _sphereGeometryVB = factory.CreateVertexBuffer(spherePositions.Length * 12, false); _sphereGeometryVB.SetVertexData(spherePositions, new VertexDescriptor(12, 1)); _ib = sphere.CreateIndexBuffer(factory, out _indexCount); Random r = new Random(); int width = InstanceRows; InstanceData[] instanceData = new InstanceData[width * width * width]; for (int z = 0; z < width; z++) { for (int y = 0; y < width; y++) { for (int x = 0; x < width; x++) { instanceData[z * width * width + y * width + x] = new InstanceData( new Vector3(x * 10, y * 10, z * 10), new RgbaFloat((float)r.NextDouble(), (float)r.NextDouble(), (float)r.NextDouble(), (float)r.NextDouble())); } } } _instanceVB = factory.CreateVertexBuffer(instanceData.Length * InstanceData.SizeInBytes, false); _instanceVB.SetVertexData(instanceData, new VertexDescriptor(InstanceData.SizeInBytes, 2, 0, IntPtr.Zero)); Shader vs = factory.CreateShader(ShaderStages.Vertex, ShaderHelper.LoadShaderCode("instanced-simple-vertex", ShaderStages.Vertex, rc.ResourceFactory)); Shader fs = factory.CreateShader(ShaderStages.Fragment, ShaderHelper.LoadShaderCode("instanced-simple-frag", ShaderStages.Fragment, rc.ResourceFactory)); VertexInputLayout inputLayout = factory.CreateInputLayout( new VertexInputDescription(VertexPosition.SizeInBytes, new VertexInputElement("in_position", VertexSemanticType.Position, VertexElementFormat.Float3)), new VertexInputDescription( InstanceData.SizeInBytes, new VertexInputElement("in_offset", VertexSemanticType.TextureCoordinate, VertexElementFormat.Float3, VertexElementInputClass.PerInstance, 1), new VertexInputElement("in_color", VertexSemanticType.Color, VertexElementFormat.Float4, VertexElementInputClass.PerInstance, 1))); ShaderSet shaderSet = factory.CreateShaderSet(inputLayout, vs, fs); ShaderResourceBindingSlots constantBindings = factory.CreateShaderResourceBindingSlots( shaderSet, new ShaderResourceDescription("ProjectionMatrixBuffer", ShaderConstantType.Matrix4x4), new ShaderResourceDescription("ViewMatrixBuffer", ShaderConstantType.Matrix4x4), new ShaderResourceDescription("WorldMatrixBuffer", ShaderConstantType.Matrix4x4)); _material = new Material(shaderSet, constantBindings); _worldBuffer = factory.CreateConstantBuffer(ShaderConstantType.Matrix4x4); Matrix4x4 identity = Matrix4x4.Identity; _worldBuffer.SetData(ref identity, 64); }
/// <summary> /// This function calculates two values: /// 1. Energy E for every vertex (N floats) /// 2. Descent vector which equals -grad(E) (3*N floats) /// Values are overwritten into the same buffer /// </summary> /// <param name="device"></param> /// <param name="rwVertexBuffer"></param> /// <param name="parameters"></param> public void CalcDescentVector(StructuredBuffer rwVertexBuffer, ComputeParams parameters) { parameters.MaxParticles = (uint)ParticleCount; paramsCB.SetData(parameters); device.ComputeShaderConstants[0] = paramsCB; device.SetCSRWBuffer(0, rwVertexBuffer, (int)parameters.MaxParticles); device.ComputeShaderResources[2] = LinksIndexBuffer; device.ComputeShaderResources[3] = LinksBuffer; device.ComputeShaderResources[4] = SelectBuffer; device.PipelineState = factory[(int)( ComputeFlags.COMPUTE | ComputeFlags.SIMULATION | ComputeFlags.EULER | ComputeFlags.LINKS)]; // device.PipelineState = factory[(int)( // ComputeFlags.COMPUTE | ComputeFlags.SIMULATION | // ComputeFlags.EULER)]; device.Dispatch(MathUtil.IntDivUp((int)parameters.MaxParticles, BlockSize)); // device.ResetStates(); // add localization forces: device.PipelineState = factory[(int)(ComputeFlags.COMPUTE | ComputeFlags.LOCAL)]; if (categories.Count > 0) { foreach (var cat in categories) { parameters.LocalCenter = new Vector4(cat.Center, 0); parameters.LocalRadius = cat.Radius; parameters.StartIndex = cat.startIndex; parameters.EndIndex = cat.endIndex; paramsCB.SetData(parameters); // device.ComputeShaderConstants[0] = paramsCB; device.Dispatch(MathUtil.IntDivUp((int)(cat.endIndex - cat.startIndex), BlockSize)); } } device.ResetStates(); }
public override Context Prepare(GameTime gameTime, StereoEye stereoEye) { var cam = Game.GetService <Camera>(); CopyBoneTransformsTo(boneTransforms); constBufferBones.SetData(boneTransforms); return(new Context() { View = cam.GetViewMatrix(stereoEye), Projection = cam.GetProjectionMatrix(stereoEye), ViewPosition = cam.GetCameraPosition4(stereoEye) }); }
/// <summary> /// /// </summary> void SetupGPUParameters(float stepTime, RenderWorld renderWorld, Matrix view, Matrix projection, Flags flags) { var deltaTime = stepTime; var camera = renderWorld.Camera; var cameraMatrix = Matrix.Invert(view); // kill particles by applying very large delta. if (requestKill) { deltaTime = float.MaxValue / 2; requestKill = false; } if (rs.FreezeParticles) { deltaTime = 0; } // fill constant data : PrtParams param = new PrtParams(); param.View = view; param.Projection = projection; param.MaxParticles = 0; param.DeltaTime = deltaTime; param.CameraForward = new Vector4(cameraMatrix.Forward, 0); param.CameraRight = new Vector4(cameraMatrix.Right, 0); param.CameraUp = new Vector4(cameraMatrix.Up, 0); param.CameraPosition = new Vector4(cameraMatrix.TranslationVector, 1); param.Gravity = new Vector4(this.Gravity, 0); param.MaxParticles = MaxSimulatedParticles; param.LinearizeDepthA = camera.LinearizeDepthScale; param.LinearizeDepthB = camera.LinearizeDepthBias; param.CocBias = renderWorld.DofSettings.CocBias; param.CocScale = renderWorld.DofSettings.CocScale; if (flags == Flags.INJECTION) { param.MaxParticles = injectionCount; } // copy to gpu : paramsCB.SetData(param); // set DeadListSize to prevent underflow: if (flags == Flags.INJECTION) { deadParticlesIndices.CopyStructureCount(paramsCB, Marshal.OffsetOf(typeof(PrtParams), "DeadListSize").ToInt32()); } }
public override bool PrepareNode(Context context, Node node, Matrix worldMatrix) { constData.View = context.View; constData.Projection = context.Projection; constData.ViewPos = context.ViewPosition; constData.World = worldMatrix; constBuffer.SetData(constData); GraphicsDevice.PipelineState = factory[0]; GraphicsDevice.PixelShaderSamplers[0] = SamplerState.AnisotropicWrap; GraphicsDevice.VertexShaderConstants[0] = constBuffer; return(true); }
/// <summary> /// Performs luminance measurement, tonemapping, applies bloom. /// </summary> /// <param name="target">LDR target.</param> /// <param name="hdrImage">HDR source image.</param> public void Render(Matrix view, Matrix projection, ShaderResource depthBuffer, ShaderResource wsNormals) { var device = Game.GraphicsDevice; var filter = Game.GetService <Filter>(); var ds = Game.GetService <DebugStrings>(); filter.StretchRect(downsampledDepth.Surface, depthBuffer); filter.StretchRect(downsampledNormals.Surface, wsNormals); // // Setup parameters : // var paramsData = new Params(); paramsData.ProjMatrix = projection; paramsData.View = view; paramsData.ViewProj = view * projection; paramsData.InvViewProj = Matrix.Invert(view * projection); paramsData.TraceStep = Config.TraceStep; paramsData.DecayRate = Config.DecayRate; paramsCB.SetData(paramsData); device.PixelShaderConstants[0] = paramsCB; // // Measure and adapt : // device.SetTargets(null, occlusionMap0); device.PixelShaderResources[0] = downsampledDepth; device.PixelShaderResources[1] = downsampledNormals; device.PixelShaderResources[2] = randomDir; device.PixelShaderSamplers[0] = SamplerState.LinearClamp; device.PipelineState = factory[(int)Flags.HBAO]; device.Draw(3, 0); device.ResetStates(); if (Config.BlurSigma != 0) { filter.GaussBlur(occlusionMap0, occlusionMap1, Config.BlurSigma, 0); } }
public void Update(double deltaSeconds) { // Poll input InputSnapshot snapshot = _window.PumpEvents(); InputTracker.UpdateFrameInput(snapshot); float circleWidth = 4f; float timeFactor = (float)DateTime.UtcNow.TimeOfDay.TotalMilliseconds / 1000; Vector3 position = new Vector3( (float)(Math.Cos(timeFactor) * circleWidth), 3 + (float)Math.Sin(timeFactor) * 2, (float)(Math.Sin(timeFactor) * circleWidth)); Vector3 lookDirection = -position; _viewMatrix = Matrix4x4.CreateLookAt(position, position + lookDirection, Vector3.UnitY); _viewBuffer.SetData(_viewMatrix); }
/// <summary> /// /// </summary> /// <param name="gameTime"></param> /// <param name="stereoEye"></param> protected override void Draw(GameTime gameTime, StereoEye stereoEye) { CBData cbData = new CBData(); var cam = GetService <Camera>(); GraphicsDevice.ClearBackbuffer(Color.CornflowerBlue, 1, 0); foreach (var e in space.Entities) { Box box = e as Box; if (box != null) // this won't create any graphics for an entity that isn't a box { if (box.IsDynamic) // draw only dynamic boxes { // fill world matrix Fusion.Mathematics.Matrix matrix = new Fusion.Mathematics.Matrix(box.WorldTransform.M11, box.WorldTransform.M12, box.WorldTransform.M13, box.WorldTransform.M14, box.WorldTransform.M21, box.WorldTransform.M22, box.WorldTransform.M23, box.WorldTransform.M24, box.WorldTransform.M31, box.WorldTransform.M32, box.WorldTransform.M33, box.WorldTransform.M34, box.WorldTransform.M41, box.WorldTransform.M42, box.WorldTransform.M43, box.WorldTransform.M44); cbData.Projection = cam.GetProjectionMatrix(stereoEye); cbData.View = cam.GetViewMatrix(stereoEye); cbData.World = matrix; cbData.ViewPos = new Vector4Fusion(cam.GetCameraMatrix(stereoEye).TranslationVector, 1); Color c = (Color)box.Tag; cbData.Color = c.ToVector4(); constBuffer.SetData(cbData); GraphicsDevice.PipelineState = factory[0]; GraphicsDevice.PixelShaderConstants[0] = constBuffer; GraphicsDevice.VertexShaderConstants[0] = constBuffer; GraphicsDevice.PixelShaderSamplers[0] = SamplerState.AnisotropicWrap; GraphicsDevice.PixelShaderResources[0] = texture; // setup data and draw box GraphicsDevice.SetupVertexInput(vb, ib); GraphicsDevice.DrawIndexed(36, 0, 0); } } } base.Draw(gameTime, stereoEye); }
/// <summary> /// /// </summary> /// <param name="dst"></param> /// <param name="cubeSrc"></param> /// <param name="sampleCount"></param> public void PrefilterEnvMap(RenderTargetCube envMap) { SetDefaultRenderStates(); int width = envMap.Width / 2; int height = envMap.Height / 2; using (new PixEvent("PrefilterEnvMap")) { var sides = new[] { ShaderFlags.PREFILTER_ENVMAP | ShaderFlags.POSX, ShaderFlags.PREFILTER_ENVMAP | ShaderFlags.NEGX, ShaderFlags.PREFILTER_ENVMAP | ShaderFlags.POSY, ShaderFlags.PREFILTER_ENVMAP | ShaderFlags.NEGY, ShaderFlags.PREFILTER_ENVMAP | ShaderFlags.POSZ, ShaderFlags.PREFILTER_ENVMAP | ShaderFlags.NEGZ }; // loop through mip levels from second to last specular mip level : for (int mip = 1; mip < RenderSystem.EnvMapSpecularMipCount; mip++) { float roughness = (float)mip / (float)(RenderSystem.EnvMapSpecularMipCount - 1); float step = 1.0f / width; vectorCB.SetData(new Vector4(roughness, step, 0, 0)); for (int face = 0; face < 6; face++) { device.SetTargets(null, envMap.GetSurface(mip, (CubeFace)face)); device.SetViewport(0, 0, width, height); device.PixelShaderConstants[0] = vectorCB; device.PipelineState = factory[(int)sides[face]]; device.VertexShaderResources[0] = envMap.GetCubeShaderResource(mip - 1); device.PixelShaderResources[0] = envMap.GetCubeShaderResource(mip - 1); device.PixelShaderSamplers[0] = SamplerState.LinearWrap; device.VertexShaderConstants[0] = matrixCB; device.Draw(3, 0); } width /= 2; height /= 2; } } device.ResetStates(); }
/// <summary> /// /// </summary> /// <param name="rs"></param> /// <param name="maxTextures"></param> internal MaterialInstance ( RenderSystem rs, ContentManager content, MaterialData parameters, IEnumerable<TextureMapBind> textureBinds, SurfaceFlags surfaceFlags ) { if (rs==null) { throw new ArgumentNullException("rs"); } if (textureBinds.Count()<0 || textureBinds.Count()>MaxTextures) { throw new ArgumentException("textureCount", "Must be less or equal to " + MaxTextures.ToString() ); } // // Pipeline states : // var factory = rs.SceneRenderer.Factory; var gbufferRigid = SurfaceFlags.GBUFFER | SurfaceFlags.RIGID | surfaceFlags ; var gbufferSkinned = SurfaceFlags.GBUFFER | SurfaceFlags.SKINNED | surfaceFlags ; var shadowRigid = SurfaceFlags.SHADOW | SurfaceFlags.RIGID | surfaceFlags ; var shadowSkinned = SurfaceFlags.SHADOW | SurfaceFlags.SKINNED | surfaceFlags ; GBufferRigid = factory[ (int)gbufferRigid ]; GBufferSkinned = factory[ (int)gbufferSkinned ]; ShadowRigid = factory[ (int)shadowRigid ]; ShadowSkinned = factory[ (int)shadowSkinned ]; // // Textures : // var textures = textureBinds .Select( texBind => texBind.TextureMap.LoadTexture( content, texBind.FallbackPath ) ); var uvMods = new Vector4[MaxTextures]; textureBinds .Select( tb => tb.TextureMap ) .Select( tm => new Vector4( tm.ScaleU, tm.ScaleV, tm.OffsetU, tm.OffsetV ) ) .ToArray() .CopyTo( uvMods, 0 ); shaderResources = textures.Select( tex => tex.Srv ).ToArray(); // // Constants : // constBufferParams = new ConstantBuffer( rs.Device, typeof(MaterialData) ); constBufferParams.SetData( parameters ); constBufferUVMods = new ConstantBuffer( rs.Device, typeof(Vector4), MaxTextures ); constBufferUVMods.SetData( uvMods ); }
/// <summary> /// Add services : /// </summary> protected override void Initialize () { // initialize services : base.Initialize(); // create structured buffers and shaders : argA = new StructuredBuffer( GraphicsDevice, typeof(float), BufferSize , StructuredBufferFlags.None ); argB = new StructuredBuffer( GraphicsDevice, typeof(float), BufferSize , StructuredBufferFlags.None ); result = new StructuredBuffer( GraphicsDevice, typeof(Result), BufferSize , StructuredBufferFlags.None ); paramsCB = new ConstantBuffer( GraphicsDevice, typeof(Params) ); shader = Content.Load<Ubershader>("test"); factory = new StateFactory( shader, typeof(ShaderFlags), Primitive.TriangleList, VertexInputElement.Empty ); // write data : var rand = new Random(); var a = Enumerable.Range(0, BufferSize).Select( i => rand.NextFloat(-1000,1000) ).ToArray(); var b = Enumerable.Range(0, BufferSize).Select( i => rand.NextFloat(-1000,1000) ).ToArray(); var r = Enumerable.Range(0, BufferSize).Select( i => new Result() ).ToArray(); argA.SetData( a ); argB.SetData( b ); paramsCB.SetData( new Params(){ Size = BufferSize } ); // bind objects : GraphicsDevice.SetCSRWBuffer( 0, argA ); GraphicsDevice.SetCSRWBuffer( 1, argB ); GraphicsDevice.SetCSRWBuffer( 2, result ); GraphicsDevice.ComputeShaderConstants[0] = paramsCB ; // set compute shader and dispatch threadblocks : GraphicsDevice.PipelineState = factory[0]; GraphicsDevice.Dispatch( MathUtil.IntDivUp(BufferSize,256) ); // get data : result.GetData( r ); Log.Message(" id : Sum Product gID gtID dtID gIdx"); for (int i=0; i<BufferSize; i++) { Log.Message("[{0,4}] : {1}", i, r[i] ); } // add keyboard handler : InputDevice.KeyDown += InputDevice_KeyDown; }
public PointsGisLayer(Game engine, int maxPointsCount, bool isDynamic = false) : base(engine) { DotsBuffer = new ConstantBuffer(engine.GraphicsDevice, typeof(DotsData)); ColorBuffer = new ConstantBuffer(engine.GraphicsDevice, typeof(ColorData), 16); PointsCountToDraw = maxPointsCount; PointsDrawOffset = 0; SizeMultiplier = 1; IsDynamic = isDynamic; var vbOptions = isDynamic ? VertexBufferOptions.Dynamic : VertexBufferOptions.Default; firstBuffer = new VertexBuffer(engine.GraphicsDevice, typeof(Gis.GeoPoint), maxPointsCount, vbOptions); currentBuffer = firstBuffer; PointsCpu = new Gis.GeoPoint[maxPointsCount]; Flags = (int) (PointFlags.DOTS_WORLDSPACE); shader = Game.Content.Load<Ubershader>("globe.Point.hlsl"); factory = shader.CreateFactory( typeof(PointFlags), Primitive.PointList, VertexInputElement.FromStructure<Gis.GeoPoint>(), BlendState.AlphaBlend, RasterizerState.CullCCW, DepthStencilState.None); ColorDatas = new ColorData[16]; for (int i = 0; i < ColorDatas.Length; i++) { ColorDatas[i] = new ColorData {Color = Color.White}; } ColorBuffer.SetData(ColorDatas); }