Skip to content

Instantly share code, notes, and snippets.

@Lightnet
Last active May 6, 2021 04:03
Show Gist options
  • Save Lightnet/bda93ce8b48c17f841898f602a1e1e4b to your computer and use it in GitHub Desktop.
Save Lightnet/bda93ce8b48c17f841898f602a1e1e4b to your computer and use it in GitHub Desktop.
glfw3 vulkan c api

Work in progress

Code Language: c

// this will not work in c
std::vector<const char*> extensions; 
// this wll work in c
uint32_t glfwExtensionCount = 0;
const char** glfwExtensions;
glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount);
//this will resize it to fixed array
const char** extensions = (char**)malloc((glfwExtensionCount + 1) * sizeof(char**));

for(int e = 0; e < glfwExtensionCount; e++){
  //printf("extensions: %s\n", extensions[e]);//will crash since it not assign string
  extensions[e] = glfwExtensions[e];
}
extensions[glfwExtensionCount+1] = VK_EXT_DEBUG_UTILS_EXTENSION_NAME;

Vulkan

  • checkValidationLayerSupport
  • getRequiredExtensions

Variables:

  • enableValidationLayers = true;
  • VkInstance instance;
  • VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
  • VkDevice device;
  • VkSurfaceCapabilitiesKHR surfaceCapabilities;
  • VkSurfaceKHR surface;
  • VkSwapchainKHR swapChain;
#================================================
# CMAKE BUILD
# WINDOW BUILD CURRENTLY
#================================================
cmake_minimum_required(VERSION 3.20) # FetchContent is available in 3.11+
#message("CMAKE_BUILD_TYPE >>> " ${CMAKE_BUILD_TYPE})
#convert checks for debug / release
if(CMAKE_BUILD_TYPE)
string(TOLOWER ${CMAKE_BUILD_TYPE} CMAKE_BUILD_TYPE)
endif()
if(CMAKE_BUILD_TYPE STREQUAL "debug")
set(CMAKE_BUILD_TYPE Debug)
message("CMAKE_BUILD_TYPE DEBUG")
elseif(CMAKE_BUILD_TYPE STREQUAL "release")
set(CMAKE_BUILD_TYPE Release)
message("CMAKE_BUILD_TYPE RELEASE")
else() #DEFAULT TO DEBUG
set(CMAKE_BUILD_TYPE Debug)
message("CMAKE_BUILD_TYPE Debug")
endif()
project(vulkancapp VERSION 0.0.1)
#add_definitions(-DECM_TEST01)
#add_definitions(-DECME_VULKAN)
set(PROJECT_VERSION 0.0.1)
set(PROJECT_VERSION_MAJOR 0)
set(PROJECT_VERSION_MINOR 0)
set(PROJECT_VERSION_PATCH 0)
message("START OF CMAKELIST...")
# https://bewagner.net/programming/2020/05/02/cmake-fetchcontent/
#set(FETCHCONTENT_FULLY_DISCONNECTED ON) # When this option is enabled, no attempt is made to download or update any content.
#set(FETCHCONTENT_UPDATES_DISCONNECTED ON) # download and skip update
#================================================
# ENTERY POINTS
#================================================
# entry point file.cpp
set(ENTRYPOINT
#vulkantriangle01.cpp
#src/main.cpp
)
#message("ENTRYPOINT: ${ENTRYPOINT}") # console log
#set(FETCHCONTENT_SOURCE_DIR_SDL ON)
#set(FETCHCONTENT_SOURCE_DIR_SDL_IMAGE ON)
#set(FETCHCONTENT_SOURCE_DIR_SDL_MIXER ON)
#set(FETCHCONTENT_SOURCE_DIR_IMGUI ON)
#================================================
# CONFIGS
#================================================
# deal with add ons and checks tests
# WINDOW / INPUT / CPU RENDER
set(ENABLE_SDL OFF)
set(ENABLE_GLFW ON)
# FONT
set(ENABLE_FREETYPE OFF) #needed for sdl image
set(ENABLE_SDL_TTF OFF)
# IMAGE
set(ENABLE_SDL_IMAGE OFF)
# SOUND / AUDIO
set(ENABLE_SDL_MIXER OFF)
# ENTITY COMPONENT SYSTEM
set(ENABLE_FLECS OFF)
# GRAPHIC USER INTERFACE
set(ENABLE_IMGUI OFF)
# 3D GRAPHIC API
set(ENABLE_VALKUN ON)
set(ENABLE_GL3W OFF)
set(ENABLE_GLAD OFF)
set(ENABLE_GLAD2 OFF)
# MATH GRAPHIC
set(ENABLE_GLM ON)
# MESH
set(ENABLE_TINYOBJECTLOADER OFF)
#================================================
# NETWORK
#================================================
#https://github.com/ValveSoftware/GameNetworkingSockets/blob/master/BUILDING.md
#set(ENABLE_GAMENETWORKKINGSOCKETS OFF) # not recommend
# there no CMakeList.txt in third parties.
# REQUIRED openssl
# REQUIRED perl
# REQUIRED ninja
# REQUIRED Protobuf
#================================================
# GIT PACKAGE VERSION
#================================================
set(FREETYPE_GIT_VERSION VER-2-10-4) # GITHUB RELEASE TAG
set(GLM_GIT_VERSION 0.9.9.8)
set(GLFW_GIT_VERSION 3.3.4)
set(SDL_GIT_VERSION release-2.0.14) # SDL GITHUB RELEASE TAG
set(SDL_TTF_GIT_VERSION main) # SDL GITHUB RELEASE TAG
set(SDL_IMAGE_GIT_VERSION main) # SDL GITHUB RELEASE TAG
set(SDL_MIXER_GIT_VERSION master) # SDL GITHUB RELEASE TAG
set(IMGUI_GIT_VERSION
#docking
v1.82
) # GITHUB RELEASE TAG
set(FLECS_GIT_VERSION v2.3.2) # GITHUB RELEASE TAG
set(GAMENETWORKKINGSOCKETS_GIT_VERSION master) # GITHUB RELEASE TAG
# config IDE ext
#include(CTest)
#enable_testing()
#================================================
# CONFIGS
#================================================
#et(CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/cmake/modules)
message("CMAKE_SYSTEM_NAME == " ${CMAKE_SYSTEM_NAME})
if (CMAKE_SYSTEM_NAME STREQUAL "Windows")
#target_compile_options(myApp PRIVATE /W4)
#message("WINDOW")
elseif (CMAKE_SYSTEM_NAME STREQUAL "Linux")
#target_compile_options(myApp PRIVATE -Wall -Wextra -Wpedantic)
#message("Linux")
elseif (CMAKE_SYSTEM_NAME STREQUAL "Darwin")
# other macOS-specific flags for Clang
#message("Darwin")
endif()
# https://cmake.org/cmake/help/latest/variable/CMAKE_BUILD_TYPE.html
#cmake -DCMAKE_BUILD_TYPE=Debug path/to/source
#cmake -DCMAKE_BUILD_TYPE=Release path/to/source
#message("CMAKE_C_FLAGS_RELEASE >>> " ${CMAKE_C_FLAGS_RELEASE})
#message("CMAKE_C_FLAGS >>> " ${CMAKE_C_FLAGS})
#message("CMAKE_CXX_FLAGS >>> " ${CMAKE_CXX_FLAGS})
#message("CMAKE_CONFIGURATION_TYPES >>> " ${CMAKE_CONFIGURATION_TYPES})
#message("CMAKE_CFG_INTDIR >>> " ${CMAKE_CFG_INTDIR})
#message("CMAKE_CUDA_FLAGS >>> " ${CMAKE_CUDA_FLAGS})
#message("CMAKE_Fortran_FLAGS >>> " ${CMAKE_Fortran_FLAGS})
#message("CMAKE_CURRENT_SOURCE_DIR >>> " ${CMAKE_CURRENT_SOURCE_DIR})
#message("CMAKE_CURRENT_BINARY_DIR >>> " ${CMAKE_CURRENT_BINARY_DIR})
# must set output build dir by default is none. user must config manual
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR})
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR})
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR})
#message("CMAKE_ARCHIVE_OUTPUT_DIRECTORY: ${CMAKE_ARCHIVE_OUTPUT_DIRECTORY}") # workspace/build/Debug
#message("CMAKE_LIBRARY_OUTPUT_DIRECTORY: ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}")
#message("CMAKE_RUNTIME_OUTPUT_DIRECTORY: ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}")
# build compiler tool
#set(CMAKE_C_STANDARD 11)
set(CMAKE_C_STANDARD 11)
#set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
#if(MSVC)
#set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /std:c++17")
#endif(MSVC)
# https://stackoverflow.com/questions/20643370/visual-studio-2013-fatal-error-c1041-fs
ADD_DEFINITIONS(-DUNICODE)
ADD_DEFINITIONS(-D_UNICODE)
# folders, files, libs
set(CPP_INCLUDE_DIRS "")
set(CPP_HEADER_FILES "")
set(CPP_SOURCE_FILES "")
set(CPP_LIBS "")
if(ENABLE_FREETYPE)
if (NOT freetype_FOUND) # If there's none, fetch and build
include(FetchContent)
FetchContent_Declare(
freetype
GIT_REPOSITORY https://github.com/freetype/freetype.git
GIT_TAG ${FREETYPE_GIT_VERSION}
#GIT_TAG VER-2-10-4
)
FetchContent_GetProperties(freetype)
if (NOT freetype_POPULATED) # Have we downloaded raylib yet?
set(FETCHCONTENT_QUIET NO)
FetchContent_Populate(freetype)
message("freetype_LIBRARY: " ${freetype_LIBRARY}) # fail but define in cmake
message("freetype_INCLUDE_DIR: " ${freetype_INCLUDE_DIR}) #pass
message("freetype_SOURCE_DIR: " ${freetype_SOURCE_DIR}) # pass
message("freetype_BINARY_DIR: " ${freetype_BINARY_DIR}) # pass
#set(FT_WITH_ZLIB OFF CACHE BOOL "" FORCE)
#set(FT_WITH_BZIP2 OFF CACHE BOOL "" FORCE)
#set(FT_WITH_PNG OFF CACHE BOOL "" FORCE)
#set(FT_WITH_HARFBUZZ OFF CACHE BOOL "" FORCE)
#set(FT_WITH_BROTLI OFF CACHE BOOL "" FORCE)
# build freetype
list(APPEND CPP_INCLUDE_DIRS ${freetype_SOURCE_DIR}/include)
list(APPEND CPP_INCLUDE_DIRS ${freetype_BINARY_DIR}/include)
list(APPEND CPP_HEADER_FILES ${freetype_SOURCE_DIR}/include/ft2build.h)
list(APPEND FREETYPE_INCLUDE_DIRS ${freetype_SOURCE_DIR}/include)
list(APPEND FREETYPE_INCLUDE_DIRS ${freetype_BINARY_DIR}/include)
set(FREETYPE_LIBRARY ${CMAKE_LIBRARY_OUTPUT_DIRECTORY})
#link_directories(${sdl_ttf_BINARY_DIR}/Debug)# this will look for libs files.
add_subdirectory(${freetype_SOURCE_DIR} ${freetype_BINARY_DIR}) #add to build in sub dir
add_library(Freetype::Freetype ALIAS freetype)
endif()
endif()
endif()
#================================================
# SDL
#================================================
if (ENABLE_SDL)
message("[[[=== CHECKING SDL2 === ]]]")
# base on environment system path variable set.
# find_package(sdl QUIET) # Requires at least version 2.5.0
message("sdl_FOUND:" ${SDL_FOUND})
if (NOT sdl_FOUND) # If there's none, fetch and build sdl
include(FetchContent)
FetchContent_Declare(
sdl
GIT_REPOSITORY https://github.com/libsdl-org/SDL.git
GIT_TAG ${SDL_GIT_VERSION}
)
FetchContent_GetProperties(sdl)
if (NOT SDL2_POPULATED) # Have we downloaded raylib yet?
set(FETCHCONTENT_QUIET NO)
FetchContent_Populate(sdl)
#message("SDL_LIBRARY: " ${sdl_LIBRARY}) # fail but define in cmake
#message("SDL_INCLUDE_DIR: " ${sdl_INCLUDE_DIR}) #pass
#message("sdl_SOURCE_DIR: " ${sdl_SOURCE_DIR}) # pass
#message("sdl_BINARY_DIR: " ${sdl_BINARY_DIR}) # pass
# build SDL2
list(APPEND CPP_INCLUDE_DIRS ${sdl_SOURCE_DIR}/include)
#include_directories(${sdl2_BINARY_DIR}/include)
#link_directories(${PROJECT_BINARY_DIR}/Debug)
add_subdirectory(${sdl_SOURCE_DIR} ${sdl_BINARY_DIR})
endif()
#needed for sub modules
list(APPEND SDL2_INCLUDE_DIR ${sdl_SOURCE_DIR}/include)
list(APPEND SDL2_LIBRARIES ${PROJECT_SOURCE_DIR}/build/Debug/SDL2maind.lib)
list(APPEND SDL2_LIBRARIES ${PROJECT_SOURCE_DIR}/build/Debug/SDL2-staticd.lib)
list(APPEND SDL2_LIBRARIES ${PROJECT_SOURCE_DIR}/build/Debug/SDL2d.lib)
#list(APPEND SDL2_LIBRARY ${PROJECT_BINARY_DIR}/Debug/SDL2maind.lib)
#list(APPEND SDL2_LIBRARY ${PROJECT_BINARY_DIR}/Debug/SDL2-staticd.lib)
#list(APPEND SDL2_LIBRARY ${PROJECT_BINARY_DIR}/Debug/SDL2d.lib)
#list(APPEND SDL2_LIB ${PROJECT_SOURCE_DIR}/build/Debug/SDL2maind.lib)
#list(APPEND SDL2_LIB ${PROJECT_SOURCE_DIR}/build/Debug/SDL2-staticd.lib)
#list(APPEND SDL2_LIB ${PROJECT_SOURCE_DIR}/build/Debug/SDL2d.lib)
list(APPEND CPP_LIBS "SDL2main")
list(APPEND CPP_LIBS "SDL2-static")
add_library(SDL2::SDL2 ALIAS SDL2)
add_library(SDL2::SDL2-static ALIAS SDL2-static)
endif()
endif()
link_directories(${PROJECT_BINARY_DIR}/Debug)
#================================================
# SDL TTF
#================================================
if (ENABLE_SDL_TTF)
# base on environment system path variable set.
if (NOT sdl_image_FOUND) # If there's none, fetch and build sdl
include(FetchContent)
FetchContent_Declare(
sdl_ttf
GIT_REPOSITORY https://github.com/libsdl-org/SDL_ttf.git
GIT_TAG ${SDL_TTF_GIT_VERSION}
)
FetchContent_GetProperties(sdl_ttf)
if (NOT sdl_ttf_POPULATED) # Have we downloaded raylib yet?
set(FETCHCONTENT_QUIET NO)
FetchContent_Populate(sdl_ttf)
#message("sdl_ttf_LIBRARY: " ${sdl_ttf_LIBRARY}) # fail but define in cmake
#message("sdl_ttf_INCLUDE_DIR: " ${sdl_ttf_INCLUDE_DIR}) #pass
#message("sdl_ttf_SOURCE_DIR: " ${sdl_ttf_SOURCE_DIR}) # pass
#message("sdl_ttf_BINARY_DIR: " ${sdl_ttf_BINARY_DIR}) # pass
# build SDL2
#list(APPEND CPP_INCLUDE_DIRS ${sdl_image_SOURCE_DIR}/include)
add_subdirectory(${sdl_ttf_SOURCE_DIR} ${sdl_ttf_BINARY_DIR})
#list(APPEND CPP_LIBS "sdl_ttf")
endif()
endif()
endif()
#================================================
# SDL IMAGE
#================================================
if (ENABLE_SDL_IMAGE)
# base on environment system path variable set.
if (NOT sdl_image_FOUND) # If there's none, fetch and build sdl
include(FetchContent)
FetchContent_Declare(
sdl_image
GIT_REPOSITORY https://github.com/libsdl-org/SDL_image.git
GIT_TAG ${SDL_IMAGE_GIT_VERSION}
)
FetchContent_GetProperties(sdl_image)
if (NOT sdl_image_POPULATED) # Have we downloaded raylib yet?
set(FETCHCONTENT_QUIET NO)
FetchContent_Populate(sdl_image)
#message("sdl_image_LIBRARY: " ${sdl_image_LIBRARY}) # fail but define in cmake
#message("sdl_image_INCLUDE_DIR: " ${sdl_image_INCLUDE_DIR}) #pass
#message("sdl_image_SOURCE_DIR: " ${sdl_image_SOURCE_DIR}) # pass
#message("sdl_image_BINARY_DIR: " ${sdl_image_BINARY_DIR}) # pass
set(SUPPORT_JPG OFF CACHE BOOL "" FORCE)
set(SUPPORT_PNG ON CACHE BOOL "" FORCE)
set(BUILD_SHOWIMAGE OFF CACHE BOOL "" FORCE)
set(BUILD_SHARED_LIBS OFF CACHE BOOL "" FORCE)
# BUILD_SHARED_LIBS OFF is LIB
# build sdl2 image
list(APPEND CPP_INCLUDE_DIRS ${sdl_image_SOURCE_DIR})
add_subdirectory(${sdl_image_SOURCE_DIR} ${sdl_image_BINARY_DIR})
list(APPEND CPP_LIBS "SDL2_image")
endif()
endif()
endif()
#================================================
# SDL MIXER
#================================================
if (ENABLE_SDL_MIXER)
# base on environment system path variable set.
if (NOT sdl_mixer_FOUND) # If there's none, fetch and build sdl
include(FetchContent)
FetchContent_Declare(
sdl_mixer
GIT_REPOSITORY https://github.com/libsdl-org/SDL_mixer.git
GIT_TAG ${SDL_MIXER_GIT_VERSION}
)
FetchContent_GetProperties(sdl_mixer)
if (NOT sdl_mixer_POPULATED) # Have we downloaded raylib yet?
set(FETCHCONTENT_QUIET NO)
FetchContent_Populate(sdl_mixer)
#message("sdl_mixer_LIBRARY: " ${sdl_mixer_LIBRARY}) # fail but define in cmake
#message("sdl_mixer_INCLUDE_DIR: " ${sdl_mixer_INCLUDE_DIR}) #pass
#message("sdl_mixer_SOURCE_DIR: " ${sdl_mixer_SOURCE_DIR}) # pass
#message("sdl_mixer_BINARY_DIR: " ${sdl_mixer_BINARY_DIR}) # pass
set(ANDROID ON)
set(SUPPORT_OGG ON CACHE BOOL "" FORCE)
#set(SUPPORT_OGG ON CACHE BOOL "" FORCE)
# build SDL2 MIXER
list(APPEND CPP_INCLUDE_DIRS ${sdl_mixer_SOURCE_DIR}/include)
add_subdirectory(${sdl_mixer_SOURCE_DIR} ${sdl_mixer_BINARY_DIR})
list(APPEND CPP_LIBS "SDL2_mixer")
endif()
endif()
endif()
#================================================
# FLECS
#================================================
if (ENABLE_FLECS)
message("[[[=== CHECKING FLECS === ]]]")
#find_package(flecs QUIET) # Requires at least version 2.5.0
if (NOT flecs_FOUND) # If there's none, fetch and build flecs
include(FetchContent)
FetchContent_Declare(
flecs
GIT_REPOSITORY https://github.com/SanderMertens/flecs.git
GIT_TAG ${FLECS_GIT_VERSION}
)
FetchContent_GetProperties(flecs)
if (NOT flecs_POPULATED) # Have we downloaded flecs yet?
set(FETCHCONTENT_QUIET NO)
FetchContent_Populate(flecs)
# build flecs
add_subdirectory(${flecs_SOURCE_DIR} ${flecs_BINARY_DIR})
endif()
endif()
endif()
if (ENABLE_TINYOBJECTLOADER)
message("[[[=== CHECKING TINY OBJECT LOADER === ]]]")
#find_package(flecs QUIET) # Requires at least version 2.5.0
if (NOT tinyobjectloader_FOUND) # If there's none, fetch and build flecs
include(FetchContent)
FetchContent_Declare(
tinyobjectloader
GIT_REPOSITORY https://github.com/tinyobjloader/tinyobjloader.git
GIT_TAG v1.0.7
#GIT_TAG ${FLECS_GIT_VERSION}
)
FetchContent_GetProperties(tinyobjectloader)
if (NOT tinyobjectloader_POPULATED) # Have we downloaded flecs yet?
set(FETCHCONTENT_QUIET NO)
FetchContent_Populate(tinyobjectloader)
# build tinyobjectloader
list(APPEND CPP_INCLUDE_DIRS ${tinyobjectloader_SOURCE_DIR})
add_subdirectory(${tinyobjectloader_SOURCE_DIR} ${tinyobjectloader_BINARY_DIR})
list(APPEND CPP_LIBS "tinyobjloader")
endif()
endif()
endif()
if (ENABLE_GLM)
message("[[[=== CHECKING GLM === ]]]")
#find_package(flecs QUIET) # Requires at least version 2.5.0
if (NOT glm_FOUND) # If there's none, fetch and build
include(FetchContent)
FetchContent_Declare(
glm
GIT_REPOSITORY https://github.com/g-truc/glm.git
GIT_TAG ${GLM_GIT_VERSION}
)
FetchContent_GetProperties(glm)
if (NOT glm_POPULATED) # Have we downloaded yet?
set(FETCHCONTENT_QUIET NO)
FetchContent_Populate(glm)
list(APPEND CPP_INCLUDE_DIRS ${glm_SOURCE_DIR})
# build glm
add_subdirectory(${glm_SOURCE_DIR} ${glm_BINARY_DIR})
endif()
endif()
endif()
if (ENABLE_GLFW)
message("[[[=== CHECKING GLFW === ]]]")
#find_package(flecs QUIET) # Requires at least version 2.5.0
if (NOT glfw_FOUND) # If there's none, fetch and build
include(FetchContent)
FetchContent_Declare(
glfw
GIT_REPOSITORY https://github.com/glfw/glfw.git
GIT_TAG ${GLFW_GIT_VERSION}
)
FetchContent_GetProperties(glfw)
if (NOT glfw_POPULATED) # Have we downloaded yet?
set(FETCHCONTENT_QUIET NO)
FetchContent_Populate(glfw)
list(APPEND CPP_INCLUDE_DIRS ${glfw_SOURCE_DIR}/include)
set(GLFW_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE)
set(GLFW_BUILD_TESTS OFF CACHE BOOL "" FORCE)
set(GLFW_BUILD_DOCS OFF CACHE BOOL "" FORCE)
set(GLFW_INSTALL OFF CACHE BOOL "" FORCE)
# build glm
add_subdirectory(${glfw_SOURCE_DIR} ${glfw_BINARY_DIR})
list(APPEND CPP_LIBS "glfw3")
endif()
endif()
endif()
#================================================
# GL3W
#================================================
if(ENABLE_GL3W)
message("[[[=== CHECKING GL3W === ]]]")
if (NOT gl3w_FOUND) # If there's none, fetch and build sdl
include(FetchContent)
FetchContent_Declare(
gl3w
GIT_REPOSITORY https://github.com/skaslev/gl3w.git
GIT_TAG master
)
FetchContent_GetProperties(gl3w)
if (NOT gl3w_POPULATED) # Have we downloaded raylib yet?
set(FETCHCONTENT_QUIET NO)
FetchContent_Populate(gl3w)
# utility to setup the downloaded library for use
#FetchContent_MakeAvailable(gl3w)
message("GL3W GITHUB ==================================== ")
message("GL3W GITHUB SRC >>> " ${gl3w_SOURCE_DIR})
message("GL3W GITHUB BIN >>> " ${gl3w_BINARY_DIR})
list(APPEND CPP_INCLUDE_DIRS ${gl3w_BINARY_DIR}/include)
#list(APPEND CPP_INCLUDE_DIRS ${gl3w_BINARY_DIR}/src)
list(APPEND CPP_HEADER_FILES ${gl3w_BINARY_DIR}/include/GL/gl3w.h)
list(APPEND CPP_HEADER_FILES ${gl3w_BINARY_DIR}/src/gl3w.c)
add_subdirectory(${gl3w_SOURCE_DIR} ${gl3w_BINARY_DIR}) #add to build in sub dir
endif()
endif()
endif()
#================================================
# IMGUI
#================================================
if (ENABLE_IMGUI)
message("[[[=== CHECKING IMGUI === ]]]")
#find_package(imgui QUIET) # Requires at least version 2.5.0
if (NOT imgui_FOUND) # If there's none, fetch and build imgui
include(FetchContent)
FetchContent_Declare(
imgui
GIT_REPOSITORY https://github.com/ocornut/imgui.git
GIT_TAG ${IMGUI_GIT_VERSION}
)
FetchContent_GetProperties(imgui)
if (NOT imgui_POPULATED) # Have we downloaded imgui yet?
set(FETCHCONTENT_QUIET NO)
FetchContent_Populate(imgui)
#message("imgui_SOURCE_DIR: " ${imgui_SOURCE_DIR})
list(APPEND CPP_INCLUDE_DIRS ${imgui_SOURCE_DIR})
list(APPEND CPP_INCLUDE_DIRS ${imgui_SOURCE_DIR}/backends)
#INCLUDE_HEADERS
#list(APPEND INCLUDE_HEADERS ${imgui_SOURCE_DIR}/imconfig.h)
list(APPEND CPP_SOURCE_FILES ${imgui_SOURCE_DIR}/imgui.cpp)
list(APPEND CPP_HEADER_FILES ${imgui_SOURCE_DIR}/imgui.h)
list(APPEND CPP_HEADER_FILES ${imgui_SOURCE_DIR}/imgui_internal.h)
list(APPEND CPP_SOURCE_FILES ${imgui_SOURCE_DIR}/imgui_demo.cpp)
list(APPEND CPP_SOURCE_FILES ${imgui_SOURCE_DIR}/imgui_draw.cpp)
list(APPEND CPP_SOURCE_FILES ${imgui_SOURCE_DIR}/imgui_tables.cpp)
list(APPEND CPP_SOURCE_FILES ${imgui_SOURCE_DIR}/imgui_widgets.cpp)
#list(APPEND CPP_HEADER_FILES ${imgui_SOURCE_DIR}/imstb_rectpack.h)
#list(APPEND CPP_HEADER_FILES ${imgui_SOURCE_DIR}/imstb_textedit.h)
#list(APPEND CPP_HEADER_FILES ${imgui_SOURCE_DIR}/imstb_truetype.h)
#list(APPEND CPP_SOURCE_FILES ${imgui_SOURCE_DIR}/backends/imgui_impl_sdl.cpp)
#list(APPEND CPP_HEADER_FILES ${imgui_SOURCE_DIR}/backends/imgui_impl_sdl.h)
#list(APPEND CPP_SOURCE_FILES ${imgui_SOURCE_DIR}/backends/imgui_impl_opengl3.cpp)
#list(APPEND CPP_HEADER_FILES ${imgui_SOURCE_DIR}/backends/imgui_impl_opengl3.h)
list(APPEND CPP_SOURCE_FILES ${imgui_SOURCE_DIR}/backends/imgui_impl_glfw.cpp)
list(APPEND CPP_HEADER_FILES ${imgui_SOURCE_DIR}/backends/imgui_impl_glfw.h)
list(APPEND CPP_SOURCE_FILES ${imgui_SOURCE_DIR}/backends/imgui_impl_vulkan.cpp)
list(APPEND CPP_HEADER_FILES ${imgui_SOURCE_DIR}/backends/imgui_impl_vulkan.h)
endif()
endif()
endif()
#================================================
# VULKAN
#================================================
if(ENABLE_VALKUN)
message("[[[=== CHECKING VULKAN SECTION === ]]]")
#look for Vulkan SDK location
find_package(Vulkan)
if(NOT Vulkan_FOUND)
message("NOT FOUND VULKAN")
return()
endif()
if(Vulkan_FOUND)
set(VULKAN_PATH ${Vulkan_INCLUDE_DIRS})
STRING(REGEX REPLACE "/Include" "" VULKAN_PATH ${VULKAN_PATH})
endif()
# vulkan-1 library for build Vulkan application.
#set(VULKAN_LIB_LIST "vulkan-1")
list(APPEND CPP_LIBS "vulkan-1")
if(${CMAKE_SYSTEM_NAME} MATCHES "Windows")
message("VULKAN_PATH " ${VULKAN_PATH})
# Include Vulkan header files from Vulkan SDK
#include_directories(AFTER ${VULKAN_PATH}/Include)
list(APPEND CPP_INCLUDE_DIRS ${Vulkan_INCLUDE_DIRS})
# Link directory for vulkan-1
link_directories(${VULKAN_PATH}/Bin;${VULKAN_PATH}/Lib;)
endif()
endif()
#not working required third party libs
if(ENABLE_GAMENETWORKKINGSOCKETS)
message("[[[=== CHECKING GAMENETWORKKINGSOCKETS === ]]]")
if (NOT gamenetworkingsockets_FOUND) # If there's none, fetch and build flecs
include(FetchContent)
FetchContent_Declare(
gamenetworkingsockets
GIT_REPOSITORY https://github.com/ValveSoftware/GameNetworkingSockets.git
GIT_TAG ${GAMENETWORKKINGSOCKETS_GIT_VERSION}
)
FetchContent_GetProperties(flecs)
if (NOT gamenetworkingsockets_POPULATED) # Have we downloaded flecs yet?
set(FETCHCONTENT_QUIET NO)
FetchContent_Populate(gamenetworkingsockets)
set(GAMENETWORKINGSOCKETS_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE)
set(GAMENETWORKINGSOCKETS_BUILD_TESTS OFF CACHE BOOL "" FORCE)
# build gamenetworkingsockets
add_subdirectory(${gamenetworkingsockets_SOURCE_DIR} ${gamenetworkingsockets_BINARY_DIR})
endif()
endif()
endif()
if(ENABLE_GLAD)
set(GLAD_DIR ${PROJECT_SOURCE_DIR}/opengl/glad)
add_library(glad ${GLAD_DIR}/src/glad.c)
target_include_directories(glad PRIVATE ${GLAD_DIR}/include)
list(APPEND CPP_INCLUDE_DIRS ${GLAD_DIR}/include)
#target_include_directories(${PROJECT_NAME} PRIVATE ${GLAD_DIR}/include)
#target_link_libraries(${PROJECT_NAME} PUBLIC glad ${CMAKE_DL_LIBS} PRIVATE ${glfw3_LIB}) #pass
#target_link_libraries(${PROJECT_NAME} PRIVATE ${glfw3_LIB} glad ${CMAKE_DL_LIBS})
list(APPEND CPP_LIBS "glad")
endif()
if(ENABLE_GLAD2)
set(GLAD2_DIR ${PROJECT_SOURCE_DIR}/opengl/glad2)
add_library(glad ${GLAD2_DIR}/src/gl.c)
target_include_directories(glad PRIVATE ${GLAD2_DIR}/include)
list(APPEND CPP_INCLUDE_DIRS ${GLAD2_DIR}/include)
#target_include_directories(${PROJECT_NAME} PRIVATE ${GLAD_DIR}/include)
#target_link_libraries(${PROJECT_NAME} PUBLIC glad ${CMAKE_DL_LIBS} PRIVATE ${glfw3_LIB}) #pass
#target_link_libraries(${PROJECT_NAME} PRIVATE ${glfw3_LIB} glad ${CMAKE_DL_LIBS})
list(APPEND CPP_LIBS "glad")
endif()
#find_package(OpenGL REQUIRED)
#================================================
# TARGET SET UP SECTION
#================================================
#================================================
# INCLUDE DIRS
#================================================
include_directories(${CPP_INCLUDE_DIRS})
include_directories(${CPP_INCLUDE_DIRS}/src_ee_c)
include_directories(${CPP_INCLUDE_DIRS}/src_ee_cpp)
#================================================
# EXECUTE APP TEST
#================================================
#add_executable(${PROJECT_NAME} ${ENTRYPOINT})
set(EE00C
src/glfw3vulkan01.c
)
set(EE00C_Name eecbase)
set(EE00_FILES "")
set(EE00_DIR src_ee_c)
file(GLOB EE00_FILES
#"${EE00_DIR}/*.cpp"
)
add_executable(${PROJECT_NAME}
#${CPP_HEADER_FILES}
#${CPP_SOURCE_FILES}
${EE00_FILES}
${EE00C}
)
target_link_libraries(${PROJECT_NAME}
${CPP_LIBS}
)
message("END OF CMAKELIST...")
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#define VK_USE_PLATFORM_WIN32_KHR
#define GLFW_INCLUDE_NONE
#define GLFW_INCLUDE_VULKAN
#define GLFW_EXPOSE_NATIVE_WIN32
#include <GLFW/glfw3.h>
#include <GLFW/glfw3native.h>
#define CLAMP( x, min, max ) ( ( (x) < (min) ) ? (min) : ( ( (x) > (max) ) ? (max) : (x) ) )
GLFWwindow* window;
VkInstance instance;
//VkAllocationCallbacks *allocator = NULL;
const VkAllocationCallbacks* allocatorCallBacks;
VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
VkDevice device;
// Check the surface proprties and formats.
VkSurfaceCapabilitiesKHR surfaceCapabilities;
VkSurfaceKHR surface;
VkFormat swapChainImageFormat;
VkExtent2D swapChainExtent;
VkQueue presentQueue;
VkSwapchainKHR swapChain;
VkRenderPass renderPass;
VkFramebuffer frameBuffer;
VkDescriptorSetLayout descSetLayout;
VkPipelineLayout pipeLayout;
VkPipeline pipeline;
// https://stackoverflow.com/questions/18205906/api-returning-a-structure
//typedef struct {
//uint32_t graphicsFamily;
//bool isComplete(){ //nope
//return graphicsFamily.has_value();
//}
//} QueueFamilyIndices;
typedef struct{
uint32_t graphicsFamily;
uint32_t presentFamily;
} QueueFamilyIndices;
QueueFamilyIndices findQueueFamilies(VkPhysicalDevice _device) {
QueueFamilyIndices indices;
uint32_t queueFamilyCount = 0;
vkGetPhysicalDeviceQueueFamilyProperties(_device, &queueFamilyCount, NULL);
printf("_device queueFamilyCount %i\n",queueFamilyCount);
VkQueueFamilyProperties *queueFamilies = (VkQueueFamilyProperties*)malloc(sizeof(VkQueueFamilyProperties*)*queueFamilyCount);
vkGetPhysicalDeviceQueueFamilyProperties(_device, &queueFamilyCount, queueFamilies);
for(int i = 0;i < queueFamilyCount;i++){
if (queueFamilies[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) {
indices.graphicsFamily = i;
//printf("queueFamilyCount >> %i\n",queueFamilyCount);
//break;
}
//if (indices.graphicsFamily) {
//printf("queueFamilyCount BREAK\n");
//break;
//}
}
//std::vector<VkQueueFamilyProperties> queueFamilies(queueFamilyCount);
//vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, queueFamilies.data());
return indices;
}
const char* validationLayers = {
"VK_LAYER_KHRONOS_validation"
};
#ifdef NDEBUG
const bool enableValidationLayers = false;
#else
const bool enableValidationLayers = true;
#endif
// https://stackoverflow.com/questions/4180818/finding-the-length-of-a-character-array-in-c
//returns the size of a character array using a pointer to the first element of the character array
int size(const char** ptr)
{
//variable used to access the subsequent array elements.
int offset = 0;
//variable that counts the number of elements in your array
int count = 0;
//While loop that tests whether the end of the array has been reached
while (*(ptr + offset) != '\0')
{
//increment the count variable
++count;
//advance to the next element of the array
++offset;
}
//return the size of the array
return count;
}
bool checkValidationLayerSupport() {
uint32_t layerCount;
vkEnumerateInstanceLayerProperties(&layerCount, NULL);
printf("ValidationLayerSupport: %i\n",layerCount);
VkLayerProperties *availableLayers = (VkLayerProperties*)malloc(layerCount * sizeof(VkLayerProperties));
vkEnumerateInstanceLayerProperties(&layerCount, availableLayers);
printf("ValidationLayerSupport:> %i\n",layerCount);
bool layerFound = false;
for(int i =0; i < layerCount;i++){
printf("availableLayer Name: %s\n",availableLayers[i].layerName);
//if (strcmp("VK_LAYER_KHRONOS_validation",availableLayers[i].layerName) == 0){
if (strcmp(validationLayers,availableLayers[i].layerName) == 0){
printf("FOUND ValidationLayerSupport >> %i\n", i);
layerFound=true;
break;
}
}
return layerFound;
//return false;
}
const char** getRequiredExtensions() {
//void getRequiredExtensions() {
uint32_t glfwExtensionCount = 0;
const char** glfwExtensions;
// VkLayerProperties *availableLayers = (VkLayerProperties*)malloc(layerCount * sizeof(VkLayerProperties));
glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount);
//for(int i =0 ; i < glfwExtensionCount;i++){
//printf("glfwGetRequiredInstanceExtensions: %s\n", glfwExtensions[i]);
//}
if (enableValidationLayers) {
const char** extensions = (char**)malloc((glfwExtensionCount + 1) * sizeof(char**));
//extensions[0] = glfwExtensions[0];
//extensions[1] = glfwExtensions[1];
//extensions[2] = VK_EXT_DEBUG_UTILS_EXTENSION_NAME;
for(int e = 0; e < glfwExtensionCount; e++){
//printf("extensions: %s\n", extensions[e]);//will crash since it not assign string
extensions[e] = glfwExtensions[e];
//printf("glfwGetRequiredInstanceExtensions: %s\n", glfwExtensions[ii]);
}
extensions[glfwExtensionCount+1] = VK_EXT_DEBUG_UTILS_EXTENSION_NAME;
printf("enableValidationLayers TRUE\n");
//extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
return extensions;
}else{
printf("enableValidationLayers FALSE\n");
return glfwExtensions;
}
//return extensions;
}
void initVukan(){
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 instanceCreateInfo;
instanceCreateInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
instanceCreateInfo.pApplicationInfo = &appInfo;
uint32_t glfwExtensionCount = 0;
const char** glfwExtensions;
glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount);
printf("glfwExtensionCount %i\n", glfwExtensionCount);
//getRequiredExtensions();
const char** exts = getRequiredExtensions();
//size_t count = sizeof(exts);
//printf("extensions: %s\n", exts[0]);
//https://stackoverflow.com/questions/37538/how-do-i-determine-the-size-of-my-array-in-c
//printf("exts %d\n", (int) sizeof(exts));
//printf("Length of array exts %d\n", (int) (sizeof(exts) / sizeof(char**)) );
//printf("Length of array exts %d\n", (int) (strlen(exts) ) );//nope
printf("Length of array exts %d\n", (int) (size(exts) ) );
instanceCreateInfo.enabledExtensionCount = glfwExtensionCount;
instanceCreateInfo.ppEnabledExtensionNames = glfwExtensions;
instanceCreateInfo.enabledLayerCount = 0;
instanceCreateInfo.pNext = NULL;//need to variable else it will crash
printf("glfwExtensions: %s\n",glfwExtensions[0]);
printf("glfwExtensions: %s\n",glfwExtensions[1]);
//if (vkCreateInstance(&instanceCreateInfo, NULL, &instance) != VK_SUCCESS) {
if (vkCreateInstance(&instanceCreateInfo, allocatorCallBacks, &instance) != VK_SUCCESS) {
printf("failed to create instance!");
}else{
printf("create instance\n");
}
checkValidationLayerSupport();
//===============================================
//
//===============================================
// https://harrylovescode.gitbooks.io/vulkan-api/content/chap03/chap03.html
VkPhysicalDevice phys[4];
uint32_t physCount = 4;
vkEnumeratePhysicalDevices(instance, &physCount, phys);
if (physCount == 0) {
//throw std::runtime_error("failed to find GPUs with Vulkan support!");
printf("failed to find GPUs with Vulkan support!");
}
printf("physCount %i\n",physCount);
//by default it should be one graphic card
for(int i = 0;i < physCount;i++){
//physicalDevice = phys[0];
physicalDevice = phys[i];
//need to check for physicalDevices
break;
}
//physicalDevice = phys[0];
//findQueueFamilies(physicalDevice);
VkPhysicalDeviceProperties deviceProperties;
VkPhysicalDeviceFeatures deviceFeatures;
vkGetPhysicalDeviceProperties(physicalDevice, &deviceProperties);
vkGetPhysicalDeviceFeatures(physicalDevice, &deviceFeatures);
printf("deviceName: %s\n",deviceProperties.deviceName);
//printf("apiVersion: %d\n",deviceProperties.apiVersion);
//printf("apiVersion: %d.%d.%d\n",
//VK_VERSION_MAJOR(physicalProperties.apiVersion),
//VK_VERSION_MINOR(physicalProperties.apiVersion),
//VK_VERSION_PATCH(physicalProperties.apiVersion)
//);
//printf("driverVersion: %d\n",deviceProperties.driverVersion);
//printf("vendorID: %d\n",deviceProperties.vendorID);
uint32_t queueFamilyCount = 0;
vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &queueFamilyCount, NULL);
printf("QueueFamilyProperties: %i \n",queueFamilyCount);
//===============================================
// DEVICE
//===============================================
float priorities[] = { 1.0f };
VkDeviceQueueCreateInfo queueInfo;
queueInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
queueInfo.pNext = NULL;
queueInfo.flags = 0;
queueInfo.queueFamilyIndex = 0;
queueInfo.queueCount = 1;
queueInfo.pQueuePriorities = &priorities[0];
const char * enabledExtensions[] = { VK_KHR_SWAPCHAIN_EXTENSION_NAME };
VkDeviceCreateInfo deviceInfo;
deviceInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
deviceInfo.pNext = NULL;
deviceInfo.flags = 0;
deviceInfo.queueCreateInfoCount = 1;
deviceInfo.pQueueCreateInfos = &queueInfo;
//deviceInfo.enabledExtensionCount = enabledExtensions.size();
//deviceInfo.ppEnabledExtensionNames = enabledExtensions.data();
deviceInfo.enabledExtensionCount = 1;
deviceInfo.ppEnabledExtensionNames = enabledExtensions;
deviceInfo.pEnabledFeatures = NULL;
if (vkCreateDevice(physicalDevice, &deviceInfo, NULL, &device) != VK_SUCCESS) {
printf("failed to create device!");
}else{
printf("create device\n");
}
//===============================================
// SURFACE
//===============================================
VkWin32SurfaceCreateInfoKHR surfaceCreateInfo;
surfaceCreateInfo.sType = VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR;
surfaceCreateInfo.hwnd = glfwGetWin32Window(window);
surfaceCreateInfo.hinstance = GetModuleHandle(NULL);
surfaceCreateInfo.flags = 0;
surfaceCreateInfo.pNext = NULL;
if (vkCreateWin32SurfaceKHR(instance, &surfaceCreateInfo, NULL, &surface) != VK_SUCCESS){
printf("failed to create window surface!\n");
}else{
printf("create window surface!\n");
}
vkGetPhysicalDeviceSurfaceCapabilitiesKHR(physicalDevice,surface,&surfaceCapabilities);
//===============================================
// SWAPCHAIN
//===============================================
uint32_t width = 640;
uint32_t height = 480;
VkExtent2D swapchainExtent =
{
CLAMP( (uint32_t)width, surfaceCapabilities.minImageExtent.width, surfaceCapabilities.maxImageExtent.width ),
CLAMP( (uint32_t)height, surfaceCapabilities.minImageExtent.height, surfaceCapabilities.maxImageExtent.height ),
};
VkExtent2D surfaceResolution = surfaceCapabilities.currentExtent;
uint32_t surfaceFormatCount = 0;
vkGetPhysicalDeviceSurfaceFormatsKHR( physicalDevice, surface, &surfaceFormatCount, NULL );
printf("surfaceFormatCount %i\n",surfaceFormatCount);
VkSurfaceFormatKHR *surfaceFormats= (VkSurfaceFormatKHR*)malloc(sizeof(VkSurfaceFormatKHR*)*surfaceFormatCount);
vkGetPhysicalDeviceSurfaceFormatsKHR( physicalDevice, surface, &surfaceFormatCount, surfaceFormats);
VkFormat colorFormat;
if( surfaceFormatCount == 1 && surfaceFormats[0].format == VK_FORMAT_UNDEFINED ) {
colorFormat = VK_FORMAT_B8G8R8_UNORM;
} else {
colorFormat = surfaceFormats[0].format;
}
//IMAGE
swapChainImageFormat=surfaceFormats[0].format;
swapChainExtent =surfaceCapabilities.currentExtent;
VkColorSpaceKHR colorSpace;
colorSpace = surfaceFormats[0].colorSpace;
VkSurfaceFormatKHR surfaceFormat;
surfaceFormat = surfaceFormats[0];
VkPresentModeKHR presentMode = VK_PRESENT_MODE_FIFO_KHR;
uint32_t desiredImageCount = 2;
if( desiredImageCount < surfaceCapabilities.minImageCount ) {
desiredImageCount = surfaceCapabilities.minImageCount;
} else if( surfaceCapabilities.maxImageCount != 0 && desiredImageCount > surfaceCapabilities.maxImageCount ) {
desiredImageCount = surfaceCapabilities.maxImageCount;
}
VkSurfaceTransformFlagBitsKHR preTransform;
if ( surfaceCapabilities.supportedTransforms & VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR ){
preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
}else{
preTransform = surfaceCapabilities.currentTransform;
}
VkSwapchainCreateInfoKHR swapCreateInfo;
swapCreateInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
swapCreateInfo.surface = surface;
swapCreateInfo.minImageCount = desiredImageCount;
swapCreateInfo.imageFormat = colorFormat;
swapCreateInfo.imageColorSpace = colorSpace;
swapCreateInfo.imageExtent = surfaceResolution;
swapCreateInfo.imageArrayLayers = 1;
swapCreateInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
swapCreateInfo.flags = 0;
swapCreateInfo.imageSharingMode=VK_SHARING_MODE_EXCLUSIVE;
swapCreateInfo.preTransform = preTransform;
swapCreateInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
swapCreateInfo.presentMode= VK_PRESENT_MODE_FIFO_KHR;
swapCreateInfo.clipped = VK_TRUE;
swapCreateInfo.oldSwapchain = VK_NULL_HANDLE;
swapCreateInfo.pNext=NULL;
//system("pause");
//swapChain
if (vkCreateSwapchainKHR(device, &swapCreateInfo, NULL, &swapChain) != VK_SUCCESS){
printf("failed to create swapChain!\n");
}else{
printf("create swapChain!\n");
}
//===============================================
// SWAPCHAIN IMAGES NOT WORKING...
//===============================================
//this should be properly enumerated
//VkImage swapChainImages;
uint32_t swapChainImageCount;
vkGetSwapchainImagesKHR(device, swapChain, &swapChainImageCount, NULL);
printf("swapChainImageCount %i\n",swapChainImageCount);
VkImage *swapChainImages= (VkImage*)malloc(sizeof(VkImage*)*swapChainImageCount);
vkGetSwapchainImagesKHR(device, swapChain, &swapChainImageCount, swapChainImages);
VkImageView *swapChainImageViews = (VkImageView*)malloc(sizeof(VkImageView*)*swapChainImageCount);
/*
for (int ii = 0; ii < swapChainImageCount; ii++) {
VkImageViewCreateInfo imageViewCreateInfo;
imageViewCreateInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
imageViewCreateInfo.image = swapChainImages[ii];
imageViewCreateInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
imageViewCreateInfo.format = swapChainImageFormat;
imageViewCreateInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY;
imageViewCreateInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY;
imageViewCreateInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY;
imageViewCreateInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY;
imageViewCreateInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
imageViewCreateInfo.subresourceRange.baseMipLevel = 0;
imageViewCreateInfo.subresourceRange.levelCount = 1;
imageViewCreateInfo.subresourceRange.baseArrayLayer = 0;
imageViewCreateInfo.subresourceRange.layerCount = 1;
if (vkCreateImageView(device, &imageViewCreateInfo, NULL, &swapChainImageViews[ii]) != VK_SUCCESS){
printf("failed to create swapChainImageViews!\n");
}else{
printf("create swapChainImageViews!\n");
}
}
*/
// Synchronisation is needed here!
//uint32_t currentSwapImage;
//vkAcquireNextImageKHR(device, swapChain, UINT64_MAX, presentCompleteSemaphore, NULL, &currentSwapImage);
// pass appropriate creation info to create view of image
//VkImageView backbufferView;
//vkCreateImageView(device, &backbufferViewCreateInfo, NULL, &backbufferView);
VkQueue queue;
vkGetDeviceQueue(device, 0, 0, &queue);
//===============================================
// RENDER PASS not working...
//===============================================
//VkRenderPassCreateInfo renderpassCreateInfo = {
// here you will specify the total list of attachments
// (which in this case is just one, that's e.g. R8G8B8A8_UNORM)
// as well as describe a single subpass, using that attachment
// for color and with no depth-stencil attachment
//};
//VkRenderPassCreateInfo renderpassCreateInfo;
VkAttachmentDescription colorAttachment;
//colorAttachment.format = swapChainImageFormat;
colorAttachment.format = VK_FORMAT_B8G8R8A8_SRGB;
colorAttachment.samples = VK_SAMPLE_COUNT_1_BIT;
colorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
colorAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
colorAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
colorAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
colorAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
colorAttachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
VkAttachmentReference colorAttachmentRef;
colorAttachmentRef.attachment = 0;
colorAttachmentRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
VkSubpassDescription subpass;
subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
subpass.colorAttachmentCount = 1;
subpass.pColorAttachments = &colorAttachmentRef;
VkRenderPassCreateInfo renderPassInfo;
renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
renderPassInfo.attachmentCount = 1;
renderPassInfo.pAttachments = &colorAttachment;
renderPassInfo.subpassCount = 1;
renderPassInfo.pSubpasses = &subpass;
if(vkCreateRenderPass(device, &renderPassInfo, NULL, &renderPass) != VK_SUCCESS) {
printf("failed to create vkCreateRenderPass!\n");
}else{
printf("create vkCreateRenderPass\n");
}
//===============================================
// FRAME BUFFER
//===============================================
//VkFramebufferCreateInfo framebufferCreateInfo = {
// include backbufferView here to render to, and renderpass to be
// compatible with.
//};
//VkFramebufferCreateInfo framebufferCreateInfo;
//if(vkCreateFramebuffer(device, &framebufferCreateInfo, NULL, &frameBuffer) != VK_SUCCESS) {
//printf("failed to create Framebuffer!\n");
//}else{
//printf("Create Framebuffer\n");
//}
//===============================================
// Descriptor Set Layout
//===============================================
//VkDescriptorSetLayoutCreateInfo descSetLayoutCreateInfo = {
// whatever we want to match our shader. e.g. Binding 0 = UBO for a simple
// case with just a vertex shader UBO with transform data.
//};
//VkDescriptorSetLayoutCreateInfo descSetLayoutCreateInfo;
//if(vkCreateDescriptorSetLayout(device, &descSetLayoutCreateInfo, NULL, &descSetLayout) != VK_SUCCESS) {
//printf("failed to create DescriptorSetLayout!\n");
//}else{
//printf("Create DescriptorSetLayout\n");
//}
//===============================================
// Descriptor Set Layout
//===============================================
//VkPipelineCreateInfo pipeLayoutCreateInfo = {
// one descriptor set, with layout descSetLayout
//};
//VkPipelineCacheCreateInfo pipeLayoutCreateInfo;
//VkPipelineLayout pipeLayout;
//vkCreatePipelineLayout(device, &pipeLayoutCreateInfo, NULL, &pipeLayout);
//===============================================
// SHADER
//===============================================
// upload the SPIR-V shaders
//VkShaderModule vertModule, fragModule;
//vkCreateShaderModule(device, &vertModuleInfoWithSPIRV, NULL, &vertModule);
//vkCreateShaderModule(device, &fragModuleInfoWithSPIRV, NULL, &fragModule);
//===============================================
// Graphics Pipeline
//===============================================
//VkGraphicsPipelineCreateInfo pipeCreateInfo = {
// there are a LOT of sub-structures under here to fully specify
// the PSO state. It will reference vertModule, fragModule and pipeLayout
// as well as renderpass for compatibility
//};
//VkGraphicsPipelineCreateInfo pipeCreateInfo;
//VkPipeline pipeline;
//vkCreateGraphicsPipelines(device, NULL, 1, &pipeCreateInfo, NULL, &pipeline);
//===============================================
// Descriptor Pool
//===============================================
//VkDescriptorPoolCreateInfo descPoolCreateInfo = {
// the creation info states how many descriptor sets are in this pool
//};
//VkDescriptorPool descPool;
//vkCreateDescriptorPool(device, &descPoolCreateInfo, NULL, &descPool);
//===============================================
// Descriptor Set Allocate
//===============================================
//VkDescriptorSetAllocateInfo descAllocInfo = {
// from pool descPool, with layout descSetLayout
//};
//VkDescriptorSet descSet;
//vkAllocateDescriptorSets(device, &descAllocInfo, &descSet);
//===============================================
// Buffer, Memory Allocate
//===============================================
//VkBufferCreateInfo bufferCreateInfo = {
// buffer for uniform usage, of appropriate size
//};
//VkMemoryAllocateInfo memAllocInfo = {
// skipping querying for memory requirements. Let's assume the buffer
// can be placed in host visible memory.
//};
//VkBuffer buffer;
//VkDeviceMemory memory;
//vkCreateBuffer(device, &bufferCreateInfo, NULL, &buffer);
//vkAllocateMemory(device, &memAllocInfo, NULL, &memory);
//vkBindBufferMemory(device, buffer, memory, 0);
//void *data = NULL;
//vkMapMemory(device, memory, 0, VK_WHOLE_SIZE, 0, &data);
// fill data pointer with lovely transform goodness
//vkUnmapMemory(device, memory);
//===============================================
// Write Descriptor Set
//===============================================
//VkWriteDescriptorSet descriptorWrite = {
// write the details of our UBO buffer into binding 0
//};
//vkUpdateDescriptorSets(device, 1, &descriptorWrite, 0, NULL);
//===============================================
// //
//===============================================
//===============================================
//
//===============================================
}
void cleanup() {
//vkDestroySurfaceKHR(instance, surface, NULL);
//vkDestroyInstance(instance, NULL);
//vkDestroyDevice(device, NULL);
}
int main(const int argc, const char *argv[]) {
//GLFWwindow* window;
// Initialize the library
if (!glfwInit())
return -1;
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
// Create a windowed mode window and its OpenGL context
window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL);
if (!window)
{
glfwTerminate();
return -1;
}
// Setup Vulkan
if (!glfwVulkanSupported())
{
printf("GLFW: Vulkan Not Supported\n");
return 1;
}else{
printf("GLFW: Vulkan Supported\n");
}
initVukan();
//createInstance();
//pickPhysicalDevice();
//createLogicalDevice();
//createSurface();
//createSwapChain();
//createImageViews();
//createRenderPass();
//createDescriptorSetLayout();
//createGraphicsPipeline();
//createFramebuffers();
//createCommandPool();
//createVertexBuffer();
//createIndexBuffer();
//createUniformBuffers();
//createDescriptorPool();
//createDescriptorSets();
//createCommandBuffers();
//createSyncObjects();
//system("pause");
// Create Window Surface
//VkSurfaceKHR surface;
//VkResult err = glfwCreateWindowSurface(instance, window, g_Allocator, &surface);
//if (err)
//{
// Window surface creation failed
//printf("GLFW: Window surface creation failed\n");
//}else{
//printf("GLFW: Window Vulkan surface created!\n");
//}
// Create Framebuffers
//int w, h;
//glfwGetFramebufferSize(window, &w, &h);
/* Make the window's context current */
glfwMakeContextCurrent(window);
// Loop until the user closes the window
while (!glfwWindowShouldClose(window))
{
// Poll for and process events
glfwPollEvents();
//Swap front and back buffers
glfwSwapBuffers(window);
}
cleanup();
glfwDestroyWindow(window);
glfwTerminate();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment