protected override void DoInitialize() { { // particleSimulator-fountain.comp is also OK. var shaderCode = new ShaderCode(File.ReadAllText(@"shaders\ParticleSimulatorRenderer\particleSimulator.comp"), ShaderType.ComputeShader); this.computeProgram = shaderCode.CreateProgram(); } { GLBuffer buffer = this.positionBuffer; Texture texture = buffer.DumpBufferTexture(OpenGL.GL_RGBA32F, autoDispose: false); texture.Initialize(); this.positionTexture = texture; } { GLBuffer buffer = this.velocityBuffer; Texture texture = buffer.DumpBufferTexture(OpenGL.GL_RGBA32F, autoDispose: false); texture.Initialize(); this.velocityTexture = texture; } { const int length = 64; UniformBuffer buffer = UniformBuffer.Create(typeof(vec4), length, BufferUsage.DynamicCopy); buffer.Bind(); OpenGL.BindBufferBase((BindBufferBaseTarget)BufferTarget.UniformBuffer, 0, buffer.BufferId); buffer.Unbind(); this.attractorBuffer = buffer; OpenGL.CheckError(); } }
public override UniformBuffer CreateUniformBuffer(ref BufferDescription description) { UniformBuffer ub = Factory.CreateUniformBuffer(ref description); DisposeCollector.Add(ub); return(ub); }
/// <summary> /// Apply this state to a shader program. /// </summary> /// <param name="ctx"> /// A <see cref="GraphicsContext"/> used to share common state between shaders. /// </param> /// <param name="shaderProgram"> /// A <see cref="ShaderProgram"/> that specify this uniform state. /// </param> /// <param name="uniformScope"> /// A <see cref="String"/> that specify the scope the uniform variable. /// </param> private void ApplyState(GraphicsContext ctx, ShaderProgram shaderProgram, string uniformScope) { if (shaderProgram == null) { throw new ArgumentNullException("shaderProgram"); } GraphicsResource.CheckCurrentContext(ctx); if (UniformBlockTag != null && UniformBuffer != null && shaderProgram.IsActiveUniformBlock(UniformBlockTag)) { // Update uniform buffer UniformBuffer.Map(ctx, BufferAccess.WriteOnly); try { ApplyState(ctx, UniformBuffer, null, UniformState.Values, this); } finally { UniformBuffer.Unmap(ctx); } // All uniforms at once shaderProgram.SetUniformBlock(ctx, UniformBlockTag, UniformBuffer); } else { ApplyState(ctx, shaderProgram, null, UniformState.Values, this); } }
protected override void DoInitialize() { { // particleSimulator-fountain.comp is also OK. var shaderCode = new ShaderCode(File.ReadAllText(@"shaders\ParticleSimulatorRenderer\particleSimulator.comp"), ShaderType.ComputeShader); this.computeProgram = shaderCode.CreateProgram(); } { BufferPtr bufferPtr = this.positionBufferPtr; Texture texture = bufferPtr.DumpBufferTexture(OpenGL.GL_RGBA32F, autoDispose: false); texture.Initialize(); this.positionTexture = texture; } { BufferPtr bufferPtr = this.velocityBufferPtr; Texture texture = bufferPtr.DumpBufferTexture(OpenGL.GL_RGBA32F, autoDispose: false); texture.Initialize(); this.velocityTexture = texture; } { IndependentBufferPtr bufferPtr = null; using (var buffer = new UniformBuffer <vec4>(BufferUsage.DynamicCopy, noDataCopyed: true)) { buffer.Create(elementCount: 64); bufferPtr = buffer.GetBufferPtr(); } bufferPtr.Bind(); OpenGL.BindBufferBase((BindBufferBaseTarget)BufferTarget.UniformBuffer, 0, bufferPtr.BufferId); this.attractorBufferPtr = bufferPtr; bufferPtr.Unbind(); } }
/// <summary> /// Create or update resources defined by this IGraphicsState, based on the associated <see cref="ShaderProgram"/>. /// </summary> /// <param name="ctx"> /// A <see cref="GraphicsContext"/> used for allocating resources. /// </param> /// <param name="shaderProgram"> /// A <see cref="ShaderProgram"/> that will be used in conjunction with this IGraphicsState. /// </param> public override void Create(GraphicsContext ctx, ShaderProgram shaderProgram) { // Create IGraphicsResource uniforms (i.e. textures) Dictionary <string, UniformStateMember> uniformState = UniformState; foreach (KeyValuePair <string, UniformStateMember> pair in uniformState) { if (pair.Value.GetUniformType().GetInterface("IGraphicsResource") == null) { continue; } IGraphicsResource graphicsResource = pair.Value.GetUniformValue(this) as IGraphicsResource; if (graphicsResource == null) { continue; } // Create the IGraphicsResource associated with the uniform state variable graphicsResource.Create(ctx); } // Create uniform buffer, if supported if (UniformBlockTag != null && shaderProgram != null && shaderProgram.IsActiveUniformBlock(UniformBlockTag) && UniformBuffer == null) { _UniformBuffer = shaderProgram.CreateUniformBlock(UniformBlockTag, MapBufferUsageMask.MapWriteBit); _UniformBuffer.Create(ctx); } // Base implementation base.Create(ctx, shaderProgram); }
private void CreateLightUniformBuffer(int bufferIndex) { // two ints + lights. two ints padded to 16 bytes var size = 16 + 1024; lightsBuffer = new UniformBuffer(GL.GenBuffer(), size, BufferUsageHint.DynamicDraw); lightsBuffer.SetBufferIndex(bufferIndex); }
public void CreateDeviceResources(GraphicsDevice gd, CommandList cl, OutputDescription outputDescription) { _gd = gd; ResourceFactory factory = gd.ResourceFactory; _vertexBuffer = factory.CreateVertexBuffer(new BufferDescription(10000, true)); _indexBuffer = factory.CreateIndexBuffer(new IndexBufferDescription(2000, IndexFormat.UInt16, true)); RecreateFontDeviceTexture(gd, cl); _projMatrixBuffer = factory.CreateUniformBuffer(new BufferDescription(64)); byte[] vertexShaderBytes = LoadEmbeddedShaderCode(gd.ResourceFactory, "imgui-vertex", ShaderStages.Vertex); byte[] fragmentShaderBytes = LoadEmbeddedShaderCode(gd.ResourceFactory, "imgui-frag", ShaderStages.Fragment); _vertexShader = factory.CreateShader(new ShaderDescription(ShaderStages.Vertex, vertexShaderBytes)); _fragmentShader = factory.CreateShader(new ShaderDescription(ShaderStages.Fragment, fragmentShaderBytes)); VertexLayoutDescription[] vertexLayouts = new VertexLayoutDescription[] { new VertexLayoutDescription( new VertexElementDescription("in_position", VertexElementSemantic.Position, VertexElementFormat.Float2), new VertexElementDescription("in_texCoord", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2), new VertexElementDescription("in_color", VertexElementSemantic.Color, VertexElementFormat.Byte4)) }; ShaderStageDescription[] shaderStages = new ShaderStageDescription[] { new ShaderStageDescription(ShaderStages.Vertex, _vertexShader, "VS"), new ShaderStageDescription(ShaderStages.Fragment, _fragmentShader, "FS") }; _layout = factory.CreateResourceLayout(new ResourceLayoutDescription( new ResourceLayoutElementDescription("ProjectionMatrixBuffer", ResourceKind.Uniform, ShaderStages.Vertex), new ResourceLayoutElementDescription("FontTexture", ResourceKind.Texture, ShaderStages.Fragment), new ResourceLayoutElementDescription("FontSampler", ResourceKind.Sampler, ShaderStages.Fragment))); PipelineDescription pd = new PipelineDescription( BlendStateDescription.SingleAlphaBlend, new DepthStencilStateDescription(false, false, DepthComparisonKind.Always), new RasterizerStateDescription(FaceCullMode.None, TriangleFillMode.Solid, FrontFace.Clockwise, false, true), PrimitiveTopology.TriangleList, new ShaderSetDescription(vertexLayouts, shaderStages), new ResourceLayout[] { _layout }, outputDescription); _pipeline = factory.CreatePipeline(ref pd); _resourceSet = factory.CreateResourceSet(new ResourceSetDescription(_layout, _projMatrixBuffer, _fontTextureView, gd.PointSampler)); }
/// <summary> /// Renders this camera. /// </summary> public void Render() { ValidateDispose(); // mark this as the currently rendering camera current = this; // set up the camera data buffer fo the render if (m_dataBuffer == null) { m_dataBuffer = new UniformBuffer <CameraData>(); } m_dataBuffer.Value = new CameraData(ViewMatrix, ProjectionMatrix); m_dataBuffer.BufferData(); // setup the lighting data buffer for the render if (m_lightBuffer == null) { m_lightBuffer = new UniformBuffer <LightData>(); } m_lightBuffer.Value = Entity.Scene.GetLightData(); m_lightBuffer.BufferData(); // clear the render target GL.ClearColor(m_clearColor); GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); // do culling on all renderable components List <Renderer> toRender = new List <Renderer>(); foreach (Renderer renderer in Entity.Scene.GetRenderables()) { if (!renderer.IsCulled()) { toRender.Add(renderer); } } // sort the rendered components to minimize state changes toRender.Sort(); // rendering all active components foreach (Renderer renderer in toRender) { renderer.Render(); } current = null; }
public static void LinkTransformsTo(this IStandardTransformMaterial me, UniformBuffer <Matrix4x4>?projection = null, UniformBuffer <Matrix4x4>?view = null, UniformBuffer <Matrix4x4>?world = null) { if (projection != null) { me.Projection.Buffer = projection.Buffer; } if (view != null) { me.View.Buffer = view.Buffer; } if (world != null) { me.World.Buffer = world.Buffer; } }
public Renderer(ShaderLibrary shaderLibrary, int width, int height) { State = new State(); Scheduler = new Scheduler(); ShaderLibrary = shaderLibrary; CameraUniformBuffer = new UniformBuffer <CameraData>(State, 0); SceneUniformBuffer = new UniformBuffer <SceneData>(State, 1); MaterialUniformBuffer = new UniformBuffer <MaterialData>(State, 2); ToneMapUniformBuffer = new UniformBuffer <ToneMapData>(State, 3); Quad = new Quad(State); Initialize(width, height); }
public ChunkBuffer() { //Setup all buffer allocators VertexBuffers = new UniformBuffer(false); BufferAllocators = new BufferAllocator[Sizes.Length]; unsafe { long *buf = (long *)VertexBuffers.Update(); for (int i = 0; i < Sizes.Length; i++) { BufferAllocators[i] = new BufferAllocator(Sizes[i], Counts[i], false, PixelInternalFormat.Rgba8ui); buf[i * 2] = BufferAllocators[i].BufferTex.View.GetTextureHandle().SetResidency(Residency.Resident); } VertexBuffers.UpdateDone(); } }
public void Use() { UniformBuffer.Use(); if (!LockBlendState) { BlendState.Execute(); } if (!LockFaceCullState) { FaceCullState.Execute(); } if (!LockDepthState) { DepthState.Execute(); } if (!LockMaskState) { MaskState.Execute(); } if (!LockStencilState) { StencilState.Execute(); } if (RenderStack.Graphics.Configuration.useGl1) { GL.Material( MaterialFace.FrontAndBack, MaterialParameter.AmbientAndDiffuse, UniformBuffer.Floats("surface_diffuse_reflectance_color").Value ); GL.Material( MaterialFace.FrontAndBack, MaterialParameter.Specular, UniformBuffer.Floats("surface_specular_reflectance_color").Value ); float r = UniformBuffer.Floats("surface_roughness").Value[0]; float shininess = (1 - r) * 128.0f; GL.Material( MaterialFace.FrontAndBack, MaterialParameter.Shininess, shininess ); } }
public RenderDriver( ProgramLoader pLoader, StaticImageLoader tLoader, Resolution resolution) { _resolution = resolution; _enable_debug_views = false; // Render UBOs _ubo_game_config = new UniformBuffer(BufferStorageFlags.DynamicStorageBit, 0, new EngineHelper.size[] { EngineHelper.size.vec4, EngineHelper.size.f }); _ubo_camera = new UniformBuffer(BufferStorageFlags.DynamicStorageBit, 1, new EngineHelper.size[] { EngineHelper.size.mat4, EngineHelper.size.mat4, EngineHelper.size.mat4, EngineHelper.size.mat4, EngineHelper.size.mat4, EngineHelper.size.vec3, EngineHelper.size.vec3 }); // Render FX List _effects = new List <RenderEffect>(); // Render FXs _fxQuad = createEffect <fx_Quad>(pLoader, "common/"); _fxTest = createEffect <fx_Test>(pLoader, "test/"); _fxCrosshair = createEffect <fx_Crosshair>(pLoader, tLoader, "crosshair/"); _fxSpecial = createEffect <fx_Special>(pLoader, "special/"); _fxFinal = createEffect <fx_Final>(pLoader, "final/"); _fxGBuffer = createEffect <fx_gBuffer>(pLoader, tLoader, "gBuffer/"); _fxVXGI = createEffect <fx_VXGI>(pLoader, "vxgi/"); _fxShadow = createEffect <fx_Shadow>(pLoader, "shadow/"); _fxSkyBox = createEffect <fx_SkyBox>(pLoader, tLoader, "skybox/"); _fxHDR = createEffect <fx_HDR>(pLoader, "hdr/"); _fxLens = createEffect <fx_Lens>(pLoader, tLoader, "lens/"); _fxDepthOfField = createEffect <fx_DepthOfField>(pLoader, tLoader, "dof/"); _fxMotionBlur = createEffect <fx_MotionBlur>(pLoader, "motion_blur/"); _fxAtmosphericScattering = createEffect <fx_AtmosphericScattering>(pLoader, "ats/"); }
internal void Write <T>(string v, T mYBuffer) where T : struct { var Value = myIDsToItems[v]; var MVPBuffer = new UniformBuffer <T>(mYBuffer); WriteDescriptorSet mySet = new WriteDescriptorSet(); mySet.DescriptorType = DescriptorType.UniformBuffer; mySet.DescriptorCount = Value.DescriptorCount; mySet.DstBinding = Value.Binding; mySet.DstSet = myDSet[Value.Binding]; unsafe { mySet.BufferInfo = new DescriptorBufferInfo[] { new DescriptorBufferInfo { Buffer = MVPBuffer, Offset = 0, Range = MVPBuffer.SizeOfBuffer } }; } VulkanRenderer.SelectedLogicalDevice.UpdateDescriptorSet(mySet, null); MVPBuffer.Dispose(); mySet.Dispose(); }
/// <summary> /// Apply this depth test render state. /// </summary> /// <param name="ctx"> /// A <see cref="GraphicsContext"/> which has defined the shader program <paramref name="shaderProgram"/>. /// </param> /// <param name="shaderProgram"> /// The <see cref="ShaderProgram"/> which has the state set. /// </param> public override void Apply(GraphicsContext ctx, ShaderProgram shaderProgram) { if (UniformBlockTag != null && shaderProgram != null && shaderProgram.IsActiveUniformBlock(UniformBlockTag)) { // Ensure uniform buffer existing if (UniformBuffer == null) { _UniformBuffer = shaderProgram.CreateUniformBlock(UniformBlockTag, MapBufferUsageMask.MapWriteBit); _UniformBuffer.Create(ctx); } // Apply uniforms to uniform buffer ApplyState(ctx, shaderProgram, String.Empty); // Set uniform block shaderProgram.SetUniformBlock(ctx, UniformBlockTag, _UniformBuffer); } else { // Apply uniforms to program ApplyState(ctx, shaderProgram, String.Empty); } }
/// <summary> /// Dispose resources allocated by <see cref="Create(GraphicsContext, ShaderProgram)"/>. /// </summary> public override void Delete() { if (_UniformBuffer != null) { _UniformBuffer.Dispose(); _UniformBuffer = null; } Dictionary <string, UniformStateMember> uniformState = UniformState; foreach (KeyValuePair <string, UniformStateMember> pair in uniformState) { if (pair.Value.GetUniformType().GetInterface("IGraphicsResource") == null) { continue; } IGraphicsResource graphicsResource = pair.Value.GetUniformValue(this) as IGraphicsResource; if (graphicsResource == null) { continue; } } }
public LightManager() { _light_count = 0; _lights = new Dictionary <int, Light>(); _lights_enabled = new List <Light>(); _lights_shadowed = new List <Light>(); _lights_shadowed_manifest = new List <Vector4>(); //vec4 info - (light type, id of this type, layer id, --) _ubo_shadow_manifest = new UniformBuffer(OpenTK.Graphics.OpenGL.BufferStorageFlags.DynamicStorageBit, 3, new EngineHelper.size[] { EngineHelper.size.vec4 }, 32); //mat4 view //mat4 perspective //mat4 viewray //vec4 - vec3 light_position / float falloff //vec4 - vec3 light_color / float intensity //vec4 - vec3 light_direction //vec4 - float spot_angle / float spot_blur _ubo_shadow_spot = new UniformBuffer(OpenTK.Graphics.OpenGL.BufferStorageFlags.DynamicStorageBit, 4, new EngineHelper.size[] { EngineHelper.size.mat4, EngineHelper.size.mat4, EngineHelper.size.mat4, EngineHelper.size.vec4, EngineHelper.size.vec4, EngineHelper.size.vec4, EngineHelper.size.vec4, }, 32); //mat4 view[6] //mat4 perspective //vec4 - vec3 light_position / float falloff //vec4 - vec3 light_color / float intensity _ubo_shadow_point = new UniformBuffer(OpenTK.Graphics.OpenGL.BufferStorageFlags.DynamicStorageBit, 5, new EngineHelper.size[] { EngineHelper.size.mat4, EngineHelper.size.mat4, EngineHelper.size.mat4, EngineHelper.size.mat4, EngineHelper.size.mat4, EngineHelper.size.mat4, EngineHelper.size.mat4, EngineHelper.size.mat4, EngineHelper.size.mat4, EngineHelper.size.mat4, EngineHelper.size.mat4, EngineHelper.size.mat4, EngineHelper.size.mat4, EngineHelper.size.vec4, EngineHelper.size.vec4, }, 32); //mat4 view[4] //mat4 perspective[4] //vec4 light_position _ubo_shadow_directional = new UniformBuffer(OpenTK.Graphics.OpenGL.BufferStorageFlags.DynamicStorageBit, 6, new EngineHelper.size[] { EngineHelper.size.mat4, EngineHelper.size.mat4, EngineHelper.size.mat4, EngineHelper.size.mat4, EngineHelper.size.mat4, EngineHelper.size.mat4, EngineHelper.size.mat4, EngineHelper.size.mat4, EngineHelper.size.vec4, }, 1); }
public override void Bind(UniformBuffer uniformBuffer) { BufferNameGL3x bufferHandle = ((UniformBufferGL3x)uniformBuffer).Handle; GL.BindBufferBase(BufferTarget.UniformBuffer, _bindHandle, bufferHandle.Value); }
private void ReadMaterialData(string relative_path) { BinaryReader reader = new BinaryReader(Project.directory_path + "\\" + relative_path); if (!reader.is_ok) { return; } MaterialData material_data = new MaterialData(); material_data.Read(reader); AssetDatabase asset_database = (AssetDatabase)App.Current.Resources["asset_database"]; AssetCacheData pixel_shader_cache = asset_database.Find(material_data.pixel_shader_id, AssetType.kShader); ShaderData pixelShader = ReadShaderData(pixel_shader_cache.path); ub = new UniformBuffer(pixelShader, material_data.uniform_buffers[0].data); inspector_.ClearInspectors(); foreach (var pair in ub.name_map_) { ShaderVariable var = ub.data_map_[pair.Value]; InspectorTypes type = InspectorTypes.kNumber; switch (var.type_) { case ShaderVarType.kBool: type = InspectorTypes.kCheckbox; break; case ShaderVarType.kFloat: case ShaderVarType.kDouble: type = InspectorTypes.kSlider; break; case ShaderVarType.kUint: case ShaderVarType.kUint8: case ShaderVarType.kInt: type = InspectorTypes.kNumber; break; case ShaderVarType.kMat3: type = InspectorTypes.kMatrix3x3; break; case ShaderVarType.kMat4: type = InspectorTypes.kMatrix4x4; break; case ShaderVarType.kVec2: type = InspectorTypes.kVector2; break; case ShaderVarType.kVec3: type = InspectorTypes.kVector3; break; case ShaderVarType.kVec4: type = InspectorTypes.kVector4; break; } inspector_.AddInspector(pair.Key, type, new VarRef(() => ub.data_map_[pair.Value].data_, val => { ub.data_map_[pair.Value].Set(val); material_data.uniform_buffers[0].data = ub.ConstructDataBuffer(); StoreMaterialData(relative_path, material_data); })); } }
public ViewProjectionProvider(World world, UniformBuffer <Matrix4x4> cameraViewProjection) : base(world) { _cameraViewProjection = cameraViewProjection; }
public virtual void Bind(UniformBuffer uniformBuffer) { }
public void BindUniformBuffer <T>(string name, UniformBuffer <T> buffer) where T : unmanaged { GL.UniformBlockBinding(Id, GL.GetUniformBlockIndex(Id, name), buffer.BindingIndex); }
public WorldViewer(ITagContainer diContainer) { this.diContainer = diContainer; resourcePool = diContainer.GetTag <IResourcePool>(); Window = diContainer.GetTag <WindowContainer>().NewWindow("World Viewer"); Window.AddTag(this); Window.InitialBounds = new Rect(float.NaN, float.NaN, 1100.0f, 600.0f); editor = new TwoColumnEditorTag(Window, diContainer); var onceAction = new OnceAction(); Window.AddTag(onceAction); Window.OnContent += onceAction.Invoke; Window.OnContent += UpdateIntersectionPrimitive; Window.OnKeyDown += HandleKeyDown; var menuBar = new MenuBarWindowTag(Window); menuBar.AddButton("Open", HandleMenuOpen); var gridRenderer = new DebugGridRenderer(diContainer); //gridRenderer.Material.LinkTransformsTo(controls.Projection, controls.View, controls.World); AddDisposable(gridRenderer); modelMaterialEdit = new ModelMaterialEdit(Window, diContainer); modelMaterialEdit.OpenEntriesByDefault = false; diContainer.GetTag <OpenDocumentSet>().AddEditor(this); openFileModal = new OpenFileModal(diContainer); openFileModal.Filter = "*.bsp"; openFileModal.IsFilterChangeable = false; openFileModal.OnOpenedResource += Load; locationBuffer = new LocationBuffer(diContainer.GetTag <GraphicsDevice>()); AddDisposable(locationBuffer); camera = new Camera(diContainer.ExtendedWith(locationBuffer)); AddDisposable(camera); controls = new FlyControlsTag(Window, camera.Location, diContainer); worldTransform = new UniformBuffer <Matrix4x4>(diContainer.GetTag <GraphicsDevice>().ResourceFactory); worldTransform.Ref = Matrix4x4.Identity; AddDisposable(worldTransform); fbArea = Window.GetTag <FramebufferArea>(); fbArea.OnResize += HandleResize; fbArea.OnRender += locationBuffer.Update; fbArea.OnRender += worldTransform.Update; fbArea.OnRender += camera.Update; fbArea.OnRender += gridRenderer.Render; fbArea.OnRender += HandleRender; editor.AddInfoSection("Statistics", HandleStatisticsContent); editor.AddInfoSection("Materials", HandleMaterialsContent, false); editor.AddInfoSection("Sections", HandleSectionsContent, false); editor.AddInfoSection("ViewFrustum Culling", HandleViewFrustumCulling, false); editor.AddInfoSection("Collision", HandleCollision, false); editor.AddInfoSection("Raycast", HandleRaycast, true); boundsRenderer = new DebugBoxLineRenderer(diContainer); boundsRenderer.Color = IColor.Red; boundsRenderer.Material.LinkTransformsTo(camera); boundsRenderer.Material.LinkTransformsTo(world: worldTransform); AddDisposable(boundsRenderer); planeRenderer = new DebugPlaneRenderer(diContainer); planeRenderer.Material.LinkTransformsTo(camera); planeRenderer.Material.LinkTransformsTo(world: worldTransform); AddDisposable(planeRenderer); frustumRenderer = new DebugHexahedronLineRenderer(diContainer); frustumRenderer.Material.LinkTransformsTo(camera); frustumRenderer.Material.LinkTransformsTo(world: worldTransform); AddDisposable(frustumRenderer); triangleRenderer = new DebugTriangleLineRenderer(diContainer); triangleRenderer.Material.LinkTransformsTo(camera); triangleRenderer.Material.LinkTransformsTo(world: worldTransform); AddDisposable(triangleRenderer); rayRenderer = new DebugLineRenderer(diContainer); rayRenderer.Material.LinkTransformsTo(camera); rayRenderer.Material.LinkTransformsTo(world: worldTransform); AddDisposable(rayRenderer); worldRenderer = new WorldRenderer(diContainer.ExtendedWith(camera, locationBuffer)); AddDisposable(worldRenderer); }
public MaterialManager() { // Create UBO for bindless material textures _ubo_bindless = new UniformBuffer(OpenTK.Graphics.OpenGL.BufferStorageFlags.DynamicStorageBit, 2, EngineHelper.size.i64, 256 * 2); }
public unsafe override void CreateDeviceObjects(GraphicsDevice gd, CommandList cl, SceneContext sc) { ResourceFactory factory = gd.ResourceFactory; _vb = factory.CreateVertexBuffer(new BufferDescription(s_vertices.SizeInBytes())); cl.UpdateBuffer(_vb, 0, s_vertices); _ib = factory.CreateIndexBuffer(new IndexBufferDescription(s_indices.SizeInBytes(), IndexFormat.UInt16)); cl.UpdateBuffer(_ib, 0, s_indices); _viewMatrixBuffer = factory.CreateUniformBuffer(new BufferDescription((ulong)Unsafe.SizeOf <Matrix4x4>())); Texture textureCube; TextureView textureView; fixed(Rgba32 *frontPin = &_front.DangerousGetPinnableReferenceToPixelBuffer()) fixed(Rgba32 * backPin = &_back.DangerousGetPinnableReferenceToPixelBuffer()) fixed(Rgba32 * leftPin = &_left.DangerousGetPinnableReferenceToPixelBuffer()) fixed(Rgba32 * rightPin = &_right.DangerousGetPinnableReferenceToPixelBuffer()) fixed(Rgba32 * topPin = &_top.DangerousGetPinnableReferenceToPixelBuffer()) fixed(Rgba32 * bottomPin = &_bottom.DangerousGetPinnableReferenceToPixelBuffer()) { uint width = (uint)_front.Width; uint height = (uint)_front.Height; textureCube = factory.CreateTexture(new TextureDescription( width, height, 1, 1, 1, PixelFormat.R8_G8_B8_A8_UNorm, TextureUsage.Sampled | TextureUsage.Cubemap)); uint faceSize = (uint)(_front.Width * _front.Height * Unsafe.SizeOf <Rgba32>()); cl.UpdateTextureCube(textureCube, (IntPtr)leftPin, faceSize, CubeFace.NegativeX, 0, 0, width, height, 0, 0); cl.UpdateTextureCube(textureCube, (IntPtr)rightPin, faceSize, CubeFace.PositiveX, 0, 0, width, height, 0, 0); cl.UpdateTextureCube(textureCube, (IntPtr)bottomPin, faceSize, CubeFace.NegativeY, 0, 0, width, height, 0, 0); cl.UpdateTextureCube(textureCube, (IntPtr)topPin, faceSize, CubeFace.PositiveY, 0, 0, width, height, 0, 0); cl.UpdateTextureCube(textureCube, (IntPtr)backPin, faceSize, CubeFace.NegativeZ, 0, 0, width, height, 0, 0); cl.UpdateTextureCube(textureCube, (IntPtr)frontPin, faceSize, CubeFace.PositiveZ, 0, 0, width, height, 0, 0); textureView = factory.CreateTextureView(new TextureViewDescription(textureCube)); } VertexLayoutDescription[] vertexLayouts = new VertexLayoutDescription[] { new VertexLayoutDescription( new VertexElementDescription("Position", VertexElementSemantic.Position, VertexElementFormat.Float3)) }; Shader vs = ShaderHelper.LoadShader(factory, "Skybox", ShaderStages.Vertex); Shader fs = ShaderHelper.LoadShader(factory, "Skybox", ShaderStages.Fragment); ShaderStageDescription[] shaderStages = new ShaderStageDescription[] { new ShaderStageDescription(ShaderStages.Vertex, vs, "VS"), new ShaderStageDescription(ShaderStages.Fragment, fs, "VS"), }; _layout = factory.CreateResourceLayout(new ResourceLayoutDescription( new ResourceLayoutElementDescription("Projection", ResourceKind.Uniform, ShaderStages.Vertex), new ResourceLayoutElementDescription("View", ResourceKind.Uniform, ShaderStages.Vertex), new ResourceLayoutElementDescription("CubeTexture", ResourceKind.Texture, ShaderStages.Fragment), new ResourceLayoutElementDescription("CubeSampler", ResourceKind.Sampler, ShaderStages.Fragment))); PipelineDescription pd = new PipelineDescription( BlendStateDescription.SingleAlphaBlend, DepthStencilStateDescription.LessEqual, new RasterizerStateDescription(FaceCullMode.None, TriangleFillMode.Solid, FrontFace.Clockwise, false, true), PrimitiveTopology.TriangleList, new ShaderSetDescription(vertexLayouts, shaderStages), new ResourceLayout[] { _layout }, gd.SwapchainFramebuffer.OutputDescription); _pipeline = factory.CreatePipeline(ref pd); _resourceSet = factory.CreateResourceSet(new ResourceSetDescription( _layout, sc.ProjectionMatrixBuffer, _viewMatrixBuffer, textureView, gd.PointSampler)); _disposeCollector.Add(_vb, _ib, _viewMatrixBuffer, textureCube, textureView, _layout, _pipeline, _resourceSet, vs, fs); }
public static void CreateResources() { uniform0 = new UniformBuffer <UniformBufferObject>(graphicsDevice, 0); }
public void SetSharedUniforms(UniformBuffer uniforms) { SharedUniforms = uniforms; Instructions |= CommandInstructions.SetSharedUniforms; }
public Material() { _ubo = new UniformBuffer(64f, 0.2f, 20.0f, 0.5f, 1.0f, new Vector4(1f, 1f, 1f, 1f), new Vector4(1f, 1f, 1f, 1f), new Vector4(1f, 1f, 1f, 1f)); _buffer = new Buffer(BufferTarget.UniformBuffer, BufferUsageHint.DynamicDraw); _changed = true; }
public Material(float sh, float ni, float ab, float gm, float gc, Vector4 amb, Vector4 dif, Vector4 spec) { _ubo = new UniformBuffer(sh, ni, ab, gm, gc, amb, dif, spec); _buffer = new Buffer(BufferTarget.UniformBuffer, BufferUsageHint.DynamicDraw); _changed = true; }
//Deferred Renderer Rework - New GBuffer - //32:32:32 WorldPos, (16b:SPARE, 16b:materialIdx) //8:8:8 Norm, 8:SPARE //reproject z buffer and recompute chain for culling public DeferredRenderer(Framebuffer[] fbufs, LightManager man) { lMan = man; InfoBindings = new TextureBinding[fbufs.Length]; InfoBindings2 = new TextureBinding[fbufs.Length]; DepthBindings = new TextureBinding[fbufs.Length]; Framebuffers = new Framebuffer[fbufs.Length]; HiZMap = new TextureView[fbufs.Length][]; views = new ViewData[fbufs.Length]; HiZMapUBO = new UniformBuffer(false); unsafe { int off = 0; float *fp = (float *)HiZMapUBO.Update(); fp += 4; for (int i = 0; i < views.Length; i++) { views[i] = new ViewData() { depthBuf = new Texture() { Width = fbufs[i].Width, Height = fbufs[i].Height, Depth = 1, Format = PixelInternalFormat.DepthComponent32f, GenerateMipmaps = false, LayerCount = 1, LevelCount = 1, Target = TextureTarget.Texture2D }.Build(), infoTex = new Texture() { Width = fbufs[i].Width, Height = fbufs[i].Height, Depth = 1, Format = PixelInternalFormat.Rgba32f, GenerateMipmaps = false, LayerCount = 1, LevelCount = 1, Target = TextureTarget.Texture2D }.Build(), infoTex2 = new Texture() { Width = fbufs[i].Width, Height = fbufs[i].Height, Depth = 1, Format = PixelInternalFormat.Rgba8, GenerateMipmaps = false, LayerCount = 1, LevelCount = 1, Target = TextureTarget.Texture2D }.Build(), hiZ = new Texture() { Width = fbufs[i].Width, Height = fbufs[i].Height, Depth = 1, Format = PixelInternalFormat.Rg32f, GenerateMipmaps = false, LayerCount = 1, LevelCount = (int)(MathHelper.Log2((ulong)Math.Max(fbufs[i].Width, fbufs[i].Height)) + 1), Target = TextureTarget.Texture2D }.Build(), gbuffer = new Framebuffer(fbufs[i].Width, fbufs[i].Height), }; views[i].depthView = new TextureView() { BaseLayer = 0, BaseLevel = 0, Format = PixelInternalFormat.DepthComponent32f, LayerCount = 1, LevelCount = 1, Target = TextureTarget.Texture2D }.Build(views[i].depthBuf); views[i].infoView = new TextureView() { BaseLayer = 0, BaseLevel = 0, Format = PixelInternalFormat.Rgba32f, LayerCount = 1, LevelCount = 1, Target = TextureTarget.Texture2D }.Build(views[i].infoTex); views[i].infoView2 = new TextureView() { BaseLayer = 0, BaseLevel = 0, Format = PixelInternalFormat.Rgba8, LayerCount = 1, LevelCount = 1, Target = TextureTarget.Texture2D }.Build(views[i].infoTex2); views[i].hiZView = new TextureView[views[i].hiZ.LevelCount]; for (int j = 0; j < views[i].hiZView.Length; j++) { views[i].hiZView[j] = new TextureView() { BaseLayer = 0, BaseLevel = j, Format = PixelInternalFormat.Rg32f, LayerCount = 1, LevelCount = 1, Target = TextureTarget.Texture2D, }.Build(views[i].hiZ); var f_arr = (float[])views[i].hiZView[j].GetImageHandle().SetResidency(Residency.Resident, AccessMode.ReadWrite); for (int q = 0; q < f_arr.Length; q++) { *(fp++) = f_arr[q]; } fp += 2; } views[i].hiZTex = new TextureView() { BaseLayer = 0, BaseLevel = 0, Format = PixelInternalFormat.Rg32f, LayerCount = 1, LevelCount = views[i].hiZView.Length, Target = TextureTarget.Texture2D }.Build(views[i].hiZ); var sampler = new TextureSampler(); sampler.SetEnableLinearFilter(false, true, false); sampler.MinReadLevel = 0; sampler.MaxReadLevel = views[i].hiZView.Length; sampler.SetTileMode(TileMode.ClampToBorder, TileMode.ClampToBorder); views[i].hiZBinding = new TextureBinding() { View = views[i].hiZTex, Sampler = sampler }; var f_arr_ = (float[])views[i].hiZBinding.GetTextureHandle().SetResidency(Residency.Resident); for (int q = 0; q < f_arr_.Length; q++) { *(fp++) = f_arr_[q]; } fp += 2; views[i].gbuffer[FramebufferAttachment.DepthAttachment] = views[i].depthView; views[i].gbuffer[FramebufferAttachment.ColorAttachment0] = views[i].infoView; views[i].gbuffer[FramebufferAttachment.ColorAttachment1] = views[i].infoView2; Framebuffers[i] = views[i].gbuffer; views[i].program = new ShaderProgram( ShaderSource.Load(ShaderType.VertexShader, "Shaders/RenderToTexture/FrameBufferTriangle/vertex.glsl"), ShaderSource.Load(ShaderType.FragmentShader, "Shaders/RenderToTexture/FrameBufferTriangle/fragment.glsl") ); views[i].copy = new ShaderProgram( ShaderSource.Load(ShaderType.ComputeShader, "Shaders/HiZ/copy.glsl", $"#define MIP_COUNT {views[i].hiZView.Length}") ); views[i].copyState = new RenderState(null, views[i].copy, null, new UniformBuffer[] { Engine.GlobalParameters, HiZMapUBO }, false, false, DepthFunc.Always, InverseDepth.Far, InverseDepth.Near, BlendFactor.SrcAlpha, BlendFactor.OneMinusSrcAlpha, Vector4.Zero, InverseDepth.ClearDepth, CullFaceMode.Back); views[i].mipchain = new ShaderProgram( ShaderSource.Load(ShaderType.ComputeShader, "Shaders/HiZ/mipchain.glsl", $"#define MIP_COUNT {views[i].hiZView.Length}") ); views[i].mipchainState = new RenderState(null, views[i].mipchain, null, new UniformBuffer[] { Engine.GlobalParameters, HiZMapUBO }, false, false, DepthFunc.Always, InverseDepth.Far, InverseDepth.Near, BlendFactor.SrcAlpha, BlendFactor.OneMinusSrcAlpha, Vector4.Zero, InverseDepth.ClearDepth, CullFaceMode.Back); views[i].state = new RenderState(fbufs[i], views[i].program, null, new UniformBuffer[] { Engine.GlobalParameters }, false, true, DepthFunc.Always, InverseDepth.Far, InverseDepth.Near, BlendFactor.SrcAlpha, BlendFactor.OneMinusSrcAlpha, Vector4.Zero, InverseDepth.ClearDepth, CullFaceMode.None); InfoBindings[i] = new TextureBinding() { View = views[i].infoView, Sampler = TextureSampler.Default }; InfoBindings[i].GetTextureHandle().SetResidency(Residency.Resident); InfoBindings2[i] = new TextureBinding() { View = views[i].infoView2, Sampler = TextureSampler.Default }; InfoBindings2[i].GetTextureHandle().SetResidency(Residency.Resident); DepthBindings[i] = new TextureBinding() { View = views[i].depthView, Sampler = TextureSampler.Default, }; DepthBindings[i].GetTextureHandle().SetResidency(Residency.Resident); HiZMap[i] = views[i].hiZView; views[i].cBuffer = new CommandBuffer(); views[i].cBuffer.SetRenderState(views[i].state); views[i].cBuffer.Draw(PrimitiveType.Triangles, 0, 3, 1, 0); } HiZMapUBO.UpdateDone(); } }