Пример #1
0
        private void InitializeVulkan(string applicationName, uint applicationVersion)
        {
            Console.WriteLine("Initializing Vulkan");
#if VALIDITION
            DebugUtilsMessengerCreateInfoEXT GetDebugMessenger(void *pNext)
            {
                return(new DebugUtilsMessengerCreateInfoEXT(
                           messageSeverity: DebugUtilsMessageSeverityFlagsEXT.DebugUtilsMessageSeverityVerboseBitExt |
                           DebugUtilsMessageSeverityFlagsEXT.DebugUtilsMessageSeverityInfoBitExt |
                           DebugUtilsMessageSeverityFlagsEXT.DebugUtilsMessageSeverityWarningBitExt |
                           DebugUtilsMessageSeverityFlagsEXT.DebugUtilsMessageSeverityErrorBitExt,
                           messageType: DebugUtilsMessageTypeFlagsEXT.DebugUtilsMessageTypeGeneralBitExt |
                           DebugUtilsMessageTypeFlagsEXT.DebugUtilsMessageTypePerformanceBitExt |
                           DebugUtilsMessageTypeFlagsEXT.DebugUtilsMessageTypeValidationBitExt,
                           pfnUserCallback: new PfnDebugUtilsMessengerCallbackEXT(DebugCallback), pNext: pNext));
            }
#endif

            _vk = Vk.GetApi();

            const uint   engineVersion = 1;
            const string engineName    = "Videre";

            var instanceLayers     = new List <string>();
            var instanceExtensions = new List <string>();

            var pApplicationName = SilkMarshal.StringToPtr(applicationName);
            var pEngineName      = SilkMarshal.StringToPtr(engineName);
            var applicationInfo  = new ApplicationInfo(pApplicationName: (byte *)pApplicationName,
                                                       applicationVersion: applicationVersion, pEngineName: (byte *)pEngineName, engineVersion: engineVersion,
                                                       apiVersion: new Version32(1, 1, 0));

            Version32 apiVersion = default;
            _vk.EnumerateInstanceVersion((uint *)&apiVersion);
            Console.WriteLine($"Instance Version: {apiVersion.Major}.{apiVersion.Minor}.{apiVersion.Patch}");

            void *instancepNext = default;

            // instanceExtensions.Add(KhrSurface.ExtensionName);
            instanceExtensions.AddRange(SilkMarshal.PtrToStringArray((nint)View.VkSurface.GetRequiredExtensions(out var requiredExtensionsCount), (int)requiredExtensionsCount));
            instanceExtensions.Add(ExtDebugUtils.ExtensionName);

            Console.WriteLine($"Creating Instance with {instanceExtensions.Count} extensions");
            VerifyInstanceExtensionsAvailable(_vk, instanceExtensions);

            var ppEnabledLayers     = instanceLayers.Count > 0 ? (byte **)SilkMarshal.StringArrayToPtr(instanceLayers) : null;
            var ppEnabledExtensions = instanceExtensions.Count > 0 ? (byte **)SilkMarshal.StringArrayToPtr(instanceExtensions) : null;

            _vk.CreateInstance(
                new InstanceCreateInfo(pApplicationInfo: &applicationInfo,
                                       enabledLayerCount: (uint)instanceLayers.Count, ppEnabledLayerNames: ppEnabledLayers,
                                       enabledExtensionCount: (uint)instanceExtensions.Count,
                                       ppEnabledExtensionNames: ppEnabledExtensions, pNext: instancepNext), _allocationCallbacks.AllocationCallbacks, out _instance)
            .ThrowCode();
            SilkMarshal.Free((nint)ppEnabledLayers);
            SilkMarshal.Free((nint)ppEnabledExtensions);

            _vk.CurrentInstance = _instance;

            if (!_vk.TryGetInstanceExtension(_instance, out _khrSurface))
            {
                Console.WriteLine($"Could not load {KhrSurface.ExtensionName}");
            }

            _vk.TryGetInstanceExtension(_instance, out _debugUtils);

            Console.WriteLine("Creating Surface");
            _surface = View.VkSurface.Create(_instance.ToHandle(), (AllocationCallbacks *)null).ToSurface();

            uint deviceCount = 0;
            _vk.EnumeratePhysicalDevices(_instance, ref deviceCount, null).ThrowCode();
            var devices = (PhysicalDevice *)SilkMarshal.Allocate((int)(deviceCount * sizeof(PhysicalDevice)));
            _vk.EnumeratePhysicalDevices(_instance, ref deviceCount, devices).ThrowCode();
            Console.WriteLine($"Found {deviceCount} devices");

            Console.WriteLine("Creating Device");
            // TODO: actually somehow reasonably find the best device.
            for (int i = 0; i < deviceCount; i++)
            {
                var physicalDevice = devices[i];
                _physicalDeviceFeatures = _vk.GetPhysicalDeviceFeature(physicalDevice);

                uint presentModeCount = 0;
                _khrSurface.GetPhysicalDeviceSurfacePresentModes(physicalDevice, _surface, ref presentModeCount, null).ThrowCode();
                if (presentModeCount <= 0)
                {
                    continue;
                }

                var presentModes = (PresentModeKHR *)SilkMarshal.Allocate((int)(presentModeCount * sizeof(PresentModeKHR)));
                _khrSurface.GetPhysicalDeviceSurfacePresentModes(physicalDevice, _surface, ref presentModeCount, presentModes).ThrowCode();

                _presentMode         = PresentModeKHR.PresentModeFifoKhr;
                View.FramesPerSecond = -1;
                for (int j = 0; j < presentModeCount; j++)
                {
                    if (presentModes[j] == PresentModeKHR.PresentModeMailboxKhr)
                    {
                        _presentMode         = PresentModeKHR.PresentModeMailboxKhr;
                        View.FramesPerSecond = -1;
                        break;
                    }
                }

                SilkMarshal.Free((nint)presentModes);

                uint surfaceFormatCount = 0;
                _khrSurface.GetPhysicalDeviceSurfaceFormats(physicalDevice, _surface, ref surfaceFormatCount, null).ThrowCode();
                var surfaceFormats = (SurfaceFormatKHR *)SilkMarshal.Allocate((int)(surfaceFormatCount * sizeof(SurfaceFormatKHR)));
                _khrSurface.GetPhysicalDeviceSurfaceFormats(physicalDevice, _surface, ref surfaceFormatCount, surfaceFormats).ThrowCode();
                int max = int.MinValue;
                SurfaceFormatKHR maxFormat = surfaceFormats[0];
                for (int j = 0; j < surfaceFormatCount; j++)
                {
                    var score = FormatRater.Rate(surfaceFormats[j].Format) + ColorSpaceRater.Rate(surfaceFormats[j].ColorSpace);
                    if (score > max)
                    {
                        max       = score;
                        maxFormat = surfaceFormats[j];
                    }
                }
                SilkMarshal.Free((nint)surfaceFormats);

                _swapchainFormat     = maxFormat.Format;
                _swapchainColorSpace = maxFormat.ColorSpace;
                Console.WriteLine($"Chose Swapchain Properties: {Enum.GetName(typeof(PresentModeKHR), _presentMode)} {Enum.GetName(typeof(Format), _swapchainFormat)} {Enum.GetName(typeof(ColorSpaceKHR), _swapchainColorSpace)}");

                _khrSurface.GetPhysicalDeviceSurfaceCapabilities(physicalDevice, _surface, out var surfaceCapabilities).ThrowCode();

                uint queueFamilyPropertyCount = 0;
                _vk.GetPhysicalDeviceQueueFamilyProperties(physicalDevice, ref queueFamilyPropertyCount, null);
                var deviceQueueFamilyProperties = (QueueFamilyProperties *)SilkMarshal.Allocate((int)(queueFamilyPropertyCount * sizeof(QueueFamilyProperties)));
                _vk.GetPhysicalDeviceQueueFamilyProperties(physicalDevice, ref queueFamilyPropertyCount, deviceQueueFamilyProperties);

                var queueCreateInfoList = new List <DeviceQueueCreateInfo>();
                var deviceExtensions    = new List <string>();
                var deviceLayers        = new List <string>();

                for (int j = 0; j < queueFamilyPropertyCount; j++)
                {
                    var    queueCount       = deviceQueueFamilyProperties[j].QueueCount;
                    float *pQueuePriorities = stackalloc float[(int)queueCount]; // queue count should generally be 1
                    for (int k = 0; k < queueCount; k++)
                    {
                        pQueuePriorities[k] = 1.0f;
                    }

                    queueCreateInfoList.Add(new DeviceQueueCreateInfo(queueFamilyIndex: (uint)j, queueCount: queueCount, pQueuePriorities: pQueuePriorities));
                }

                deviceExtensions.Add(KhrSwapchain.ExtensionName);
                // deviceExtensions.Add(KhrSynchronization2.ExtensionName);
                // deviceExtensions.Add(ExtBufferDeviceAddress.ExtensionName);

                var features = new PhysicalDeviceFeatures();
                features.ShaderInt64 = true;

                void *devicePNext = null;

//                 var physicalDeviceDescriptorIndexingFeaturesExt = new PhysicalDeviceDescriptorIndexingFeaturesEXT(
//                     descriptorBindingSampledImageUpdateAfterBind: true,
//                     descriptorBindingStorageBufferUpdateAfterBind: true,
//                     descriptorBindingStorageImageUpdateAfterBind: true,
//                     descriptorBindingUniformBufferUpdateAfterBind: true,
//                     descriptorBindingStorageTexelBufferUpdateAfterBind: true,
//                     descriptorBindingUniformTexelBufferUpdateAfterBind: true,
//                     descriptorBindingUpdateUnusedWhilePending: true,
//                     runtimeDescriptorArray: true,
//                     pNext: devicePNext);
//                 devicePNext = &physicalDeviceDescriptorIndexingFeaturesExt;
//
                var physicalDeviceBufferDeviceAddressFeatures = new PhysicalDeviceBufferDeviceAddressFeatures(bufferDeviceAddress: true,
#if DEBUG
                                                                                                              bufferDeviceAddressCaptureReplay: true,
#endif
                                                                                                              pNext: devicePNext);
                devicePNext = &physicalDeviceBufferDeviceAddressFeatures;

//                 var version12 = new PhysicalDeviceVulkan12Features(bufferDeviceAddress: true,
// #if DEBUG
//                     bufferDeviceAddressCaptureReplay: true,
// #endif
//                    descriptorBindingSampledImageUpdateAfterBind: true,
//                    descriptorBindingStorageBufferUpdateAfterBind: true,
//                    descriptorBindingStorageImageUpdateAfterBind: true,
//                    descriptorBindingUniformBufferUpdateAfterBind: true,
//                    descriptorBindingStorageTexelBufferUpdateAfterBind: true,
//                    descriptorBindingUniformTexelBufferUpdateAfterBind: true,
//                    descriptorBindingUpdateUnusedWhilePending: true,
//                    runtimeDescriptorArray: true,
//                     pNext: devicePNext);
//                 devicePNext = &version12;

                var queueCreateInfos = queueCreateInfoList.Distinct().ToArray();
                queueCreateInfoList = null;

                VerifyDeviceExtensionsAvailable(_vk, devices[i], deviceExtensions, ref deviceLayers);

                _physicalDevice = devices[i];

                Console.WriteLine("Creating Logical Device");
                var ppDeviceExtensions = deviceExtensions.Count > 0 ? (byte **)SilkMarshal.StringArrayToPtr(deviceExtensions) : null;
                var ppDeviceLayers     = deviceLayers.Count > 0 ? (byte **)SilkMarshal.StringArrayToPtr(deviceLayers) : null;

                fixed(DeviceQueueCreateInfo *pQueueCreateInfos = queueCreateInfos)
                _vk.CreateDevice(physicalDevice,
                                 new DeviceCreateInfo(queueCreateInfoCount: (uint)queueCreateInfos.Length,
                                                      pQueueCreateInfos: pQueueCreateInfos,
                                                      enabledExtensionCount: (uint)deviceExtensions.Count,
                                                      enabledLayerCount: (uint)deviceLayers.Count,
                                                      ppEnabledExtensionNames: ppDeviceExtensions,
                                                      ppEnabledLayerNames: ppDeviceLayers, pEnabledFeatures: &features, pNext: devicePNext), null,
                                 out _logicalDevice)
                .ThrowCode();

                _vk.CurrentDevice = _logicalDevice;

                if (!_vk.TryGetDeviceExtension(_instance, _logicalDevice, out _khrSwapchain))
                {
                    Console.WriteLine($"Could not load {KhrSwapchain.ExtensionName}!");
                }

                _queueManager = new(_vk, _khrSurface, _instance, _physicalDevice, _logicalDevice, _surface, new Span <QueueFamilyProperties>(deviceQueueFamilyProperties, (int)queueFamilyPropertyCount));
                Console.WriteLine($"{_queueManager.QueueCount} queues found");

                SilkMarshal.Free((nint)ppDeviceExtensions);
                SilkMarshal.Free((nint)ppDeviceLayers);
                SilkMarshal.Free((nint)deviceQueueFamilyProperties);
                break;
            }
            SilkMarshal.Free((nint)devices);
            Console.WriteLine("Initialized Vulkan");
        }
Пример #2
0
        public unsafe VulkanRenderer(UserSettings userSettings, Window window, IScene scene, CameraInitialState cameraInitialState, ILogger logger, bool enableDebugLogging)
        {
            _userSettings = userSettings;
            _window       = window;

            _api = new Api(enableDebugLogging, logger);

            _presentMode = _userSettings.VSync ? PresentModeKHR.PresentModeFifoKhr : PresentModeKHR.PresentModeImmediateKhr;

            _api.Instance = new Instance(_api, _window, new Version32(1, 2, 0));
            _surface      = new Surface(_api, _window, _api.Instance);

            // Find the vulkan device we want
            var physicalDevice = _api.Instance.PhysicalDevices.Where(d =>
            {
                _api.Vk.GetPhysicalDeviceFeatures(d, out var deviceFeatures);

                if (deviceFeatures.GeometryShader == false)
                {
                    return(false);
                }

                var queueFamilies = Enumerate.Get <PhysicalDevice, QueueFamilyProperties>(d, (device, count, values) =>
                                                                                          _api.Vk.GetPhysicalDeviceQueueFamilyProperties(device, (uint *)count, (QueueFamilyProperties *)values));

                for (var i = 0; i < queueFamilies.Count; i++)
                {
                    if (queueFamilies[i].QueueCount > 0 && queueFamilies[i].QueueFlags.HasFlag(QueueFlags.QueueGraphicsBit))
                    {
                        return(true);
                    }
                }

                return(false);
            }).FirstOrDefault();

            if (physicalDevice.Handle == 0)
            {
                throw new Exception($"{nameof(VulkanRenderer)}: Could not find a suitable graphics device.");
            }

            var deviceProps = new PhysicalDeviceProperties2();

            deviceProps.SType = StructureType.PhysicalDeviceProperties2;

            _api.Vk.GetPhysicalDeviceProperties2(physicalDevice, &deviceProps);

            _api.Logger.Debug($"{nameof(VulkanRenderer)}: Setting physical device: {deviceProps.Properties.DeviceID} ({Marshal.PtrToStringAnsi((nint)deviceProps.Properties.DeviceName)})");

            // Opt-in into mandatory device features.
            var shaderClockFeatures = new PhysicalDeviceShaderClockFeaturesKHR();

            shaderClockFeatures.SType = StructureType.PhysicalDeviceShaderClockFeaturesKhr;
            shaderClockFeatures.PNext = null;
            shaderClockFeatures.ShaderSubgroupClock = true;

            var deviceFeatures = new PhysicalDeviceFeatures();

            deviceFeatures.FillModeNonSolid  = true;
            deviceFeatures.SamplerAnisotropy = true;
            deviceFeatures.ShaderInt64       = true;

            // Required device features.
            var bufferDeviceAddressFeatures = new PhysicalDeviceBufferDeviceAddressFeatures();

            bufferDeviceAddressFeatures.SType = StructureType.PhysicalDeviceBufferDeviceAddressFeatures;
            bufferDeviceAddressFeatures.PNext = &shaderClockFeatures;
            bufferDeviceAddressFeatures.BufferDeviceAddress = true;

            var indexingFeatures = new PhysicalDeviceDescriptorIndexingFeatures();

            indexingFeatures.SType = StructureType.PhysicalDeviceDescriptorIndexingFeatures;
            indexingFeatures.PNext = &bufferDeviceAddressFeatures;
            indexingFeatures.RuntimeDescriptorArray = true;
            indexingFeatures.ShaderSampledImageArrayNonUniformIndexing = true;

            var accelerationStructureFeatures = new PhysicalDeviceAccelerationStructureFeaturesKHR();

            accelerationStructureFeatures.SType = StructureType.PhysicalDeviceAccelerationStructureFeaturesKhr;
            accelerationStructureFeatures.PNext = &indexingFeatures;
            accelerationStructureFeatures.AccelerationStructure = true;

            var rayTracingFeatures = new PhysicalDeviceRayTracingPipelineFeaturesKHR();

            rayTracingFeatures.SType = StructureType.PhysicalDeviceRayTracingPipelineFeaturesKhr;
            rayTracingFeatures.PNext = &accelerationStructureFeatures;
            rayTracingFeatures.RayTracingPipeline = true;

            _api.Device = new Device(_api, physicalDevice, _surface, deviceFeatures, Unsafe.AsPointer(ref rayTracingFeatures));

            // Now that we have an instance and a device, load all of the extentions we need.
            _api.InitializeExtensions();

            _commandPool = new CommandPool(_api, _api.Device.GraphicsFamilyIndex, true);

            _rayTracingProperties = new RayTracingProperties(_api);

            // Load the scene, and create the swap chain / command buffers
            LoadScene(scene, cameraInitialState);

            _currentFrame = 0;

            _api.Device.WaitIdle();
        }