private void CreateInstance()
        {
            AvailableInstanceExtensions = Instance.EnumerateExtensionProperties();
            string[] selectExtensions = new[] { Constant.InstanceExtension.ExtDebugReport }
            .Where(AvailableInstanceExtensions.Contains)
            .ToArray();

            // Specify standard validation layers.
            var createInfo = new InstanceCreateInfo
            {
                EnabledLayerNames     = new[] { Constant.InstanceLayer.LunarGStandardValidation },
                EnabledExtensionNames = selectExtensions
            };

            Instance = new Instance(createInfo);

            // Attach debug callback and fail any test on any error or warning from validation layers.
            var debugReportCreateInfo = new DebugReportCallbackCreateInfoExt(
                DebugReportFlagsExt.Error |
                DebugReportFlagsExt.Warning |
                DebugReportFlagsExt.PerformanceWarning,
                args =>
            {
                if ((args.Flags & (DebugReportFlagsExt.Error |
                                   DebugReportFlagsExt.PerformanceWarning |
                                   DebugReportFlagsExt.Warning)) > 0)
                {
                    Assert.True(false, $"Validation layer error/warning:\n\n[{args.Flags}] {args.Message}");
                }
                return(false);
            }
                );

            _debugReportCallback = Instance.CreateDebugReportCallbackExt(debugReportCreateInfo);
        }
Beispiel #2
0
        public bool InitVulkan(string appName, VER appVer, bool bDebug)
        {
            Glfw.Init();

            mInstance = new Instance(appName, EngineName,
                                     appVer, mEngineVer, mAPIVer, bDebug);

            if (!mInstance.IsValid())
            {
                Misc.SafeInvoke(eErrorSpam, "Couldn't create Vulkan instance.");
                return(false);
            }

            if (bDebug)
            {
                //set up debug callback to talk to validation stuff
                DebugReportCallbackCreateInfoExt drcbci = new DebugReportCallbackCreateInfoExt(
                    DebugReportFlagsExt.All, DebugReportCallback, IntPtr.Zero);
                mDebugCB = mInstance.AttachDebugCallback(drcbci);
            }

            return(true);
        }
Beispiel #3
0
        public Host(
            Platform.INativeApp nativeApp,
            string appName,
            int appVersion,
            Logger logger = null)
        {
            if (nativeApp == null)
            {
                throw new ArgumentNullException(nameof(nativeApp));
            }
            this.nativeApp  = nativeApp;
            this.appName    = appName;
            this.appVersion = appVersion;
            this.logger     = logger;

            availableLayers = Instance.EnumerateLayerProperties();
            logger?.LogList(nameof(Host), "Available layers:", availableLayers);
            availbleExtensions = Instance.EnumerateExtensionProperties();
            logger?.LogList(nameof(Host), "Available extensions:", availbleExtensions);

            //Verify that all the required layers are available on this host
            var layersToEnable = new List <string>(GetRequiredLayers(nativeApp.SurfaceType));

            for (int i = 0; i < layersToEnable.Count; i++)
            {
                if (!IsLayerAvailable(layersToEnable[i]))
                {
                    throw new Exception(
                              $"[{nameof(Host)}] Required layer '{layersToEnable[i]}' is not available");
                }
            }

            //Verify that all the required extensions are available on this host
            var extensionsToEnable = new List <string>(GetRequiredExtensions(nativeApp.SurfaceType));

            for (int i = 0; i < extensionsToEnable.Count; i++)
            {
                if (!IsExtensionAvailable(extensionsToEnable[i]))
                {
                    throw new Exception(
                              $"[{nameof(Host)}] Required extension '{extensionsToEnable[i]}' is not available");
                }
            }

            //Add any optional layers IF its supported by this host
            string[] optionalLayers = GetOptionalLayers(nativeApp.SurfaceType);
            for (int i = 0; i < optionalLayers.Length; i++)
            {
                if (IsLayerAvailable(optionalLayers[i]))
                {
                    layersToEnable.Add(optionalLayers[i]);
                }
            }

            //Add any optional extensions IF its supported by this host
            string[] optionalExtensions = GetOptionalExtensions(nativeApp.SurfaceType);
            for (int i = 0; i < optionalExtensions.Length; i++)
            {
                if (IsExtensionAvailable(optionalExtensions[i]))
                {
                    extensionsToEnable.Add(optionalExtensions[i]);
                }
            }

            InstanceCreateInfo createInfo = new InstanceCreateInfo(
                appInfo: new ApplicationInfo(
                    applicationName: appName,
                    applicationVersion: appVersion,
                    engineName: Info.NAME,
                    engineVersion: Info.VERSION,
                    apiVersion: new VulkanCore.Version(major: 1, minor: 0, patch: 69)
                    ),
                enabledLayerNames: layersToEnable.ToArray(),
                enabledExtensionNames: extensionsToEnable.ToArray()
                );

            instance = new Instance(createInfo);

            logger?.Log(nameof(Host), "Created instance");
            logger?.LogList(nameof(Host), "Enabled layers:", layersToEnable);
            logger?.LogList(nameof(Host), "Enabled extensions:", extensionsToEnable);

            #if DEBUG
            if (extensionsToEnable.Contains("VK_EXT_debug_report"))
            {
                debugCallback = instance.CreateDebugReportCallbackExt(
                    new DebugReportCallbackCreateInfoExt(
                        //We want to handle everthing except for info reports
                        flags: DebugReportFlagsExt.All & ~DebugReportFlagsExt.Information,
                        callback: OnDebugReport));
                logger?.Log(nameof(Host), "Enabled debug callback");
            }
            #else
            debugCallback = null;
            #endif

            //Get all the devices in this host
            PhysicalDevice[] physicalDevices = instance.EnumeratePhysicalDevices();
            hostDevices = new HostDevice[physicalDevices.Length];
            for (int i = 0; i < hostDevices.Length; i++)
            {
                hostDevices[i] = new HostDevice(physicalDevices[i], nativeApp.SurfaceType, logger);
            }
        }
Beispiel #4
0
        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();
        }
Beispiel #5
0
        /// <summary>
        /// Initialize the static part of Graphics
        /// </summary>
        private static void InitializeStatic()
        {
            // Don't do anything if it's already been initialized
            if (InitializedStatic)
            {
                return;
            }
            // Create the Vulkan Instance
            {
                var createInfo = new InstanceCreateInfo();
                // Set application info automatically using assembly info and Vulkan API 1.0.0
                {
                    var entryAssemblyName = Assembly.GetEntryAssembly().GetName();
                    var thisAssemblyName  = typeof(Graphics).Assembly.GetName();
                    createInfo.ApplicationInfo = new ApplicationInfo()
                    {
                        ApiVersion         = new VulkanCore.Version(1, 0, 0),
                        ApplicationName    = entryAssemblyName.Name,
                        ApplicationVersion = new VulkanCore.Version(
                            entryAssemblyName.Version.Major,
                            entryAssemblyName.Version.Minor,
                            entryAssemblyName.Version.Build
                            ),
                        EngineName    = "Wyvern",
                        EngineVersion = new VulkanCore.Version(
                            thisAssemblyName.Version.Major,
                            thisAssemblyName.Version.Minor,
                            thisAssemblyName.Version.Build
                            )
                    };
                }
                // Set the enabled extensions
                createInfo.EnabledExtensionNames = EnabledInstanceExtensions
                                                   .Concat(WyvernWindow.RequiredExtensions)
                                                   .Distinct()
                                                   .ToArray();
                // Set the enabled layers
                var availableLayers = Instance.EnumerateLayerProperties();
                createInfo.EnabledLayerNames = EnabledDebugLayers
                                               .Where(e => {
                    if (availableLayers.Contains(e))
                    {
                        Debug.Info($"Enabled layer {e}", "Graphics");
                        return(true);
                    }
                    return(false);
                })
                                               .Distinct()
                                               .ToArray();
                // Create instance
                Instance = new Instance(createInfo);
            }
            // Create the debug callback
            {
#if DEBUG
                DebugCallback = Instance.CreateDebugReportCallbackExt(new DebugReportCallbackCreateInfoExt(
                                                                          DebugReportFlagsExt.All, OnDebugReport
                                                                          ));
#endif
            }
            // Flag that we are now initialized
            InitializedStatic = true;
        }
Beispiel #6
0
 internal static unsafe extern void vkDestroyDebugReportCallbackEXT(Instance instance, DebugReportCallbackExt callback, AllocationCallbacks *Allocator);