CommandBuffer[] AllocateCommandBuffers(CommandPool commandPool, uint buffersToAllocate) { // Command buffers are objects used to record commands which can be subsequently submitted // to a device queue for execution. There are two levels of command buffers - primary // command buffers, which can execute secondary command buffers, and which are submitted to // queues, and secondary command buffers, which can be executed by primary command buffers, // and which are not directly submitted to queues. // // Recorded commands include commands to bind pipelines and descriptor sets to the command // buffer, commands to modify dynamic state, commands to draw (for graphics rendering), // commands to dispatch(for compute), commands to execute secondary command buffers (for // primary command buffers only), commands to copy buffers and images, and other commands. var commandBufferAllocationInfo = new CommandBufferAllocateInfo(commandPool, CommandBufferLevel.Primary, buffersToAllocate); var commandBuffers = device.AllocateCommandBuffers(commandBufferAllocationInfo); if (commandBuffers.Length == 0) { throw new InvalidOperationException("Couldn't allocate any command buffers"); } return(commandBuffers); }
/// <summary> /// 获取命令池 /// </summary> /// <param name=""></param> /// <returns>命令池</returns> /// <memo></memo> public CommandPool GetCommandPool() { IntPtr __ptr = CControlSpace_getCommandPool_CCommandPool(this.NativeObject); if (__ptr == IntPtr.Zero) { return(null); } CommandPool csObj = new CommandPool(CreatedWhenConstruct.CWC_NotToCreate); csObj.BindNativeObject(__ptr, "CCommandPool"); csObj.Delegate = true; IClassFactory csObjClassFactory = GlobalClassFactoryMap.Get(csObj.GetCppInstanceTypeName()); if (csObjClassFactory != null) { csObj.Delegate = true; csObj = csObjClassFactory.Create() as CommandPool; csObj.BindNativeObject(__ptr, "CCommandPool"); csObj.Delegate = true; } return(csObj); }
public PbrModelTexArray(Queue transferQ, string path) { dev = transferQ.Dev; using (CommandPool cmdPool = new CommandPool(dev, transferQ.index)) { using (glTFLoader ctx = new glTFLoader(path, transferQ, cmdPool)) { loadSolids <Vertex> (ctx); if (ctx.ImageCount > 0) { texArray = new Image(dev, Image.DefaultTextureFormat, VkImageUsageFlags.Sampled | VkImageUsageFlags.TransferDst | VkImageUsageFlags.TransferSrc, VkMemoryPropertyFlags.DeviceLocal, TEXTURE_DIM, TEXTURE_DIM, VkImageType.Image2D, VkSampleCountFlags.SampleCount1, VkImageTiling.Optimal, Image.ComputeMipLevels(TEXTURE_DIM), ctx.ImageCount); ctx.BuildTexArray(ref texArray, 0); } else { texArray = new Image(dev, Image.DefaultTextureFormat, VkImageUsageFlags.Sampled | VkImageUsageFlags.TransferDst | VkImageUsageFlags.TransferSrc, VkMemoryPropertyFlags.DeviceLocal, TEXTURE_DIM, TEXTURE_DIM, VkImageType.Image2D, VkSampleCountFlags.SampleCount1, VkImageTiling.Optimal, Image.ComputeMipLevels(TEXTURE_DIM), 1); PrimaryCommandBuffer cmd = cmdPool.AllocateAndStart(VkCommandBufferUsageFlags.OneTimeSubmit); texArray.SetLayout(cmd, VkImageAspectFlags.Color, VkImageLayout.ShaderReadOnlyOptimal); transferQ.EndSubmitAndWait(cmd, true); } texArray.CreateView(VkImageViewType.ImageView2DArray, VkImageAspectFlags.Color, texArray.CreateInfo.arrayLayers); texArray.CreateSampler(); texArray.Descriptor.imageLayout = VkImageLayout.ShaderReadOnlyOptimal; texArray.SetName("model texArray"); loadMaterials(ctx); materialUBO = new HostBuffer <Material> (dev, VkBufferUsageFlags.UniformBuffer, materials); } } }
public void Reset() { CommandPool.Reset(); CommandBuffer.Reset(); }
public CommandBufferTest(DefaultHandles defaults, ITestOutputHelper output) : base(defaults, output) { CommandPool = Device.CreateCommandPool( new CommandPoolCreateInfo(defaults.GraphicsQueue.FamilyIndex, CommandPoolCreateFlags.ResetCommandBuffer)); CommandBuffer = CommandPool.AllocateBuffers(new CommandBufferAllocateInfo(CommandBufferLevel.Primary, 1))[0]; }
/// <summary> /// Initializes the specified device. /// </summary> /// <param name="graphicsProfiles">The graphics profiles.</param> /// <param name="deviceCreationFlags">The device creation flags.</param> /// <param name="windowHandle">The window handle.</param> private unsafe void InitializePlatformDevice(GraphicsProfile[] graphicsProfiles, DeviceCreationFlags deviceCreationFlags, object windowHandle) { if (nativeDevice != Device.Null) { // Destroy previous device ReleaseDevice(); } rendererName = Adapter.Description; PhysicalDeviceProperties physicalDeviceProperties; NativePhysicalDevice.GetProperties(out physicalDeviceProperties); ConstantBufferDataPlacementAlignment = (int)physicalDeviceProperties.Limits.MinUniformBufferOffsetAlignment; RequestedProfile = graphicsProfiles.Last(); var queueProperties = NativePhysicalDevice.QueueFamilyProperties; // Command lists are thread-safe and execute deferred IsDeferred = true; // TODO VULKAN // Create Vulkan device based on profile uint queuePriorities = 0; var queueCreateInfo = new DeviceQueueCreateInfo { StructureType = StructureType.DeviceQueueCreateInfo, QueueFamilyIndex = 0, QueueCount = 1, QueuePriorities = new IntPtr(&queuePriorities) }; var enabledFeature = new PhysicalDeviceFeatures { FillModeNonSolid = true, ShaderClipDistance = true, ShaderCullDistance = true, SamplerAnisotropy = true, DepthClamp = true, }; var extensionProperties = NativePhysicalDevice.GetDeviceExtensionProperties(); var availableExtensionNames = new List <string>(); var desiredExtensionNames = new List <string>(); for (int index = 0; index < extensionProperties.Length; index++) { var namePointer = new IntPtr(Interop.Fixed(ref extensionProperties[index].ExtensionName)); var name = Marshal.PtrToStringAnsi(namePointer); availableExtensionNames.Add(name); } desiredExtensionNames.Add("VK_KHR_swapchain"); if (!availableExtensionNames.Contains("VK_KHR_swapchain")) { throw new InvalidOperationException(); } if (availableExtensionNames.Contains("VK_EXT_debug_marker") && IsDebugMode) { desiredExtensionNames.Add("VK_EXT_debug_marker"); IsProfilingSupported = true; } var enabledExtensionNames = desiredExtensionNames.Select(Marshal.StringToHGlobalAnsi).ToArray(); try { var deviceCreateInfo = new DeviceCreateInfo { StructureType = StructureType.DeviceCreateInfo, QueueCreateInfoCount = 1, QueueCreateInfos = new IntPtr(&queueCreateInfo), EnabledExtensionCount = (uint)enabledExtensionNames.Length, EnabledExtensionNames = enabledExtensionNames.Length > 0 ? new IntPtr(Interop.Fixed(enabledExtensionNames)) : IntPtr.Zero, EnabledFeatures = new IntPtr(&enabledFeature) }; nativeDevice = NativePhysicalDevice.CreateDevice(ref deviceCreateInfo); } finally { foreach (var enabledExtensionName in enabledExtensionNames) { Marshal.FreeHGlobal(enabledExtensionName); } } NativeCommandQueue = nativeDevice.GetQueue(0, 0); //// Prepare copy command list (start it closed, so that every new use start with a Reset) var commandPoolCreateInfo = new CommandPoolCreateInfo { StructureType = StructureType.CommandPoolCreateInfo, QueueFamilyIndex = 0, //device.NativeCommandQueue.FamilyIndex Flags = CommandPoolCreateFlags.ResetCommandBuffer }; NativeCopyCommandPool = NativeDevice.CreateCommandPool(ref commandPoolCreateInfo); var commandBufferAllocationInfo = new CommandBufferAllocateInfo { StructureType = StructureType.CommandBufferAllocateInfo, Level = CommandBufferLevel.Primary, CommandPool = NativeCopyCommandPool, CommandBufferCount = 1 }; CommandBuffer nativeCommandBuffer; NativeDevice.AllocateCommandBuffers(ref commandBufferAllocationInfo, &nativeCommandBuffer); NativeCopyCommandBuffer = nativeCommandBuffer; DescriptorPools = new HeapPool(this); nativeResourceCollector = new NativeResourceCollector(this); graphicsResourceLinkCollector = new GraphicsResourceLinkCollector(this); EmptyTexelBuffer = Buffer.Typed.New(this, 1, PixelFormat.R32G32B32A32_Float); }
protected virtual void CreateCommandBuffer() { // Command pool var commandPoolCreateInfo = new CommandPoolCreateInfo { StructureType = StructureType.CommandPoolCreateInfo, QueueFamilyIndex = 0, Flags = CommandPoolCreateFlags.ResetCommandBuffer }; commandPool = device.CreateCommandPool(ref commandPoolCreateInfo); // Command buffer var commandBufferAllocationInfo = new CommandBufferAllocateInfo { StructureType = StructureType.CommandBufferAllocateInfo, Level = CommandBufferLevel.Primary, CommandPool = commandPool, CommandBufferCount = 1 }; CommandBuffer commandBuffer; device.AllocateCommandBuffers(ref commandBufferAllocationInfo, &commandBuffer); this.commandBuffer = commandBuffer; }
public async Task Check(IDiscordMessage e, ICommandHandler c, string identifier = "") { Log.Message($"Entering {Name}!"); string command = e.Content.Substring(identifier.Length).Split(' ')[0]; string args = ""; List <string> allAliases = new List <string>(); string[] arguments = new string[0]; if (e.Content.Split(' ').Length > 1) { args = e.Content.Substring(e.Content.Split(' ')[0].Length + 1); arguments = args.Split(' '); } if (Module != null) { if (Module.Nsfw && !e.Channel.Nsfw) { return; } } if (Aliases != null) { allAliases.AddRange(Aliases); allAliases.Add(Name); } if (!await IsEnabled(e.Channel.Id)) { Log.WarningAt(Name, " is disabled"); return; } if (IsOnCooldown(e.Author.Id)) { Log.WarningAt(Name, " is on cooldown"); return; } if (GuildPermissions.Count > 0) { foreach (DiscordGuildPermission g in GuildPermissions) { if (!e.Author.HasPermissions(e.Channel, g)) { await e.Channel.SendMessage($"Please give me the guild permission `{g}` to use this command."); return; } } } ProcessCommandDelegate targetCommand = ProcessCommand; if (arguments.Length > 0) { if (CommandPool.ContainsKey(arguments[0])) { targetCommand = CommandPool[arguments[0]]; args = args.Substring((arguments[0].Length == args.Length) ? arguments[0].Length : arguments[0].Length + 1); } } Stopwatch sw = new Stopwatch(); sw.Start(); EventContext context = new EventContext(); context.commandHandler = c; context.arguments = args; context.message = e; Log.Message($"Starting Command!!! {Name}"); if (await TryProcessCommand(targetCommand, context)) { await eventSystem.OnCommandDone(e, this); TimesUsed++; Log.Message($"{Name} called from {e.Guild.Name} in {sw.ElapsedMilliseconds}ms"); } sw.Stop(); Log.Message($"Leaving {Name}"); }
internal static unsafe extern Result vkResetCommandPool(Device device, CommandPool commandPool, CommandPoolResetFlags flags);
public CommandSystem() { mLockBuffer = false; mShowDebugInfo = true; mCommandPool = new CommandPool(); }
public unsafe void DestroyCommandPool(CommandPool commandPool, AllocationCallbacks* allocator = null) { vkDestroyCommandPool(this, commandPool, allocator); }
void generateCubemaps(Queue staggingQ, CommandPool cmdPool) { irradianceCube = generateCubeMap(staggingQ, cmdPool, CBTarget.IRRADIANCE); prefilterCube = generateCubeMap(staggingQ, cmdPool, CBTarget.PREFILTEREDENV); }
internal static unsafe extern void vkFreeCommandBuffers(Device device, CommandPool commandPool, uint commandBufferCount, CommandBuffer* commandBuffers);
internal static unsafe extern Result vkCreateCommandPool(Device device, CommandPoolCreateInfo* createInfo, AllocationCallbacks* allocator, CommandPool* commandPool);
public unsafe void ResetCommandPool(CommandPool commandPool, CommandPoolResetFlags flags) { vkResetCommandPool(this, commandPool, flags).CheckError(); }
public unsafe void FreeCommandBuffers(CommandPool commandPool, uint commandBufferCount, CommandBuffer* commandBuffers) { vkFreeCommandBuffers(this, commandPool, commandBufferCount, commandBuffers); }
protected bool mTraceCommand; // 是否追踪命令的来源 public CommandSystem() { mBufferLock = new ThreadLock(); mTraceCommand = false; mCommandPool = new CommandPool(); }
public abstract void TrimCommandPool([Count(Count = 0)] Device device, [Count(Count = 0)] CommandPool commandPool, [Count(Count = 0)] uint flags);
/// <summary> /// Trim a command pool. /// <para> /// Trimming a command pool recycles unused memory from the command pool back to the system. /// </para> /// <para>Command buffers allocated from the pool are not affected by the command.</para> /// </summary> /// <param name="commandPool">The command pool to trim.</param> public static void TrimKhr(this CommandPool commandPool) { vkTrimCommandPoolKHR(commandPool.Parent, commandPool, 0); }
public partial void TrimCommandPool([Count(Count = 0)] Device device, [Count(Count = 0)] CommandPool commandPool, [Count(Count = 0)] uint flags);
public ICommandEvent On(string args, ProcessCommandDelegate command) { CommandPool.Add(args, command); return(this); }
// TODO: clean up public async Task Check(EventContext e, string identifier = "") { string command = e.message.Content.Substring(identifier.Length).Split(' ')[0]; string args = ""; List <string> arguments = new List <string>(); if (e.message.Content.Split(' ').Length > 1) { args = e.message.Content.Substring(e.message.Content.Split(' ')[0].Length + 1); arguments.AddRange(args.Split(' ')); arguments = arguments .Where(x => !string.IsNullOrWhiteSpace(x)) .ToList(); } if (Module != null) { if (Module.Nsfw && !(await e.message.GetChannelAsync()).IsNsfw) { throw new ChannelNotNsfwException(); } } if (IsOnCooldown(e.message.Author.Id)) { Log.WarningAt(Name, " is on cooldown"); return; } if (GuildPermissions.Count > 0) { foreach (GuildPermission g in GuildPermissions) { if (!(await(await e.message.GetChannelAsync() as IDiscordGuildChannel).GetPermissionsAsync(e.message.Author as IDiscordGuildUser)).HasFlag(g)) { await(await e.message.GetChannelAsync()).SendMessageAsync($"Please give me the guild permission `{g}` to use this command."); return; } } } ProcessCommandDelegate targetCommand = ProcessCommand; if (arguments.Count > 0) { if (CommandPool.ContainsKey(arguments[0])) { targetCommand = CommandPool[arguments[0]]; args = args.Substring((arguments[0].Length == args.Length) ? arguments[0].Length : arguments[0].Length + 1); } } if (e.Channel is IDiscordGuildChannel c) { e.Guild = await c.GetGuildAsync(); } e.Arguments = new Args(args); await targetCommand(e); }
internal static unsafe extern void vkDestroyCommandPool(Device device, CommandPool commandPool, AllocationCallbacks *Allocator);
private void CreateCommandPool() { QueueFamilyIndices queueFamilies = FindQueueFamilies(this.physicalDevice); this.commandPool = device.CreateCommandPool(queueFamilies.GraphicsFamily.Value); }
internal static unsafe extern void vkFreeCommandBuffers(Device device, CommandPool commandPool, UInt32 commandBufferCount, IntPtr pCommandBuffers);
private static T AcquireCommand <T>() where T : Command, new() { return(CommandPool <T> .Acquire()); }
private void TearDown() { device.WaitIdle(); this.renderFinishedSemaphore.Dispose(); this.renderFinishedSemaphore = null; this.imageAvailableSemaphore.Dispose(); this.imageAvailableSemaphore = null; this.descriptorPool.Dispose(); this.descriptorPool = null; this.descriptorSet = null; this.uniformBufferMemory.Free(); this.uniformBufferMemory = null; this.uniformBuffer.Dispose(); this.uniformBuffer = null; this.uniformStagingBufferMemory.Free(); this.uniformStagingBufferMemory = null; this.uniformStagingBuffer.Dispose(); this.uniformStagingBuffer = null; this.indexBufferMemory.Free(); this.indexBufferMemory = null; this.indexBuffer.Dispose(); this.indexBuffer = null; this.vertexBufferMemory.Free(); this.vertexBufferMemory = null; this.vertexBuffer.Dispose(); this.vertexBuffer = null; this.commandPool.Dispose(); this.commandPool = null; this.commandBuffers = null; foreach (var frameBuffer in this.frameBuffers) { frameBuffer.Dispose(); } this.frameBuffers = null; this.fragShader.Dispose(); this.fragShader = null; this.vertShader.Dispose(); this.vertShader = null; this.pipeline.Dispose(); this.pipeline = null; this.pipelineLayout.Dispose(); this.pipelineLayout = null; foreach (var imageView in this.swapChainImageViews) { imageView.Dispose(); } this.swapChainImageViews = null; this.descriptorSetLayout.Dispose(); this.descriptorSetLayout = null; this.renderPass.Dispose(); this.renderPass = null; this.swapChain.Dispose(); this.swapChain = null; this.device.Dispose(); this.device = null; this.surface.Dispose(); this.surface = null; this.instance.Dispose(); this.instance = null; }
private static void ReleaseCommand <T>(T command) where T : Command, new() { CommandPool <T> .Release(command); }
public Context(GameWindow window) { Window = window; Instance = ToDispose(VKHelper.CreateInstance()); DebugReportCallback = ToDispose(VKHelper.CreateDebugReportCallback(Instance)); Surface = ToDispose(VKHelper.CreateSurface(Instance, Window.Handle)); foreach (PhysicalDevice physicalDevice in Instance.EnumeratePhysicalDevices()) { QueueFamilyProperties[] queueFamilyProperties = physicalDevice.GetQueueFamilyProperties(); for (int i = 0; i < queueFamilyProperties.Length; i++) { if (queueFamilyProperties[i].QueueFlags.HasFlag(Queues.Graphics)) { if (GraphicsQueueFamilyIndex == -1) { GraphicsQueueFamilyIndex = i; } if (ComputeQueueFamilyIndex == -1) { ComputeQueueFamilyIndex = i; } if (physicalDevice.GetSurfaceSupportKhr(i, Surface) && VKHelper.GetPresentationSupport(physicalDevice, i)) { PresentQueueFamilyIndex = i; } if (GraphicsQueueFamilyIndex != -1 && ComputeQueueFamilyIndex != -1 && PresentQueueFamilyIndex != -1) { PhysicalDevice = physicalDevice; break; } } } if (PhysicalDevice != null) { break; } } if (PhysicalDevice == null) { throw new InvalidOperationException("No suitable physical device found."); } GenerateDepthStencilFormat(); // Store memory properties of the physical device. MemoryProperties = PhysicalDevice.GetMemoryProperties(); Features = PhysicalDevice.GetFeatures(); Properties = PhysicalDevice.GetProperties(); // Create a logical device. bool sameGraphicsAndPresent = GraphicsQueueFamilyIndex == PresentQueueFamilyIndex; var queueCreateInfos = new DeviceQueueCreateInfo[sameGraphicsAndPresent ? 1 : 2]; queueCreateInfos[0] = new DeviceQueueCreateInfo(GraphicsQueueFamilyIndex, 1, 1.0f); if (!sameGraphicsAndPresent) { queueCreateInfos[1] = new DeviceQueueCreateInfo(PresentQueueFamilyIndex, 1, 1.0f); } var deviceCreateInfo = new DeviceCreateInfo( queueCreateInfos, new[] { Constant.DeviceExtension.KhrSwapchain, Constant.DeviceExtension.KhrMaintenance1 }, Features); Device = PhysicalDevice.CreateDevice(deviceCreateInfo); // Get queue(s). GraphicsQueue = Device.GetQueue(GraphicsQueueFamilyIndex); ComputeQueue = ComputeQueueFamilyIndex == GraphicsQueueFamilyIndex ? GraphicsQueue : Device.GetQueue(ComputeQueueFamilyIndex); PresentQueue = PresentQueueFamilyIndex == GraphicsQueueFamilyIndex ? GraphicsQueue : Device.GetQueue(PresentQueueFamilyIndex); Content = new Content(this); GraphicsCommandPool = ToDispose(Device.CreateCommandPool(new CommandPoolCreateInfo(GraphicsQueueFamilyIndex, CommandPoolCreateFlags.ResetCommandBuffer))); ComputeCommandPool = ToDispose(Device.CreateCommandPool(new CommandPoolCreateInfo(ComputeQueueFamilyIndex))); Graphics = ToDispose(new Graphics(this)); Build(); }
public PooledCommand(CommandPool pool) { this.pool = pool; }
public void Free() { using (CommandPool.AllocateBuffers(new CommandBufferAllocateInfo(CommandBufferLevel.Primary, 1))[0]) { } CommandBuffer[] buffers = CommandPool.AllocateBuffers(new CommandBufferAllocateInfo(CommandBufferLevel.Primary, 1)); CommandPool.FreeBuffers(buffers); }
public void SetCommandPool(CommandPool pool) { this.pool = pool; }
public override void Dispose() { CommandPool.Dispose(); base.Dispose(); }
internal static unsafe extern void vkDestroyCommandPool(Device device, CommandPool commandPool, AllocationCallbacks* allocator);
protected virtual void ReleaseUnmanagedResources() { // Command buffers first CommandPool.DestroyCommandPool(Device, null); }
public HelpCommandModel(CommandPool commands) { this.commands = commands ?? throw new ArgumentNullException(nameof(commands)); }
public void RemoveCommandPool() { this.pool = null; }