bool Tutorial01::CreateInstance() {
    VkApplicationInfo application_info = {
      VK_STRUCTURE_TYPE_APPLICATION_INFO,             // VkStructureType            sType
      nullptr,                                        // const void                *pNext
      "API without Secrets: Introduction to Vulkan",  // const char                *pApplicationName
      VK_MAKE_VERSION( 1, 0, 0 ),                     // uint32_t                   applicationVersion
      "Vulkan Tutorial by Intel",                     // const char                *pEngineName
      VK_MAKE_VERSION( 1, 0, 0 ),                     // uint32_t                   engineVersion
      VK_MAKE_VERSION( 1, 0, 0 )                      // uint32_t                   apiVersion
    };

    VkInstanceCreateInfo instance_create_info = {
      VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,         // VkStructureType            sType
      nullptr,                                        // const void*                pNext
      0,                                              // VkInstanceCreateFlags      flags
      &application_info,                              // const VkApplicationInfo   *pApplicationInfo
      0,                                              // uint32_t                   enabledLayerCount
      nullptr,                                        // const char * const        *ppEnabledLayerNames
      0,                                              // uint32_t                   enabledExtensionCount
      nullptr                                         // const char * const        *ppEnabledExtensionNames
    };

    if( vkCreateInstance( &instance_create_info, nullptr, &Vulkan.Instance ) != VK_SUCCESS ) {
      std::cout << "Could not create Vulkan instance!" << std::endl;
      return false;
    }
    return true;
  }
示例#2
0
vku::ApplicationInstance vku::CreateApplicationInstance(m1::game_platform const &gamePlatform)
{
    vku::InstanceCreateInfo const instance_create_info =
        vku::CreateInstanceCreateInfo(// applicationInfo
                                      {
                                          gamePlatform.get_name().c_str(), // pApplicationName
                                          VK_MAKE_VERSION(0, 0, 0),        // applicationVersion
                                          "m1",                            // pEngineName
                                          VK_MAKE_VERSION(0, 0, 0),        // engineVersion
                                          VK_MAKE_VERSION(0, 0, 0),        // apiVersion
                                      },
                                      // requiredLayers
                                      {},
                                      // allowedLayers
                                      {"VK_LAYER_LUNARG_standard_validation"},
                                      // requiredExtensions
                                      {
                                          VK_KHR_SURFACE_EXTENSION_NAME,
                                          GetSurfaceExtensionName(gamePlatform),
                                      },
                                      // allowedExtensions
                                      {});

    WsiInstance instance(CreateInstance(instance_create_info));
    VkSurfaceKHR const surface = CreateSurfaceKHR(instance, gamePlatform);

    return ApplicationInstance(std::move(instance),
                               surface);
}
    void createInstance() {
        if (enableValidationLayers && !checkValidationLayerSupport()) {
            throw std::runtime_error("validation layers requested, but not available!");
        }

        VkApplicationInfo appInfo = {};
        appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
        appInfo.pApplicationName = "Hello Triangle";
        appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
        appInfo.pEngineName = "No Engine";
        appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);
        appInfo.apiVersion = VK_API_VERSION_1_0;

        VkInstanceCreateInfo createInfo = {};
        createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
        createInfo.pApplicationInfo = &appInfo;

        auto extensions = getRequiredExtensions();
        createInfo.enabledExtensionCount = extensions.size();
        createInfo.ppEnabledExtensionNames = extensions.data();

        if (enableValidationLayers) {
            createInfo.enabledLayerCount = validationLayers.size();
            createInfo.ppEnabledLayerNames = validationLayers.data();
        } else {
            createInfo.enabledLayerCount = 0;
        }

        if (vkCreateInstance(&createInfo, nullptr, &instance) != VK_SUCCESS) {
            throw std::runtime_error("failed to create instance!");
        }
    }
示例#4
0
void VContext::_initInstance() {
    vk::ApplicationInfo applicationInfo;
    {
        applicationInfo.apiVersion = VK_API_VERSION_1_0;
        applicationInfo.applicationVersion = VK_MAKE_VERSION(0,1,0);
        applicationInfo.engineVersion = VK_MAKE_VERSION(0,1,0);
        applicationInfo.pApplicationName = "app";
        applicationInfo.pEngineName = "engine";
    };

    std::vector<vk::ExtensionProperties> extensions;
    std::vector<const char*> extensionNames;
    {
        uint32_t count = 0;
        vk::enumerateInstanceExtensionProperties(nullptr,&count, nullptr);
        extensions.resize(count);
        vk::enumerateInstanceExtensionProperties(nullptr,&count, extensions.data());
        extensionNames.resize(extensions.size());
        for(auto i = 0;i<extensionNames.size();i++){
            extensionNames[i] = extensions[i].extensionName;
        }
    }

    std::vector<const char*> layers = {"VK_LAYER_LUNARG_standard_validation"};

    vk::InstanceCreateInfo createInfo;
    {
        createInfo.pApplicationInfo = &applicationInfo;
        createInfo.enabledExtensionCount = extensions.size();
        createInfo.ppEnabledExtensionNames = extensionNames.data();
        createInfo.enabledLayerCount = layers.size();
        createInfo.ppEnabledLayerNames = layers.data();
    };
    instance = vk::createInstance(createInfo);
}
  bool VulkanCommon::CreateInstance() {
    uint32_t extensions_count = 0;
    if( (vkEnumerateInstanceExtensionProperties( nullptr, &extensions_count, nullptr ) != VK_SUCCESS) ||
        (extensions_count == 0) ) {
      std::cout << "Error occurred during instance extensions enumeration!" << std::endl;
      return false;
    }

    std::vector<VkExtensionProperties> available_extensions( extensions_count );
    if( vkEnumerateInstanceExtensionProperties( nullptr, &extensions_count, &available_extensions[0] ) != VK_SUCCESS ) {
      std::cout << "Error occurred during instance extensions enumeration!" << std::endl;
      return false;
    }

    std::vector<const char*> extensions = {
      VK_KHR_SURFACE_EXTENSION_NAME,
#if defined(VK_USE_PLATFORM_WIN32_KHR)
      VK_KHR_WIN32_SURFACE_EXTENSION_NAME
#elif defined(VK_USE_PLATFORM_XCB_KHR)
      VK_KHR_XCB_SURFACE_EXTENSION_NAME
#elif defined(VK_USE_PLATFORM_XLIB_KHR)
      VK_KHR_XLIB_SURFACE_EXTENSION_NAME
#endif
    };

    for( size_t i = 0; i < extensions.size(); ++i ) {
      if( !CheckExtensionAvailability( extensions[i], available_extensions ) ) {
        std::cout << "Could not find instance extension named \"" << extensions[i] << "\"!" << std::endl;
        return false;
      }
    }

    VkApplicationInfo application_info = {
      VK_STRUCTURE_TYPE_APPLICATION_INFO,             // VkStructureType            sType
      nullptr,                                        // const void                *pNext
      "API without Secrets: Introduction to Vulkan",  // const char                *pApplicationName
      VK_MAKE_VERSION( 1, 0, 0 ),                     // uint32_t                   applicationVersion
      "Vulkan Tutorial by Intel",                     // const char                *pEngineName
      VK_MAKE_VERSION( 1, 0, 0 ),                     // uint32_t                   engineVersion
      VK_API_VERSION                                  // uint32_t                   apiVersion
    };

    VkInstanceCreateInfo instance_create_info = {
      VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,         // VkStructureType            sType
      nullptr,                                        // const void                *pNext
      0,                                              // VkInstanceCreateFlags      flags
      &application_info,                              // const VkApplicationInfo   *pApplicationInfo
      0,                                              // uint32_t                   enabledLayerCount
      nullptr,                                        // const char * const        *ppEnabledLayerNames
      static_cast<uint32_t>(extensions.size()),       // uint32_t                   enabledExtensionCount
      &extensions[0]                                  // const char * const        *ppEnabledExtensionNames
    };

    if( vkCreateInstance( &instance_create_info, nullptr, &Vulkan.Instance ) != VK_SUCCESS ) {
      std::cout << "Could not create Vulkan instance!" << std::endl;
      return false;
    }
    return true;
  }
示例#6
0
bool create_instance(const char *app_name) {
    uint32_t extensions_count = 0;
    VK_VERIFY (vkEnumerateInstanceExtensionProperties(nullptr, &extensions_count, nullptr));
    VERIFY_LOG (extensions_count > 0, LOG_TYPE, "Error occurred during instance extensions enumeration!", "");

    std::vector<VkExtensionProperties> available_extensions(extensions_count);
    VK_VERIFY (vkEnumerateInstanceExtensionProperties(nullptr, &extensions_count, &available_extensions[0]));

    std::vector<const char *> extensions = {
        VK_KHR_SURFACE_EXTENSION_NAME,
#ifdef PLATFORM_WINDOWS
        VK_KHR_WIN32_SURFACE_EXTENSION_NAME
#elif PLATFORM_LINUX
        VK_KHR_XCB_SURFACE_EXTENSION_NAME
#endif
    };

    for (size_t i = 0; i < extensions.size(); ++i) {
        VERIFY_LOG(utils::check_extension(extensions[i], available_extensions), LOG_TYPE,
                   "Could not find instance extension named \"%s\"!", extensions[i]);
    }

    VkApplicationInfo application_info = {
        VK_STRUCTURE_TYPE_APPLICATION_INFO,             // VkStructureType            sType
        nullptr,                                        // const void                *pNext
        app_name,                                       // const char                *pApplicationName
        VK_MAKE_VERSION(0, 0, 1),                       // uint32_t                   applicationVersion
        "gladius",                                      // const char                *pEngineName
        VK_MAKE_VERSION(0, 0, 1),                       // uint32_t                   engineVersion
        VK_MAKE_VERSION(1, 0, 21)                       // uint32_t                   apiVersion
    };

    VkInstanceCreateInfo instance_create_info = {
        VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,         // VkStructureType            sType
        nullptr,                                        // const void                *pNext
        0,                                              // VkInstanceCreateFlags      flags
        &application_info,                              // const VkApplicationInfo   *pApplicationInfo
        0,                                              // uint32_t                   enabledLayerCount
        nullptr,                                        // const char * const        *ppEnabledLayerNames
        static_cast<uint32_t>(extensions.size()),      // uint32_t                   enabledExtensionCount
        &extensions[0]                                  // const char * const        *ppEnabledExtensionNames
    };

    VK_VERIFY(vkCreateInstance(&instance_create_info, nullptr, &(vk_globals::instance)));

    GET_INSTANCE_PROC_ADDR(vk_globals::instance, GetPhysicalDeviceSurfaceSupportKHR);
    GET_INSTANCE_PROC_ADDR(vk_globals::instance, GetPhysicalDeviceSurfaceFormatsKHR);

    return true;
}
示例#7
0
				instance::instance() {

					if (Aeon::framework::enableValidationLayers && !checkValidationLayerSupport()) {
						throw Aeon::framework::exception("validation layers requested, but not available!");
					}

					// Setup appinfo
					appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
					appInfo.pApplicationName = "Hello Triangle";
					appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
					appInfo.pEngineName = ENGINE_NAME;
					appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);
					appInfo.apiVersion = VK_API_VERSION_1_0;

					//Setup create info
					createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
					createInfo.pApplicationInfo = &appInfo;

					auto extensions = getRequiredExtensions();
					createInfo.enabledExtensionCount = extensions.size();
					createInfo.ppEnabledExtensionNames = extensions.data();

					if (Aeon::framework::enableValidationLayers) {
						createInfo.enabledLayerCount = Aeon::framework::validationLayers.size();
						createInfo.ppEnabledLayerNames = Aeon::framework::validationLayers.data();
					}
					else {
						createInfo.enabledLayerCount = 0;
					}

					// Create VKInstance;
					if (vkCreateInstance(&createInfo, nullptr, &pdata) != VK_SUCCESS) {
						throw Aeon::framework::exception("failed to create instance!");
					}

					// Setup debug callback

					if (Aeon::framework::enableValidationLayers) {
						VkDebugReportCallbackCreateInfoEXT dbgcreateInfo = {};
						dbgcreateInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT;
						dbgcreateInfo.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT;
						dbgcreateInfo.pfnCallback = debugCallback;

						if (CreateDebugReportCallbackEXT(pdata, &dbgcreateInfo, nullptr, &callback) != VK_SUCCESS) {
							throw Aeon::framework::exception("failed to set up debug callback!");
						}
					}
				}
示例#8
0
文件: Instance.cpp 项目: krre/gagarin
Instance::Instance() {
    // Get layers
    uint32_t layerCount;
    vkEnumerateInstanceLayerProperties(&layerCount, nullptr);
    layersProperties.resize(layerCount);
    vkEnumerateInstanceLayerProperties(&layerCount, layersProperties.data());

    // Get extensions
    uint32_t extensionCount;
    vkEnumerateInstanceExtensionProperties(nullptr, &extensionCount, nullptr);
    extensionProperties.resize(extensionCount);
    vkEnumerateInstanceExtensionProperties(nullptr, &extensionCount, extensionProperties.data());

#if defined(_WIN32)
    enabledExtensions = {
        "VK_KHR_surface",
        "VK_KHR_win32_surface",
    };
#elif defined(__linux__)
    enabledExtensions = {
        "VK_KHR_surface",
        "VK_KHR_xcb_surface",
    };
#endif

    applicationInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
    applicationInfo.pApplicationName = "Application";
    applicationInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
    applicationInfo.apiVersion = VK_API_VERSION_1_0;

    createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
    createInfo.pApplicationInfo = &applicationInfo;
}
VkResult VulkanBase::createInstance(bool enableValidation) {
	this->enableValidation = enableValidation;

	VkApplicationInfo appInfo = {};
	appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
	appInfo.pApplicationName = name.c_str();
	appInfo.pEngineName = name.c_str();
	appInfo.apiVersion = VK_MAKE_VERSION(1, 0, 7);

	std::vector<const char*> enabledExtensions = {VK_KHR_SURFACE_EXTENSION_NAME};

	enabledExtensions.push_back(VK_KHR_WIN32_SURFACE_EXTENSION_NAME);

	VkInstanceCreateInfo instanceCreateInfo = {};
	instanceCreateInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
	instanceCreateInfo.pNext = NULL;
	instanceCreateInfo.pApplicationInfo = &appInfo;
	if (enabledExtensions.size() > 0){
		if (enableValidation)
			enabledExtensions.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
		instanceCreateInfo.enabledExtensionCount = (uint32_t)enabledExtensions.size();
		instanceCreateInfo.ppEnabledExtensionNames = enabledExtensions.data();
	}
	if (enableValidation){
		instanceCreateInfo.enabledLayerCount = vkDebug::validationLayerCount;
		instanceCreateInfo.ppEnabledLayerNames = vkDebug::validationLayerNames;
	}
	return vkCreateInstance(&instanceCreateInfo, nullptr, &instance);
}
示例#10
0
//Creates our vulkan instance and returns an error if it fails
VkResult gvkInitUtils::initVulkan(VkInstance * inst)
{
	VkApplicationInfo appinfo = {};
	appinfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
	appinfo.pNext = nullptr;
	appinfo.pApplicationName = "TODO: CHANGE THIS";
	appinfo.pEngineName = "VKEngine";
	appinfo.apiVersion = VK_API_VERSION_1_0;
	appinfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
	appinfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);

	std::vector<const char *> enableExtensions = { VK_KHR_SURFACE_EXTENSION_NAME};

#ifdef _WIN32
	enableExtensions.push_back(VK_KHR_WIN32_SURFACE_EXTENSION_NAME);
#elif defined(__linux__)
	enableExtensions.push_back(VK_KHR_XCB_SURFACE_EXTENSION_NAME);
#endif
	
	VkInstanceCreateInfo instCrInfo = {};
	instCrInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
	instCrInfo.pApplicationInfo = &appinfo;
	instCrInfo.pNext = nullptr;
#ifdef _DEBUG
	std::array<const char*, 1> enabledLayers = {"VK_LAYER_LUNARG_standard_validation" };
	if (!hasLayer("VK_LAYER_LUNARG_standard_validation")) {
		std::cerr << "ERROR REQUIRED LAYER DOES NOT EXIST" << std::endl;
		return VK_ERROR_INCOMPATIBLE_DRIVER;
	}
	enableExtensions.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
	instCrInfo.enabledLayerCount = enabledLayers.size();
	instCrInfo.ppEnabledLayerNames = enabledLayers.data();
	if (!hasExtension(VK_EXT_DEBUG_REPORT_EXTENSION_NAME, "VK_LAYER_LUNARG_standard_validation")) {
		std::cerr << "ERROR: REQUIRED EXTENSION DOES NOT EXIST" << std::endl;
		return VK_ERROR_INCOMPATIBLE_DRIVER;
	}
	
#else
	instCrInfo.enabledLayerCount = 0;
	instCrInfo.ppEnabledLayerNames = nullptr;
#endif
	instCrInfo.flags = 0;

	instCrInfo.enabledExtensionCount = enableExtensions.size();
	instCrInfo.ppEnabledExtensionNames = enableExtensions.data();
	return vkCreateInstance(&instCrInfo, nullptr, inst);
}
示例#11
0
void Renderer::initInstance() {
    VkApplicationInfo applicationInfo{};
    applicationInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
    applicationInfo.apiVersion = VK_MAKE_VERSION(1, 0, 11);
    applicationInfo.applicationVersion = VK_MAKE_VERSION(0, 1, 0);
    applicationInfo.pApplicationName = "Vulkan Test Application";

    VkInstanceCreateInfo instanceCreateInfo{};
    instanceCreateInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
    instanceCreateInfo.pApplicationInfo = &applicationInfo;
    instanceCreateInfo.enabledLayerCount = mInstanceLayerList.size();
    instanceCreateInfo.ppEnabledLayerNames = mInstanceLayerList.data();
    instanceCreateInfo.enabledExtensionCount = mInstanceExtensionList.size();
    instanceCreateInfo.ppEnabledExtensionNames = mInstanceExtensionList.data();
    instanceCreateInfo.pNext = &mDebugCallbackCreateInfo;

    errorCheck(vkCreateInstance(&instanceCreateInfo, nullptr, &mInstance));
}
示例#12
0
namespace ste {

static constexpr char *ste_name = "StE";
static constexpr unsigned ste_version_major = 2;
static constexpr unsigned ste_version_minor = 0;

static constexpr auto vk_api_version = VK_MAKE_VERSION(1, 0, 42);

}
示例#13
0
VkInstance VulkanContext::CreateVulkanInstance(WindowSystemType wstype, bool enable_debug_report,
                                               bool enable_validation_layer)
{
  ExtensionList enabled_extensions;
  if (!SelectInstanceExtensions(&enabled_extensions, wstype, enable_debug_report))
    return VK_NULL_HANDLE;

  VkApplicationInfo app_info = {};
  app_info.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
  app_info.pNext = nullptr;
  app_info.pApplicationName = "Dolphin Emulator";
  app_info.applicationVersion = VK_MAKE_VERSION(5, 0, 0);
  app_info.pEngineName = "Dolphin Emulator";
  app_info.engineVersion = VK_MAKE_VERSION(5, 0, 0);
  app_info.apiVersion = VK_MAKE_VERSION(1, 0, 0);

  VkInstanceCreateInfo instance_create_info = {};
  instance_create_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
  instance_create_info.pNext = nullptr;
  instance_create_info.flags = 0;
  instance_create_info.pApplicationInfo = &app_info;
  instance_create_info.enabledExtensionCount = static_cast<uint32_t>(enabled_extensions.size());
  instance_create_info.ppEnabledExtensionNames = enabled_extensions.data();
  instance_create_info.enabledLayerCount = 0;
  instance_create_info.ppEnabledLayerNames = nullptr;

  // Enable debug layer on debug builds
  if (enable_validation_layer)
  {
    static const char* layer_names[] = {"VK_LAYER_LUNARG_standard_validation"};
    instance_create_info.enabledLayerCount = 1;
    instance_create_info.ppEnabledLayerNames = layer_names;
  }

  VkInstance instance;
  VkResult res = vkCreateInstance(&instance_create_info, nullptr, &instance);
  if (res != VK_SUCCESS)
  {
    LOG_VULKAN_ERROR(res, "vkCreateInstance failed: ");
    return nullptr;
  }

  return instance;
}
示例#14
0
void Renderer::_InitInstance()
{
	VkApplicationInfo application_info {};
	application_info.sType							= VK_STRUCTURE_TYPE_APPLICATION_INFO;
	application_info.apiVersion						= VK_MAKE_VERSION( 1, 0, 2 );			// 1.0.2 should work on all vulkan enabled drivers.
	application_info.applicationVersion				= VK_MAKE_VERSION( 0, 1, 0 );
	application_info.pApplicationName				= "Vulkan API Tutorial Series";

	VkInstanceCreateInfo instance_create_info {};
	instance_create_info.sType						= VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
	instance_create_info.pApplicationInfo			= &application_info;
	instance_create_info.enabledLayerCount			= _instance_layers.size();
	instance_create_info.ppEnabledLayerNames		= _instance_layers.data();
	instance_create_info.enabledExtensionCount		= _instance_extensions.size();
	instance_create_info.ppEnabledExtensionNames	= _instance_extensions.data();
	instance_create_info.pNext						= &_debug_callback_create_info;

	ErrorCheck( vkCreateInstance( &instance_create_info, nullptr, &_instance ) );
}
示例#15
0
namespace System
{
	using ResultMap = std::unordered_map<VkResult, std::string>;
	ResultMap n_ResultMap;
	const std::string n_DefaultResult("N/A");
	bool n_bInitialized = false;
	uint32 n_uiAPIVersion = VK_MAKE_VERSION(1, 0, 0);

	void PopulateResultMap();
}
示例#16
0
			bool VkContext::CreateInstance(const char* name) {
				VkApplicationInfo appInfo = {};
				appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
				appInfo.pNext = nullptr;
				appInfo.pApplicationName = name;
				appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
				appInfo.pEngineName = "Voxl Engine";
				appInfo.engineVersion = VK_MAKE_VERSION(VOXL_VERSION_MAJOR, VOXL_VERSION_MINOR, VOXL_VERSION_PATCH);
				appInfo.apiVersion = VK_API_VERSION_1_0;

				std::vector<const char *> instanceExtensions;
				std::vector<const char *> instanceLayers;

#ifdef VOXL_DEBUG
				// Add debug report extension
				instanceExtensions.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);

				// Add validation layers
				instanceLayers.push_back("VK_LAYER_LUNARG_standard_validation");
#endif

				// Add GLFW extensions
				u32 glfwExtensionCount = 0;
				const char **glfwExtensions =
					glfwGetRequiredInstanceExtensions(&glfwExtensionCount);
				for (u32 i = 0; i < glfwExtensionCount; i++) {
					instanceExtensions.push_back(glfwExtensions[i]);
				}

				VkInstanceCreateInfo instanceInfo = {};
				instanceInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
				instanceInfo.pNext = nullptr;
				instanceInfo.flags = 0;
				instanceInfo.pApplicationInfo = &appInfo;
				instanceInfo.enabledExtensionCount = (u32)instanceExtensions.size();
				instanceInfo.ppEnabledExtensionNames = instanceExtensions.data();
				instanceInfo.enabledLayerCount = (u32)instanceLayers.size();
				instanceInfo.ppEnabledLayerNames = instanceLayers.data();

				CheckVkResult(vkCreateInstance(&instanceInfo, nullptr, &instance));

				return true;
			}
示例#17
0
// Instances
void Renderer::_InitInstance() {
	// Application info
	VkApplicationInfo application_info {};
	application_info.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
	application_info.apiVersion = VK_MAKE_VERSION(1, 0, 13);
	application_info.applicationVersion = VK_MAKE_VERSION(0, 1, 0);
	application_info.pApplicationName = "Vulkan Testing";

	// Instance create info
	VkInstanceCreateInfo instance_create_info{};
	instance_create_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
	instance_create_info.pApplicationInfo = &application_info;
	instance_create_info.enabledLayerCount = (uint32_t) _instance_layer_list.size();
	instance_create_info.ppEnabledLayerNames = _instance_layer_list.data();
	instance_create_info.enabledExtensionCount = (uint32_t) _instance_extension_list.size();
	instance_create_info.ppEnabledExtensionNames = _instance_extension_list.data();
	instance_create_info.pNext = &_debug_callback_create_info;

	ErrorCheck(vkCreateInstance(&instance_create_info, nullptr, &_instance));
}
    void createInstance()
    {
        // Get the required vulkan extensions
        auto extensions = std::move(getRequiredExtensions());

        // Fetch the validation layers we watch
        if(enableValidationLayers && !checkValidationLayerSupport()) {
            throw std::runtime_error("Requested validation layers unavailable");
        }

        // Setup some simple application information for Vulkan
        VkApplicationInfo appInfo  = {};
        appInfo.sType              = VK_STRUCTURE_TYPE_APPLICATION_INFO;
        appInfo.pApplicationName   = TITLE;
        appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
        appInfo.pEngineName        = "Derpgin";
        appInfo.engineVersion      = VK_MAKE_VERSION(1, 0, 0);
        appInfo.apiVersion         = VK_API_VERSION_1_0;

        // Setup the instance information
        VkInstanceCreateInfo createInfo    = {};
        createInfo.sType                   = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
        createInfo.pApplicationInfo        = &appInfo;
        createInfo.enabledExtensionCount   = extensions.size();
        createInfo.ppEnabledExtensionNames = extensions.data();
        createInfo.enabledLayerCount       = 0;

        if(enableValidationLayers) {
            createInfo.enabledLayerCount   = validationLayers.size();
            createInfo.ppEnabledLayerNames = validationLayers.data();
        } else {
            createInfo.enabledLayerCount   = 0;
        }

        // Create the vulkan instance
        if(vkCreateInstance(&createInfo, nullptr, &instance) != VK_SUCCESS) {
            throw std::runtime_error("Failed to create Vulkan instance");
        }
    }
示例#19
0
	VkResult Instance::create()
	{
		const char* extensionNames[] = { VK_KHR_SURFACE_EXTENSION_NAME, VK_KHR_WIN32_SURFACE_EXTENSION_NAME };

		VkApplicationInfo applicationInfo = {};
		applicationInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
		applicationInfo.pApplicationName = "test_vk";
		applicationInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
		applicationInfo.pEngineName = "test_vk";
		applicationInfo.engineVersion = VK_MAKE_VERSION(0, 9, 0);
		applicationInfo.apiVersion = VK_API_VERSION;

		VkInstanceCreateInfo instanceCreateInfo = {};
		instanceCreateInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
		instanceCreateInfo.flags = 0;
		instanceCreateInfo.pApplicationInfo = &applicationInfo;
		instanceCreateInfo.enabledLayerCount = 0;
		instanceCreateInfo.ppEnabledLayerNames = nullptr;
		instanceCreateInfo.enabledExtensionCount = 2;
		instanceCreateInfo.ppEnabledExtensionNames = extensionNames;

		return vkCreateInstance(&instanceCreateInfo, nullptr, &m_instance);
	}
示例#20
0
VkResult VulkanExampleBase::createInstance(bool enableValidation)
{
	this->enableValidation = enableValidation;

	VkApplicationInfo appInfo = {};
	appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
	appInfo.pApplicationName = name.c_str();
	appInfo.pEngineName = name.c_str();
	// Temporary workaround for drivers not supporting SDK 1.0.3 upon launch
	// todo : Use VK_API_VERSION
	appInfo.apiVersion = VK_MAKE_VERSION(1, 0, 2);

	std::vector<const char*> enabledExtensions = { VK_KHR_SURFACE_EXTENSION_NAME };

	// Enable surface extensions depending on os
#if defined(_WIN32)
	enabledExtensions.push_back(VK_KHR_WIN32_SURFACE_EXTENSION_NAME);
#elif defined(__ANDROID__)
	enabledExtensions.push_back(VK_KHR_ANDROID_SURFACE_EXTENSION_NAME);
#elif defined(__linux__)
	enabledExtensions.push_back(VK_KHR_XCB_SURFACE_EXTENSION_NAME);
#endif

	VkInstanceCreateInfo instanceCreateInfo = {};
	instanceCreateInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
	instanceCreateInfo.pNext = NULL;
	instanceCreateInfo.pApplicationInfo = &appInfo;
	if (enabledExtensions.size() > 0)
	{
		if (enableValidation)
		{
			enabledExtensions.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
		}
		instanceCreateInfo.enabledExtensionCount = (uint32_t)enabledExtensions.size();
		instanceCreateInfo.ppEnabledExtensionNames = enabledExtensions.data();
	}
	if (enableValidation)
	{
		instanceCreateInfo.enabledLayerCount = vkDebug::validationLayerCount;
		instanceCreateInfo.ppEnabledLayerNames = vkDebug::validationLayerNames;
	}
	return vkCreateInstance(&instanceCreateInfo, nullptr, &instance);
}
示例#21
0
void Shell::init_instance()
{
    assert_all_instance_layers();
    assert_all_instance_extensions();

    VkApplicationInfo app_info = {};
    app_info.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
    app_info.pApplicationName = settings_.name.c_str();
    app_info.applicationVersion = 0;
    app_info.apiVersion = VK_MAKE_VERSION(1, 0, 0);

    VkInstanceCreateInfo instance_info = {};
    instance_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
    instance_info.pApplicationInfo = &app_info;
    instance_info.enabledLayerCount = static_cast<uint32_t>(instance_layers_.size());
    instance_info.ppEnabledLayerNames = instance_layers_.data();
    instance_info.enabledExtensionCount = static_cast<uint32_t>(instance_extensions_.size());
    instance_info.ppEnabledExtensionNames = instance_extensions_.data();

    vk::assert_success(vk::CreateInstance(&instance_info, nullptr, &ctx_.instance));
}
示例#22
0
bool VKAppInstance::Initialize(std::string title)
{
    VkResult res = VK_SUCCESS;

    if(!CheckInstanceExtensions())
        return false;

    VkApplicationInfo info;
    info.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
    info.pNext = nullptr;
    info.pApplicationName = title.c_str();
    info.applicationVersion = 0;
    info.pEngineName = "VulkanExamples";
    info.engineVersion = 0;
    info.apiVersion = VK_MAKE_VERSION(1, 0, 11);

    for(auto layers : m_instanceLayerCollection)
    {
        m_enabledLayerNames = layers;

        VkInstanceCreateInfo cInfo;
        cInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
        cInfo.pNext = nullptr;
        cInfo.flags = 0;
        cInfo.pApplicationInfo = &info;
        cInfo.enabledLayerCount = static_cast<uint32_t>(layers.size());
        cInfo.ppEnabledLayerNames = &layers[0];
        cInfo.enabledExtensionCount = m_enabledExtNames.size();
        cInfo.ppEnabledExtensionNames = &m_enabledExtNames[0];

        res = vkCreateInstance(&cInfo, nullptr, &m_instance);
        if(res == VK_SUCCESS)
            break;
        else
            std::cerr << "Failed to create Vulkan instance." << std::endl;
    }

    return true;
}
int main()
{
	// Our application initialization params
	Application::InitializationParams initParams = {};
	initParams.sApplicationName = "Chronicles of a Fallen Soul";
	initParams.sEngineName = "Wonderland";
	initParams.sApplicationVersion = VK_MAKE_VERSION(0, 0, 1);
	initParams.sEngineVersion = VK_MAKE_VERSION(0, 0, 1);
	initParams.sTotalNumberPeonThreads = 4;
	initParams.sThreadRingBufferSize = 65000;

	// Create and initialize the main application
	Application mainApplication = {};
	if (!mainApplication.Initialize(initParams))
	{
		return false;
	}

	// Run the main loop
	mainApplication.MainLoop();

	//

	bool result;

	//

	// Get all creator a register instances we need
	Flux::ClassCreator* classCreatorInstance = Flux::ClassCreator::GetInstance();
	Flux::ClassRegister* classRegisterInstance = Flux::ClassRegister::GetInstance();
	Flux::TypeCreator* typeCreatorInstance = Flux::TypeCreator::GetInstance();
	Flux::TypeRegister* typeRegisterInstance = Flux::TypeRegister::GetInstance();
	Flux::DynamicMemberFunctionCreator* memberFunctionCreatorInstance = Flux::DynamicMemberFunctionCreator::GetInstance();

	// Basic type registration //
	Flux::Type* intType = typeCreatorInstance->CreateType("int");
	Flux::Type* floatType = typeCreatorInstance->CreateType("float");
	Flux::Type* charType = typeCreatorInstance->CreateType("char");
	Flux::Type* stringType = typeCreatorInstance->CreateType("string");
	Flux::Type* booleanType = typeCreatorInstance->CreateType("bool");
	Flux::Type* vectorType = typeCreatorInstance->CreateType("vector");

	// Class creation //

	// Create a new class
	Flux::Class* newClass = classCreatorInstance->CreateClass("Car");
	if (newClass == nullptr)
	{
		return false;
	}

	// Create a variable from the created class
	Flux::MemberVariable speedVariable;
	result = speedVariable.Build(floatType, "m_Speed");
	if (!result)
	{
		return false;
	}

	// Add the member variable
	result = newClass->AddMemberVariable(speedVariable);
	if(!result)
	{
		return false;
	}

	// Create a variable from the created class
	Flux::MemberVariable distanceVariable;
	result = distanceVariable.Build(intType, "m_CurrentDistance");
	if (!result)
	{
		return false;
	}

	// Add the member variable
	result = newClass->AddMemberVariable(speedVariable);
	if (!result)
	{
		return false;
	}

	// Create a variable from the created class
	Flux::MemberVariable costVariable;
	result = costVariable.Build(floatType, "m_CostPerDistance");
	if (!result)
	{
		return false;
	}

	// Add the member variable
	result = newClass->AddMemberVariable(speedVariable);
	if (!result)
	{
		return false;
	}

	// Function creation //

	// Create the nem member function
	Flux::DynamicMemberFunction* newFunction = memberFunctionCreatorInstance->CreateDynamicMemberFunction("CalculateTime", *newClass);
	if (newFunction == nullptr)
	{
		return false;
	}

	/*

		- Handle precisa ter um id de versão
	*/

	/*
		
		=> Dynamic Function:

		- Head		-> Definições de uma função (qual o nome, se pertence à uma classe, quais entradas... etc)
		- Body		-> Como esta definido o seu corpo, quais funções (boxes) são utilizados, quais foram as ligações efetuadas, variáveis utilizadas... etc
		- Linker	-> Realização da compilação da DynamicFunction em realtime.
	*/

	/*
		- Vamos ter uma nova classe que vai ser tipo um box, ele vai contar o ponto inicial, final e vai possuir blocos que vão se ligar entre si, esses blocos fazem referência
		à um box conectado.
		- Começando no bloco inicial, vamos ir para o proximo, aqui podemos ter por exemplo uma função membro, nosso objetivo será pegar os dados da função membro, fazer a chamada
		com ela utilizando as variáveis linkadas (nota que não foi incluido a geração dos nomes das variáveis).
		- Após isso vamos para a proxima função, que pode ser um loop por exemplo, o loop deve criar uma variável que vai ser o contador e usar os parâmetros de entrada para realizar
		as chamadas seguintes.

		- Da pra perceber que o ideal é fechar cada bloco, por exemplo no primeiro, podemos passar as variáveis linkadas aos sockets de entrada para o "fechador" da função membro
		utilizada e ela fica responsável por usar essas entradas e gerar a chamada, podendo até mesmo retornar e assim seguimos para a proxima box ou continuar por conta propria.
		- No segundo exemplo nos iriamos para um loop, ele vai ter os valores de entrada (index inicial, final, etc) e provavelmente deveriamos continuar a execução por conta
		propria.

		- Temos que pensar em como vamos fazer os ifs, os sequences, sets, gets, for eachs, prints, etc... São todas funções standard, intrinsic.
		- Talvez devemos separar tipo, funções membro, funções normais, loop for, if, set, get e assim vai... Só que as funções (tanto membro quando normais) existiriam de várias
		formas precisando serem registradas enquanto os outros seriam classes especializadas que não precisariam serem registradas, afinal já teriamos uma de cada tipo.
		- O ideal seria que tivermos uma forma de criar essas funções intrinsics, talvez seja possível faze-las na parte de funções normais ou quem sabe fazer um criador para elas.
	*/

	/*
		- Uma box pode ter inputs e outputs, não importa qual o tipo de box.
		- Uma input/output pode ser de vários tipos.

		- Uma box pode ser uma função, uma caixa de debug, um start ou end dentro de uma função, etc.
		- Uma input/output pode ser uma variável, um valor absoluto, uma constante, etc.
		- Uma input/output pode ter um valor temporário para teste na engine.
		- Uma input/output pode ser uma array, nesse caso ele não pode possuir um valor absoluto e sim deve ser uma variável.

		- Uma box SEMPRE deve ter (se tiver) apenas UMA entrada.
		- Uma box pode ter várias saídas desde que mantenha em mente que as saídas serão executadas em sequência (depende da interpretação da box)

		
	
	
	
	
	*/

	////////////////
	// INITIALIZE //
	////////////////
	MainViewController viewController;
	viewController.Initialize();

	////////////////////////
	////////////////////////
	////////////////////////

    return 0;
}
示例#24
0
    "VK_LAYER_LUNARG_device_limits",
    "VK_LAYER_LUNARG_object_tracker",
    "VK_LAYER_LUNARG_image",
    "VK_LAYER_LUNARG_core_validation",
    "VK_LAYER_LUNARG_swapchain",
    "VK_LAYER_GOOGLE_unique_objects",
    // not included in standard_validation
    //"VK_LAYER_LUNARG_api_dump",
    //"VK_LAYER_LUNARG_vktrace",
    //"VK_LAYER_LUNARG_screenshot",
};
#endif

// the minimum version of Vulkan supported
#ifdef SK_BUILD_FOR_ANDROID
const uint32_t kGrVkMinimumVersion = VK_MAKE_VERSION(1, 0, 3);
#else
const uint32_t kGrVkMinimumVersion = VK_MAKE_VERSION(1, 0, 8);
#endif

// Create the base Vulkan objects needed by the GrVkGpu object
const GrVkBackendContext* GrVkBackendContext::Create(uint32_t* presentQueueIndexPtr,
                             bool(*canPresent)(VkInstance, VkPhysicalDevice, uint32_t queueIndex)) {
    VkPhysicalDevice physDev;
    VkDevice device;
    VkInstance inst;
    VkResult err;

    const VkApplicationInfo app_info = {
        VK_STRUCTURE_TYPE_APPLICATION_INFO, // sType
        nullptr,                            // pNext
示例#25
0
IInstanceSP VKTS_APIENTRY instanceCreate(const char* applicationName, const uint32_t applicationVersion, const uint32_t apiVersion, const VkInstanceCreateFlags flags, const uint32_t enabledLayerCount, const char* const* enabledLayerNames, const uint32_t enabledExtensionCount, const char* const* enabledExtensionNames)
{
    if (!applicationName)
    {
        return IInstanceSP();
    }

    VkResult result;

    VkApplicationInfo applicationInfo;

    memset(&applicationInfo, 0, sizeof(VkApplicationInfo));

    applicationInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;

    applicationInfo.pApplicationName = applicationName;
    applicationInfo.applicationVersion = applicationVersion;
    applicationInfo.pEngineName = VKTS_ENGINE_NAME;
    applicationInfo.engineVersion = VK_MAKE_VERSION(VKTS_ENGINE_MAJOR, VKTS_ENGINE_MINOR, VKTS_ENGINE_PATCH);
    applicationInfo.apiVersion = apiVersion;

    VkInstanceCreateInfo instanceCreateInfo;

    memset(&instanceCreateInfo, 0, sizeof(VkInstanceCreateInfo));

    instanceCreateInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;

    instanceCreateInfo.flags = flags;
    instanceCreateInfo.pApplicationInfo = &applicationInfo;
    instanceCreateInfo.enabledLayerCount = enabledLayerCount;
    instanceCreateInfo.ppEnabledLayerNames = enabledLayerNames;
    instanceCreateInfo.enabledExtensionCount = enabledExtensionCount;
    instanceCreateInfo.ppEnabledExtensionNames = enabledExtensionNames;

    VkInstance instance;

    result = vkCreateInstance(&instanceCreateInfo, nullptr, &instance);

    if (result != VK_SUCCESS)
    {
        logPrint(VKTS_LOG_ERROR, "Instance: Could not create instance.");

        return IInstanceSP();
    }

    if (enabledExtensionCount > 0)
    {
        if (!instanceExtensionsAvailable(enabledExtensionCount, enabledExtensionNames))
        {
            vkDestroyInstance(instance, nullptr);

            return IInstanceSP();
        }
    }

    auto newInstance = new Instance(applicationName, applicationVersion, std::string(applicationInfo.pEngineName), applicationInfo.engineVersion, apiVersion, flags, enabledLayerCount, enabledLayerNames, enabledExtensionCount, enabledExtensionNames, instance);

    if (!newInstance)
    {
        vkDestroyInstance(instance, nullptr);

        return IInstanceSP();
    }

    return IInstanceSP(newInstance);
}
示例#26
0
void create_vulkan_renderer_backend(ReaperRoot& root, VulkanBackend& backend)
{
    REAPER_PROFILE_SCOPE("Vulkan", MP_RED1);
    log_info(root, "vulkan: creating backend");

    log_debug(root, "vulkan: loading {}", REAPER_VK_LIB_NAME);
    backend.vulkanLib = dynlib::load(REAPER_VK_LIB_NAME);

    vulkan_load_exported_functions(backend.vulkanLib);
    vulkan_load_global_level_functions();

    std::vector<const char*> extensions = {VK_KHR_SURFACE_EXTENSION_NAME, REAPER_VK_SWAPCHAIN_EXTENSION_NAME};

#if defined(REAPER_DEBUG)
    extensions.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
#endif

    log_info(root, "vulkan: using {} instance level extensions", extensions.size());
    for (auto& e : extensions)
        log_debug(root, "- {}", e);

    vulkan_instance_check_extensions(extensions);

    std::vector<const char*> layers;

#if defined(REAPER_DEBUG) && !defined(REAPER_PLATFORM_WINDOWS)
    layers.push_back("VK_LAYER_LUNARG_standard_validation");
#endif

    log_info(root, "vulkan: using {} instance level layers", layers.size());
    for (auto& layer : layers)
        log_debug(root, "- {}", layer);

    vulkan_instance_check_layers(layers);

    VkApplicationInfo application_info = {
        VK_STRUCTURE_TYPE_APPLICATION_INFO, // VkStructureType            sType
        nullptr,                            // const void                *pNext
        "MyGame",                           // const char                *pApplicationName
        VK_MAKE_VERSION(
            REAPER_VERSION_MAJOR, REAPER_VERSION_MINOR, REAPER_VERSION_PATCH), // uint32_t applicationVersion
        "Reaper",                                                              // const char                *pEngineName
        VK_MAKE_VERSION(REAPER_VERSION_MAJOR, REAPER_VERSION_MINOR, REAPER_VERSION_PATCH), // uint32_t engineVersion
        REAPER_VK_API_VERSION // uint32_t                   apiVersion
    };

    uint32_t layerCount = static_cast<uint32_t>(layers.size());
    uint32_t extensionCount = static_cast<uint32_t>(extensions.size());

    VkInstanceCreateInfo instance_create_info = {
        VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,          // VkStructureType            sType
        nullptr,                                         // const void*                pNext
        0,                                               // VkInstanceCreateFlags      flags
        &application_info,                               // const VkApplicationInfo   *pApplicationInfo
        layerCount,                                      // uint32_t                   enabledLayerCount
        (layerCount > 0 ? &layers[0] : nullptr),         // const char * const        *ppEnabledLayerNames
        extensionCount,                                  // uint32_t                   enabledExtensionCount
        (extensionCount > 0 ? &extensions[0] : nullptr), // const char * const        *ppEnabledExtensionNames
    };

    Assert(vkCreateInstance(&instance_create_info, nullptr, &backend.instance) == VK_SUCCESS,
           "cannot create Vulkan instance");

    vulkan_load_instance_level_functions(backend.instance);

#if defined(REAPER_DEBUG)
    log_debug(root, "vulkan: attaching debug callback");
    vulkan_setup_debug_callback(root, backend);
#endif

    WindowCreationDescriptor windowDescriptor;
    windowDescriptor.title = "Vulkan";
    windowDescriptor.width = 800;
    windowDescriptor.height = 600;
    windowDescriptor.fullscreen = false;

    log_info(root,
             "vulkan: creating window: size = {}x{}, title = '{}', fullscreen = {}",
             windowDescriptor.width,
             windowDescriptor.height,
             windowDescriptor.title,
             windowDescriptor.fullscreen);
    IWindow* window = createWindow(windowDescriptor);

    root.renderer->window = window;

    log_debug(root, "vulkan: creating presentation surface");
    vulkan_create_presentation_surface(backend.instance, backend.presentInfo.surface, window);

    log_debug(root, "vulkan: choosing physical device");
    vulkan_choose_physical_device(root, backend, backend.physicalDeviceInfo);

    log_debug(root, "vulkan: creating logical device");
    vulkan_create_logical_device(root, backend);

    SwapchainDescriptor swapchainDesc;
    swapchainDesc.preferredImageCount = 2; // Double buffering
    swapchainDesc.preferredFormat = {VK_FORMAT_B8G8R8A8_UNORM, VK_COLORSPACE_SRGB_NONLINEAR_KHR};
    swapchainDesc.preferredExtent = {windowDescriptor.width, windowDescriptor.height};

    configure_vulkan_wm_swapchain(root, backend, swapchainDesc, backend.presentInfo);
    create_vulkan_wm_swapchain(root, backend, backend.presentInfo);

    // create_vulkan_display_swapchain(root, backend);

    log_info(root, "vulkan: ready");
}
示例#27
0
bool vulkan_check_physical_device(IWindow*                        window,
                                  VkPhysicalDevice                physical_device,
                                  VkSurfaceKHR                    presentationSurface,
                                  const std::vector<const char*>& extensions,
                                  uint32_t&                       queue_family_index,
                                  uint32_t&                       selected_present_queue_family_index)
{
    Assert(window != nullptr);

    vulkan_device_check_extensions(extensions, physical_device);

    VkPhysicalDeviceProperties device_properties;
    VkPhysicalDeviceFeatures   device_features;

    vkGetPhysicalDeviceProperties(physical_device, &device_properties);
    vkGetPhysicalDeviceFeatures(physical_device, &device_features);

    Assert(device_properties.apiVersion >= VK_MAKE_VERSION(1, 0, 0));
    Assert(device_properties.limits.maxImageDimension2D >= 4096);
    Assert(device_features.shaderClipDistance == VK_TRUE); // This is just checked, not enabled

    uint32_t queue_families_count = 0;
    vkGetPhysicalDeviceQueueFamilyProperties(physical_device, &queue_families_count, nullptr);

    Assert(queue_families_count > 0, "device doesn't have any queue families");
    if (queue_families_count == 0)
        return false;

    std::vector<VkQueueFamilyProperties> queue_family_properties(queue_families_count);
    std::vector<VkBool32>                queue_present_support(queue_families_count);

    vkGetPhysicalDeviceQueueFamilyProperties(physical_device, &queue_families_count, &queue_family_properties[0]);

    uint32_t graphics_queue_family_index = UINT32_MAX;
    uint32_t present_queue_family_index = UINT32_MAX;

    for (uint32_t i = 0; i < queue_families_count; ++i)
    {
        Assert(vkGetPhysicalDeviceSurfaceSupportKHR(physical_device, i, presentationSurface, &queue_present_support[i])
               == VK_SUCCESS);

        if ((queue_family_properties[i].queueCount > 0)
            && (queue_family_properties[i].queueFlags & VK_QUEUE_GRAPHICS_BIT))
        {
            // Select first queue that supports graphics
            if (graphics_queue_family_index == UINT32_MAX)
                graphics_queue_family_index = i;

            Assert(vulkan_queue_family_has_presentation_support(physical_device, i, window)
                       == (queue_present_support[i] == VK_TRUE),
                   "Queue family presentation support mismatch.");

            // If there is queue that supports both graphics and present - prefer it
            if (queue_present_support[i])
            {
                queue_family_index = i;
                selected_present_queue_family_index = i;
                return true;
            }
        }
    }

    // We don't have queue that supports both graphics and present so we have to use separate queues
    for (uint32_t i = 0; i < queue_families_count; ++i)
    {
        if (queue_present_support[i] == VK_TRUE)
        {
            present_queue_family_index = i;
            break;
        }
    }

    Assert(graphics_queue_family_index != UINT32_MAX);
    Assert(present_queue_family_index != UINT32_MAX);

    queue_family_index = graphics_queue_family_index;
    selected_present_queue_family_index = present_queue_family_index;
    return true;
}
示例#28
0
VkResult init_Vulkan(VkInstance& vk_instance, VkDevice* out_device, DrawCommandBuffer* out_draw_command_buffer, SwapChain* out_swap_chain)
{
    if ((out_device == nullptr) || (out_swap_chain == nullptr))
    {
        return VK_ERROR_INITIALIZATION_FAILED;
    }
    VkApplicationInfo app_info = {};
    app_info.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
    app_info.pNext = nullptr;
    app_info.pApplicationName = "VT Test";
    app_info.applicationVersion = 0x00000001;
    app_info.pEngineName = "Noengine";
    app_info.engineVersion = 0x00;
    app_info.apiVersion = VK_MAKE_VERSION(1, 0, 2);

    std::vector<const char *> enabledExtensions = { VK_KHR_SURFACE_EXTENSION_NAME };
    enabledExtensions.push_back(VK_KHR_WIN32_SURFACE_EXTENSION_NAME);

    VkInstanceCreateInfo instance_info = {};
    instance_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
    instance_info.pNext = nullptr;
    instance_info.flags = 0;
    instance_info.pApplicationInfo = &app_info;
    instance_info.enabledLayerCount = 0;
    instance_info.ppEnabledLayerNames = nullptr;
    instance_info.enabledExtensionCount = static_cast<uint32_t>(enabledExtensions.size());
    instance_info.ppEnabledExtensionNames = enabledExtensions.data();

    VK_THROW(vkCreateInstance(&instance_info, nullptr, &vk_instance)); // Create Vulkan library instance

    out_swap_chain->instance = GetModuleHandle(NULL);
    out_swap_chain->window = setup_window(out_swap_chain->instance, 800, 600, "vk_test");

    uint32_t gpu_count = 0;
    // Get number of available physical devices
    VK_THROW(vkEnumeratePhysicalDevices(vk_instance, &gpu_count, nullptr));
    assert(gpu_count > 0);

    std::vector<VkPhysicalDevice> physicalDevices(gpu_count); // Enumerate devices
    VK_THROW(vkEnumeratePhysicalDevices(vk_instance, &gpu_count, physicalDevices.data()));
    bool surface_created = false;
    VkPhysicalDeviceProperties gpu_properties;
    VkPhysicalDeviceFeatures gpu_feature;
    for (uint32_t gidx = 0; gidx < gpu_count; ++gidx)
    {
        VkPhysicalDevice gpu = physicalDevices[gidx];
        vkGetPhysicalDeviceProperties(gpu, &gpu_properties);
        std::cout << gidx << "Driver Version: " << gpu_properties.driverVersion << "\n";
        std::cout << gidx << "Device Name:    " << gpu_properties.deviceName << "\n";
        std::cout << gidx << "Device Type:    " << gpu_properties.deviceType << "\n";
        std::cout << gidx << "API Version:    " << VK_VERSION_MAJOR(gpu_properties.apiVersion) << "." << VK_VERSION_MINOR(gpu_properties.apiVersion) << "." << VK_VERSION_PATCH(gpu_properties.apiVersion) << "\n";

        // we can choose a gpu based on the features here.
        vkGetPhysicalDeviceFeatures(gpu, &gpu_feature);

        VkResult err = create_surface(vk_instance, gpu, out_device, out_draw_command_buffer, out_swap_chain);
        if (err == VK_SUCCESS)
        {
            surface_created = true;
            break;
        }
    }
    if (!surface_created)
    {
        return VK_ERROR_INITIALIZATION_FAILED;
    }

    return VK_SUCCESS;
}
示例#29
0
文件: main.cpp 项目: YoutaVen/Vulkan
int main()
{
	//
	// Engine initialization.
	//

	if (!vkts::engineInit())
	{
		return -1;
	}

	vkts::logSetLevel(VKTS_LOG_INFO);

	//
	// Set task executors.
	//

	if (!vkts::engineSetTaskExecutorCount(vkts::processorGetNumber()))
	{
		vkts::logPrint(VKTS_LOG_ERROR, "Main: Could not set task executors.");

		terminateApp();

		return -1;
	}

	//

	VkResult result;

	//

	if (!vkts::wsiGatherNeededInstanceExtensions())
	{
		vkts::logPrint(VKTS_LOG_ERROR, "Example: Could not gather instance extensions.");

		terminateApp();

		return -1;
	}

	auto instance = vkts::instanceCreate(VKTS_EXAMPLE_NAME, VK_MAKE_VERSION(1, 0, 0), VK_MAKE_VERSION(1, 0, 0), 0, 0, nullptr, vkts::extensionGetNeededInstanceExtensionCount(), vkts::extensionGetNeededInstanceExtensionNames());

	if (!instance.get())
	{
		vkts::logPrint(VKTS_LOG_ERROR, "Main: Could not create instance.");

		terminateApp();

		return -1;
	}

	if (!vkts::wsiInitInstanceExtensions(instance->getInstance()))
	{
		vkts::logPrint(VKTS_LOG_ERROR, "Main: Could not initialize instance extension.");

		terminateApp();

		return -1;
	}

	auto physicalDevice = vkts::physicalDeviceCreate(instance->getInstance(), 0);

	if (!physicalDevice.get())
	{
		vkts::logPrint(VKTS_LOG_ERROR, "Main: Could not get physical device.");

		terminateApp();

		return -1;
	}

	//

	VkPhysicalDeviceFeatures physicalDeviceFeatures;

	physicalDevice->getPhysicalDeviceFeatures(physicalDeviceFeatures);

	// Check, if geometry and tessellation shader are available.
	if (!physicalDeviceFeatures.geometryShader || !physicalDeviceFeatures.tessellationShader)
	{
		vkts::logPrint(VKTS_LOG_ERROR, "Main: Physical device not capable of geometry and tessellation shaders.");

		return VK_FALSE;
	}

	//

	if (!vkts::wsiGatherNeededDeviceExtensions(physicalDevice->getPhysicalDevice()))
	{
		vkts::logPrint(VKTS_LOG_ERROR, "Main: Could not gather device extension.");

		terminateApp();

		return -1;
	}

	//
	// Visual initialization.
	//

	if (!vkts::visualInit(instance->getInstance(), physicalDevice->getPhysicalDevice()))
	{
		vkts::logPrint(VKTS_LOG_ERROR, "Main: Could not initialize visual.");

		terminateApp();

		return -1;
	}

	display = vkts::visualCreateDefaultDisplay().lock();

	if (!display.get())
	{
		vkts::logPrint(VKTS_LOG_ERROR, "Main: Could not create display.");

		terminateApp();

		return -1;
	}

	window = vkts::visualCreateWindow(display, VKTS_EXAMPLE_NAME, 1024, 768, VK_FALSE, VK_TRUE, VK_FALSE).lock();

	if (!window.get())
	{
		window = vkts::visualGetWindow(VKTS_DEFAULT_WINDOW_INDEX).lock();

		if (!window.get())
		{
			vkts::logPrint(VKTS_LOG_ERROR, "Main: Could not create window.");

			terminateApp();

			return -1;
		}
	}

	//

	surface = vkts::wsiSurfaceCreate(instance->getInstance(), display->getNativeDisplay(), window->getNativeWindow());

	if (!surface.get())
	{
		vkts::logPrint(VKTS_LOG_ERROR, "Main: Could not create surface.");

		terminateApp();

		return -1;
	}

	//

	std::vector<VkBool32> supportFilter;

	result = vkts::wsiGetPhysicalDeviceSurfaceSupport(physicalDevice->getPhysicalDevice(), surface->getSurface(), (uint32_t) physicalDevice->getAllQueueFamilyProperties().size(), supportFilter);

	if (result != VK_SUCCESS || supportFilter.size() == 0)
	{
		vkts::logPrint(VKTS_LOG_ERROR, "Main: Could not get physical device surface support.");

		terminateApp();

		return -1;
	}

	//

	uint32_t queueFamilyIndex;

	if (!vkts::queueGetFamilyIndex(physicalDevice->getAllQueueFamilyProperties(), VK_QUEUE_GRAPHICS_BIT, 0, &supportFilter, queueFamilyIndex))
	{
		vkts::logPrint(VKTS_LOG_ERROR, "Main: Could not find queue family index.");

		terminateApp();

		return -1;
	}

	//

	float queuePriorities[1] = {0.0f};

	VkDeviceQueueCreateInfo deviceQueueCreateInfo;

	memset(&deviceQueueCreateInfo, 0, sizeof(VkDeviceQueueCreateInfo));

	deviceQueueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;

	deviceQueueCreateInfo.flags = 0;
	deviceQueueCreateInfo.queueFamilyIndex = 0;
	deviceQueueCreateInfo.queueCount = 1;
	deviceQueueCreateInfo.pQueuePriorities = queuePriorities;

	auto device = vkts::deviceCreate(physicalDevice->getPhysicalDevice(), 0, 1, &deviceQueueCreateInfo, 0, nullptr, vkts::extensionGetNeededDeviceExtensionCount(), vkts::extensionGetNeededDeviceExtensionNames(), nullptr);

	if (!device.get())
	{
		vkts::logPrint(VKTS_LOG_ERROR, "Main: Could not create device.");

		terminateApp();

		return -1;
	}

	if (!vkts::wsiInitDeviceExtensions(device->getDevice()))
	{
		vkts::logPrint(VKTS_LOG_ERROR, "Main: Could not initialize device extension.");

		terminateApp();

		return -1;
	}

	//

	auto queue = vkts::queueGet(device->getDevice(), queueFamilyIndex, 0);

	if (!queue.get())
	{
		vkts::logPrint(VKTS_LOG_ERROR, "Main: Could not get device queue.");

		terminateApp();

		return -1;
	}

	//

	initialResources = vkts::initialResourcesCreate(instance, physicalDevice, device, queue);

	if (!initialResources.get())
	{
		vkts::logPrint(VKTS_LOG_ERROR, "Main: Could not create initial resources.");

		terminateApp();

		return -1;
	}

	//
	// Example setup.
	//

	// Single threaded application, so it is safe to pass display and window.
	vkts::IUpdateThreadSP example = vkts::IUpdateThreadSP(new Example(initialResources, window->getIndex(), surface));

	if (!example.get())
	{
		vkts::logPrint(VKTS_LOG_ERROR, "Main: Could not create application.");

		terminateApp();

		return -1;
	}

	// This update thread is executed in the main loop. No additional thread is launched.
	vkts::engineAddUpdateThread(example);

	//
	// Execution.
	//

	vkts::engineRun();

	//
	// Termination.
	//

	terminateApp();

	return 0;
}
示例#30
0
			bool Device::Create()
			{
				// Application info structure
				VkApplicationInfo appInfo = {};
				appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
				appInfo.pApplicationName = "Shard Application";
				appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
				appInfo.pEngineName = "Shard Engine";
				appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);
				appInfo.apiVersion = VK_API_VERSION_1_0;

				// Instance info structure
				VkInstanceCreateInfo createInfo = {};
				createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
				createInfo.pApplicationInfo = &appInfo;

				// Load validation layers
				const std::vector<const char*> validationLayers =
				{
					"VK_LAYER_LUNARG_standard_validation"
				};
				const bool enableValidationLayers = true;	// TODO: only in debug

				if (enableValidationLayers)
				{
					uint32 layerCount = 0;
					vkEnumerateInstanceLayerProperties(&layerCount, NULL);
					std::vector<VkLayerProperties> availableLayers(layerCount);
					vkEnumerateInstanceLayerProperties(&layerCount, availableLayers.data());

					for (const char* layerName : validationLayers)
					{
						bool layerFound = false;
						for (const auto& layerProp : availableLayers)
						{
							if (std::strcmp(layerName, layerProp.layerName) == 0)
							{
								layerFound = true;
								break;
							}
						}

						if (!layerFound)
						{
							Debugging::Logger::d() << "Could not find VK validation layer: " << layerName << std::endl;
							return false;
						}
					}

					// Write layers in create info
					createInfo.enabledLayerCount = validationLayers.size();
					createInfo.ppEnabledLayerNames = validationLayers.data();
				}
				else
				{
					// No layers are enabled
					createInfo.enabledLayerCount = 0;
				}

				// Load extensions
				std::vector<const char*> extensionsNeeded =
				{
					VK_KHR_SURFACE_EXTENSION_NAME, VK_KHR_WIN32_SURFACE_EXTENSION_NAME
				};
				if (enableValidationLayers)
				{
					extensionsNeeded.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
				}

				uint32 extensionCount = 0;
				vkEnumerateInstanceExtensionProperties(NULL, &extensionCount, NULL);
				std::vector<VkExtensionProperties> availableExtensions(extensionCount);
				vkEnumerateInstanceExtensionProperties(NULL, &extensionCount, availableExtensions.data());
				for (const char* extName : extensionsNeeded)
				{
					bool extFound = false;
					for (const auto& extProp : availableExtensions)
					{
						if (std::strcmp(extName, extProp.extensionName) == 0)
						{
							extFound = true;
							break;
						}
					}

					if (!extFound)
					{
						Debugging::Logger::d() << "Could not find VK extension: " << extName << std::endl;
						return false;
					}
				}

				// Write extensions in create info
				createInfo.enabledExtensionCount = extensionsNeeded.size();
				createInfo.ppEnabledExtensionNames = extensionsNeeded.data();

				// Create the instance
				VkInstance instance;
				if (vkCreateInstance(&createInfo, nullptr, &instance) != VK_SUCCESS)
				{
					Debugging::Logger::d() << "Could not create VK device" << std::endl;
					return false;
				}

				return true;
			}