Initial Commit

This took alot of love to build.
It is build off of the combo of the Vulkan Tutorial and Sample files
from the vulkanHPP library.

The VulkanHPP Library appears compatible with the GPL license as per it
being the Apache 2 license.
This commit is contained in:
Rebekah 2024-07-13 20:29:05 -04:00
commit a6c67dd91f
Signed by: oneechanhax
GPG Key ID: 0074BF373B812798
12 changed files with 1890 additions and 0 deletions

6
.clang-format Normal file
View File

@ -0,0 +1,6 @@
BasedOnStyle: WebKit
BreakBeforeBraces: Attach
CompactNamespaces: true
FixNamespaceComments: true
NamespaceIndentation: None
SortIncludes: Never

21
.gitignore vendored Normal file
View File

@ -0,0 +1,21 @@
# IDE
.vs/
.vscode/
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
.cache/*
# Build Files
CMakeFiles/*
CMakeCache.txt
cmake_install.cmake
Makefile
build/*
compile_commands.json

205
CMakeLists.txt Normal file
View File

@ -0,0 +1,205 @@
# VulkZample! Your example in Vulkan!
# Copyright (C) 2024 Rebekah Rowe
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
cmake_minimum_required(VERSION 3.28)
project(vulkzample LANGUAGES CXX VERSION 1.0.0)
set(CMAKE_CXX_STANDARD 23)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_EXPORT_COMPILE_COMMANDS true)
if(CMAKE_BUILD_TYPE STREQUAL "Release")
set(CMAKE_INTERPROCEDURAL_OPTIMIZATION true)
endif()
find_package(glm REQUIRED)
find_package(SDL2 REQUIRED)
find_package(SDL2pp REQUIRED)
find_package(ImageMagick REQUIRED COMPONENTS convert identify )
#find_package(GLEW REQUIRED)
find_package(Vulkan REQUIRED)
find_package(Doxygen)
add_executable(${PROJECT_NAME} "")
target_include_directories(${PROJECT_NAME} PRIVATE
Vulkan::Headers SDL2pp::Headers
)
target_link_libraries(${PROJECT_NAME} Vulkan::Vulkan SDL2pp::SDL2pp)
file(GLOB_RECURSE sources "${CMAKE_CURRENT_SOURCE_DIR}/src/*.cpp")
target_sources(${PROJECT_NAME} PRIVATE ${sources})
if (DOXYGEN_FOUND)
doxygen_add_docs(${PROJECT_NAME})
endif()
if ("${CMAKE_BUILD_TYPE}" STREQUAL "Debug")
target_compile_options(${PROJECT_NAME} PRIVATE -O0 -fno-omit-frame-pointer -ggdb -Wall -Werror -fno-common)
target_link_options(${PROJECT_NAME} PRIVATE -O0 -fno-omit-frame-pointer -ggdb -Wall -Werror -fno-common)
if (ENABLE_ASAN)
target_compile_options(${PROJECT_NAME} PRIVATE -fsanitize=address)
target_link_options(${PROJECT_NAME} PRIVATE -fsanitize=address)
endif()
endif()
if (ENABLE_TESTS)
message(STATUS "Tests Enabled, Building with Testing!")
target_compile_definitions(${PROJECT_NAME} PRIVATE -DENABLE_TESTS=1)
endif()
# SHADER COMPILATION
function(CommandCompileGLSLToSPV file_in)
cmake_path(GET file_in FILENAME filename)
cmake_path(GET file_in PARENT_PATH filepath)
cmake_path(GET file_in STEM LAST_ONLY filepath_without_glsl_ext)
cmake_path(GET filepath_without_glsl_ext EXTENSION LAST_ONLY file_shader_type)
if(file_shader_type MATCHES "^\\..*")
string(REGEX REPLACE "^\\." "" file_shader_type "${file_shader_type}") # Remove the dot: ".vertex"
endif()
add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/${filename}.spv
WORKING_DIRECTORY ${filepath}
COMMAND Vulkan::glslc
ARGS -fshader-stage="${file_shader_type}" ${filename} -o ${CMAKE_CURRENT_BINARY_DIR}/${filename}.spv
DEPENDS ${file_in}
POST_BUILD)
set(FUNC_RET ${CMAKE_CURRENT_BINARY_DIR}/${filename}.spv PARENT_SCOPE)
endfunction()
function(CommandCompileMassGSGLShaders)
set(SHADILER_OBJ_RET "")
foreach(file_path ${ARGV})
CommandCompileGLSLToSPV(${file_path})
list(APPEND SHADILER_OBJ_RET "${FUNC_RET}")
endforeach()
set(SHADILER_OBJ_RET "${SHADILER_OBJ_RET}" PARENT_SCOPE)
endfunction()
file(GLOB_RECURSE shaders_frag "${CMAKE_CURRENT_SOURCE_DIR}/shader/*.frag.glsl")
file(GLOB_RECURSE shaders_vertex "${CMAKE_CURRENT_SOURCE_DIR}/shader/*.vertex.glsl")
CommandCompileMassGSGLShaders(${shaders_frag} ${shaders_vertex})
# EMBED CMAKE
function(CommandConvertImageToRgba file_in)
cmake_path(GET file_in FILENAME filename)
cmake_path(GET file_in PARENT_PATH filepath)
add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/${filename}.rgba
WORKING_DIRECTORY ${filepath}
COMMAND ${ImageMagick_convert_EXECUTABLE}
ARGS ${filename} -depth 8 -format rgba ${CMAKE_CURRENT_BINARY_DIR}/${filename}.rgba
DEPENDS ${file_in}
POST_BUILD)
set(FUNC_RET ${CMAKE_CURRENT_BINARY_DIR}/${filename}.rgba PARENT_SCOPE)
endfunction()
function(CommandConvertToObjcopy file_in)
cmake_path(GET file_in FILENAME filename)
cmake_path(GET file_in PARENT_PATH filepath)
add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/${filename}.o
WORKING_DIRECTORY ${filepath}
COMMAND ${CMAKE_OBJCOPY}
ARGS --input binary --output elf64-x86-64 --binary-architecture i386 ${filename} ${CMAKE_CURRENT_BINARY_DIR}/${filename}.o
DEPENDS ${file_in}
POST_BUILD)
set(FUNC_RET ${CMAKE_CURRENT_BINARY_DIR}/${filename}.o PARENT_SCOPE)
endfunction()
function(CommandConvertImageToObject file_in)
CommandConvertImageToRgba("${file_in}")
CommandConvertToObjcopy(${FUNC_RET})
set(FUNC_RET ${FUNC_RET} PARENT_SCOPE)
endfunction()
function(EmbedResources)
set(EMBED_HEADER_DIR "${CMAKE_CURRENT_BINARY_DIR}/")
set(EMBED_HEADER_DIR "${EMBED_HEADER_DIR}" PARENT_SCOPE)
file(WRITE "${EMBED_HEADER_DIR}/embed_resources.hpp" "
/* AUTOGENERATED CMAKE EMBEDED FILE HEADER!!! DO NOT EDIT THIS FILE!!!
ALL CHANGES WILL BE WIPED!!! */
#include <cstddef>
#include <iterator>
class EmbededResource {
public:
constexpr EmbededResource(const std::byte* _begin, const std::byte* _end)
: begin(_begin), end(_end), size(std::distance(_begin, _end)) {
//static_assert(this->begin != nullptr && this->end != nullptr);
}
const std::byte* const begin;
const std::byte* const end;
std::size_t size;
};
class EmbededImage {
public:
constexpr EmbededImage(std::size_t _width, std::size_t _height, EmbededResource _data)\
: width(_width), height(_height), data(_data) {
//static_assert(this->width != 0 && this->height);
}
const std::size_t width;
const std::size_t height;
const EmbededResource data;
};
")
set(EMBED_OBJ_RET "")
foreach(file_path ${ARGV})
cmake_path(GET file_path EXTENSION LAST_ONLY file_ext)
set(type "embed")
if (file_ext STREQUAL ".jpg")
set(type "image")
endif()
if (file_ext STREQUAL ".png")
set(type "image")
endif()
if (type STREQUAL "image")
CommandConvertImageToObject(${file_path})
elseif (type STREQUAL "embed")
CommandConvertToObjcopy(${file_path})
endif()
list(APPEND EMBED_OBJ_RET "${FUNC_RET}")
cmake_path(GET FUNC_RET STEM LAST_ONLY obj_filestem)
string(REPLACE "." "_" obj_cleaned_name "${obj_filestem}")
file(APPEND "${EMBED_HEADER_DIR}/embed_resources.hpp" "extern const std::byte _binary_${obj_cleaned_name}_start; extern const std::byte _binary_${obj_cleaned_name}_end; \n")
if (type STREQUAL "image")
cmake_path(GET file_path PARENT_PATH file_parent)
cmake_path(GET file_path FILENAME file_name)
exec_program("${ImageMagick_identify_EXECUTABLE}" "${file_parent}"
ARGS -format "%[fx:w]" "${file_name}"
OUTPUT_VARIABLE image_width)
exec_program("${ImageMagick_identify_EXECUTABLE}" "${file_parent}"
ARGS -format "%[fx:h]" "${file_name}"
OUTPUT_VARIABLE image_height)
file(APPEND "${EMBED_HEADER_DIR}/embed_resources.hpp" "inline EmbededImage embeded_${obj_cleaned_name}(${image_width}, ${image_height}, EmbededResource(&_binary_${obj_cleaned_name}_start, &_binary_${obj_cleaned_name}_end)); \n")
elseif (type STREQUAL "embed")
file(APPEND "${EMBED_HEADER_DIR}/embed_resources.hpp" "inline EmbededResource embeded_${obj_cleaned_name}(&_binary_${obj_cleaned_name}_start, &_binary_${obj_cleaned_name}_end); \n")
endif()
endforeach()
set(EMBED_OBJ_RET "${EMBED_OBJ_RET}" PARENT_SCOPE)
endfunction()
EmbedResources(${SHADILER_OBJ_RET})
target_sources(${PROJECT_NAME} PRIVATE ${EMBED_OBJ_RET})
target_include_directories(${PROJECT_NAME} PUBLIC "${EMBED_HEADER_DIR}")

25
build.sh Normal file
View File

@ -0,0 +1,25 @@
#/bin/sh -e
SCRIPT_PATH="$(readlink -f "$0")"
SCRIPT_DIR="$(dirname "$SCRIPT_PATH")"
cd "$SCRIPT_DIR"
if [ -z "$ENABLE_DEBUG" ]; then
EXT_CMAKE_OPTIONS="-DCMAKE_BUILD_TYPE=Release"
else
EXT_CMAKE_OPTIONS="-DCMAKE_BUILD_TYPE=Debug"
if [ -n "$ENABLE_ASAN" ]; then
EXT_CMAKE_OPTIONS="$EXT_CMAKE_OPTIONS -DENABLE_ASAN=ON"
else
EXT_CMAKE_OPTIONS="$EXT_CMAKE_OPTIONS -DENABLE_ASAN=OFF"
fi
fi
if [ -n "$ENABLE_TESTS" ]; then
EXT_CMAKE_OPTIONS="$EXT_CMAKE_OPTIONS -DENABLE_TESTS=ON"
else
EXT_CMAKE_OPTIONS="$EXT_CMAKE_OPTIONS -DENABLE_TESTS=OFF"
fi
cmake $EXT_CMAKE_OPTIONS -S ./ -B ./build/
cmake --build ./build/ --parallel

11
clean.sh Normal file
View File

@ -0,0 +1,11 @@
#/bin/sh -e
SCRIPT_PATH="$(readlink -f "$0")"
SCRIPT_DIR="$(dirname "$SCRIPT_PATH")"
cd "$SCRIPT_DIR"
if [ -d "build/" ]; then
echo "Cleaning Build Dir"
rm -r build/
fi

675
license.md Normal file
View File

@ -0,0 +1,675 @@
### GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
<https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this
license document, but changing it is not allowed.
### Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom
to share and change all versions of a program--to make sure it remains
free software for all its users. We, the Free Software Foundation, use
the GNU General Public License for most of our software; it applies
also to any other work released this way by its authors. You can apply
it to your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you
have certain responsibilities if you distribute copies of the
software, or if you modify it: responsibilities to respect the freedom
of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the
manufacturer can do so. This is fundamentally incompatible with the
aim of protecting users' freedom to change the software. The
systematic pattern of such abuse occurs in the area of products for
individuals to use, which is precisely where it is most unacceptable.
Therefore, we have designed this version of the GPL to prohibit the
practice for those products. If such problems arise substantially in
other domains, we stand ready to extend this provision to those
domains in future versions of the GPL, as needed to protect the
freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish
to avoid the special danger that patents applied to a free program
could make it effectively proprietary. To prevent this, the GPL
assures that patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
### TERMS AND CONDITIONS
#### 0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds
of works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of
an exact copy. The resulting work is called a "modified version" of
the earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user
through a computer network, with no transfer of a copy, is not
conveying.
An interactive user interface displays "Appropriate Legal Notices" to
the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
#### 1. Source Code.
The "source code" for a work means the preferred form of the work for
making modifications to it. "Object code" means any non-source form of
a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users can
regenerate automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same
work.
#### 2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey,
without conditions so long as your license otherwise remains in force.
You may convey covered works to others for the sole purpose of having
them make modifications exclusively for you, or provide you with
facilities for running those works, provided that you comply with the
terms of this License in conveying all material for which you do not
control copyright. Those thus making or running the covered works for
you must do so exclusively on your behalf, under your direction and
control, on terms that prohibit them from making any copies of your
copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under the
conditions stated below. Sublicensing is not allowed; section 10 makes
it unnecessary.
#### 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such
circumvention is effected by exercising rights under this License with
respect to the covered work, and you disclaim any intention to limit
operation or modification of the work as a means of enforcing, against
the work's users, your or third parties' legal rights to forbid
circumvention of technological measures.
#### 4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
#### 5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these
conditions:
- a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
- b) The work must carry prominent notices stating that it is
released under this License and any conditions added under
section 7. This requirement modifies the requirement in section 4
to "keep intact all notices".
- c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
- d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
#### 6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of
sections 4 and 5, provided that you also convey the machine-readable
Corresponding Source under the terms of this License, in one of these
ways:
- a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
- b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the Corresponding
Source from a network server at no charge.
- c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
- d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
- e) Convey the object code using peer-to-peer transmission,
provided you inform other peers where the object code and
Corresponding Source of the work are being offered to the general
public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal,
family, or household purposes, or (2) anything designed or sold for
incorporation into a dwelling. In determining whether a product is a
consumer product, doubtful cases shall be resolved in favor of
coverage. For a particular product received by a particular user,
"normally used" refers to a typical or common use of that class of
product, regardless of the status of the particular user or of the way
in which the particular user actually uses, or expects or is expected
to use, the product. A product is a consumer product regardless of
whether the product has substantial commercial, industrial or
non-consumer uses, unless such uses represent the only significant
mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to
install and execute modified versions of a covered work in that User
Product from a modified version of its Corresponding Source. The
information must suffice to ensure that the continued functioning of
the modified object code is in no case prevented or interfered with
solely because modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or
updates for a work that has been modified or installed by the
recipient, or for the User Product in which it has been modified or
installed. Access to a network may be denied when the modification
itself materially and adversely affects the operation of the network
or violates the rules and protocols for communication across the
network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
#### 7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders
of that material) supplement the terms of this License with terms:
- a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
- b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
- c) Prohibiting misrepresentation of the origin of that material,
or requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
- d) Limiting the use for publicity purposes of names of licensors
or authors of the material; or
- e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
- f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions
of it) with contractual assumptions of liability to the recipient,
for any liability that these contractual assumptions directly
impose on those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions; the
above requirements apply either way.
#### 8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your license
from a particular copyright holder is reinstated (a) provisionally,
unless and until the copyright holder explicitly and finally
terminates your license, and (b) permanently, if the copyright holder
fails to notify you of the violation by some reasonable means prior to
60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
#### 9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run
a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
#### 10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
#### 11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims owned
or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within the
scope of its coverage, prohibits the exercise of, or is conditioned on
the non-exercise of one or more of the rights that are specifically
granted under this License. You may not convey a covered work if you
are a party to an arrangement with a third party that is in the
business of distributing software, under which you make payment to the
third party based on the extent of your activity of conveying the
work, and under which the third party grants, to any of the parties
who would receive the covered work from you, a discriminatory patent
license (a) in connection with copies of the covered work conveyed by
you (or copies made from those copies), or (b) primarily for and in
connection with specific products or compilations that contain the
covered work, unless you entered into that arrangement, or that patent
license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
#### 12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under
this License and any other pertinent obligations, then as a
consequence you may not convey it at all. For example, if you agree to
terms that obligate you to collect a royalty for further conveying
from those to whom you convey the Program, the only way you could
satisfy both those terms and this License would be to refrain entirely
from conveying the Program.
#### 13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
#### 14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions
of the GNU General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in
detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies that a certain numbered version of the GNU General Public
License "or any later version" applies to it, you have the option of
following the terms and conditions either of that numbered version or
of any later version published by the Free Software Foundation. If the
Program does not specify a version number of the GNU General Public
License, you may choose any version ever published by the Free
Software Foundation.
If the Program specifies that a proxy can decide which future versions
of the GNU General Public License can be used, that proxy's public
statement of acceptance of a version permanently authorizes you to
choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
#### 15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT
WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND
PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE
DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR
CORRECTION.
#### 16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR
CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES
ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT
NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR
LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM
TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER
PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
#### 17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
### How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these
terms.
To do so, attach the following notices to the program. It is safest to
attach them to the start of each source file to most effectively state
the exclusion of warranty; and each file should have at least the
"copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper
mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands \`show w' and \`show c' should show the
appropriate parts of the General Public License. Of course, your
program's commands might be different; for a GUI interface, you would
use an "about box".
You should also get your employer (if you work as a programmer) or
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. For more information on this, and how to apply and follow
the GNU GPL, see <https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your
program into proprietary programs. If your program is a subroutine
library, you may consider it more useful to permit linking proprietary
applications with the library. If this is what you want to do, use the
GNU Lesser General Public License instead of this License. But first,
please read <https://www.gnu.org/licenses/why-not-lgpl.html>.

9
readme.md Normal file
View File

@ -0,0 +1,9 @@
# VulkZample
a Pure C++ (or as pure as C++ gets) Vulkan Renderer Example using SDL2.
### How to run this project
```
sh build.sh
sh run.sh
```

24
run.sh Executable file
View File

@ -0,0 +1,24 @@
#!/bin/sh -e
SCRIPT_PATH="$(readlink -f "$0")"
SCRIPT_DIR="$(dirname "$SCRIPT_PATH")"
cd "$SCRIPT_DIR"
if [ ! -d "build/" ]; then
echo "Build the project first before attempting to run it."
exit 404
fi
cd build/
CODE_DEBUGGER=''
if [ -n "$ENABLE_DEBUG" ]; then
CODE_DEBUGGER='gdb'
fi
if [ -n "$ENABLE_SWRAST" ]; then
export VK_DRIVER_FILES='/usr/share/vulkan/icd.d/lvp_icd.x86_64.json'
export LIBGL_ALWAYS_SOFTWARE=1
export __GLX_VENDOR_LIBRARY_NAME=mesa
fi
$CODE_DEBUGGER ./vulkzample

27
shader/shader.frag.glsl Normal file
View File

@ -0,0 +1,27 @@
/*
* VulkZample
* Copyright (C) 2024 Rebekah Rowe
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#version 450
layout(location = 0) out vec4 outColor;
layout(location = 0) in vec3 fragColor;
void main() {
outColor = vec4(fragColor, 1.0);
}

39
shader/shader.vertex.glsl Normal file
View File

@ -0,0 +1,39 @@
/*
* VulkZample
* Copyright (C) 2024 Rebekah Rowe
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#version 450
layout(location = 0) out vec3 fragColor;
vec2 positions[3] = vec2[](
vec2(0.0, -0.5),
vec2(0.5, 0.5),
vec2(-0.5, 0.5)
);
vec3 colors[3] = vec3[](
vec3(1.0, 0.0, 0.0),
vec3(0.0, 1.0, 0.0),
vec3(0.0, 0.0, 1.0)
);
void main() {
gl_Position = vec4(positions[gl_VertexIndex], 0.0, 1.0);
fragColor = colors[gl_VertexIndex];
}

812
src/main.cpp Normal file
View File

@ -0,0 +1,812 @@
/*
* VulkZample
* Copyright (C) 2024 Rebekah Rowe
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#define VULKAN_HPP_NO_CONSTRUCTORS
#include <vulkan/vulkan_raii.hpp>
#include <SDL2/SDL.h>
#include <SDL2/SDL_vulkan.h>
#include <SDL2pp/SDL2pp.hh>
#define GLM_FORCE_DEPTH_ZERO_TO_ONE
#include <glm/vec4.hpp>
#include <glm/mat4x4.hpp>
#include <embed_resources.hpp>
#include <iostream>
#include <memory>
#include <vector>
#include <string_view>
#include <set>
static constexpr bool fatal_errors = true;
#define ENABLE_VULKAN_VALIDATION true
static constexpr bool vulkan_enable_validation_layers =
#if defined(ENABLE_VULKAN_VALIDATION)
true;
#else
false;
#endif
#if defined(ENABLE_VULKAN_VALIDATION)
static VKAPI_ATTR VkBool32 VKAPI_CALL VulkanDebugCallback(
VkDebugUtilsMessageSeverityFlagBitsEXT message_severity,
VkDebugUtilsMessageTypeFlagsEXT message_type,
const VkDebugUtilsMessengerCallbackDataEXT* callback_data,
void* user_data);
/*static VKAPI_ATTR VkBool32 VKAPI_CALL VulkanReportCallback(
VkDebugReportFlagsEXT flags,
VkDebugReportObjectTypeEXT type,
uint64_t obj,
size_t location,
int32_t code,
const char* layer_prefix,
const char* msg,
void* user_data);*/
#endif
class VulkanExampleApplication {
std::unique_ptr<SDL2pp::SDL> libsdl;
std::unique_ptr<SDL2pp::Window> window;
std::unique_ptr<vk::raii::Context> vk_ctx;
std::unique_ptr<vk::raii::Instance> vk_inst;
std::unique_ptr<vk::raii::DebugUtilsMessengerEXT> vk_debug_utils_messenger;
// std::unique_ptr<vk::raii::DebugReportCallbackEXT> vk_debug_report_callback;
std::unique_ptr<vk::raii::PhysicalDevice> vk_gfx_card;
std::unique_ptr<vk::raii::SurfaceKHR> vk_screen_surface;
std::unique_ptr<vk::raii::Device> vk_gpu;
std::unique_ptr<vk::raii::Queue> vk_queue_graphics;
std::unique_ptr<vk::raii::Queue> vk_queue_present;
std::unique_ptr<vk::raii::SwapchainKHR> vk_swapchain;
std::unique_ptr<vk::raii::Image> vk_depth_image;
vk::Format vk_swapchain_image_format;
vk::Extent2D vk_swapchain_extent;
std::vector<vk::raii::ImageView> vk_swapchain_image_views;
std::vector<vk::raii::Framebuffer> vk_swapchain_framebuffers;
std::unique_ptr<vk::raii::ShaderModule> vk_shader_vertex;
std::unique_ptr<vk::raii::ShaderModule> vk_shader_frag;
std::unique_ptr<vk::raii::PipelineLayout> vk_pipeline_layout;
std::unique_ptr<vk::raii::RenderPass> vk_render_pass;
std::unique_ptr<vk::raii::Pipeline> vk_pipeline;
std::unique_ptr<vk::raii::CommandPool> vk_command_pool;
std::unique_ptr<vk::raii::CommandBuffers> vk_command_buffers;
std::unique_ptr<vk::raii::DescriptorSetLayout> vk_descriptor_set_layout;
std::unique_ptr<vk::raii::DescriptorPool> vk_descriptor_pool;
std::unique_ptr<vk::raii::DescriptorSets> vk_descriptor_sets;
std::unique_ptr<vk::raii::Fence> vk_fence_in_flight;
std::unique_ptr<vk::raii::Semaphore> vk_semephore_image_available;
std::unique_ptr<vk::raii::Semaphore> vk_semephore_render_finished;
struct VulkanDeviceQueriedInfo {
std::unique_ptr<vk::raii::SurfaceKHR> screen_surface;
std::optional<std::uint32_t> graphics_family;
std::optional<std::uint32_t> present_family;
vk::SurfaceCapabilitiesKHR surface_capabilities;
std::vector<vk::PresentModeKHR> surface_present_modes;
std::vector<vk::SurfaceFormatKHR> surface_formats;
bool IsGoodCard() const {
return this->graphics_family.has_value() && this->present_family.has_value() && this->screen_surface && !surface_present_modes.empty() && !surface_formats.empty();
}
} vk_physical_card_info;
public:
VulkanExampleApplication() {
try { // try me // all the code is in init :O boo hoo, ill shove all ur ram out of scope ASAP i can, dont seperate them, just scope them instead dumb dumb.
{ // Window init
this->libsdl = std::make_unique<SDL2pp::SDL>(SDL_INIT_VIDEO);
SDL_Vulkan_LoadLibrary(nullptr); // optional
this->window = std::make_unique<SDL2pp::Window>(this->app_name, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 800, 480, SDL_WINDOW_VULKAN | SDL_WINDOW_SHOWN);
}
{ // Vulkan Init
this->vk_ctx = std::make_unique<vk::raii::Context>();
#if defined(ENABLE_VULKAN_VALIDATION)
const std::vector<vk::LayerProperties> available_layers = this->vk_ctx->enumerateInstanceLayerProperties();
for (const auto& required_layer_name : required_vulkan_validation_layers) {
const auto find_wanted_layer = std::find_if(available_layers.begin(), available_layers.end(), [&](const auto& layer_to_test) { return std::string_view(layer_to_test.layerName) == required_layer_name; });
if (find_wanted_layer == available_layers.end())
throw std::runtime_error("validation layers requested, but not available!");
}
#endif
}
{ // Setup vulkan
constexpr vk::ApplicationInfo app_info {
.pApplicationName = this->app_name,
.applicationVersion = VK_MAKE_VERSION(1, 0, 0),
.pEngineName = "No Engine",
.engineVersion = VK_MAKE_VERSION(1, 0, 0),
.apiVersion = VK_API_VERSION_1_3
};
const std::vector<const char*> required_extensions = [this]() -> std::vector<const char*> {
std::uint32_t extension_count = 0;
SDL_Vulkan_GetInstanceExtensions(this->window->Get(), &extension_count, nullptr);
std::vector<const char*> ret_extensions(extension_count);
SDL_Vulkan_GetInstanceExtensions(this->window->Get(), &extension_count, ret_extensions.data());
if (vulkan_enable_validation_layers)
ret_extensions.push_back(vk::EXTDebugUtilsExtensionName);
return ret_extensions;
}();
const vk::InstanceCreateInfo instance_create_info {
#if defined(ENABLE_VULKAN_VALIDATION)
.pNext = &debug_message_info,
#endif
.pApplicationInfo = &app_info,
.enabledLayerCount = required_vulkan_validation_layers.size(),
.ppEnabledLayerNames = required_vulkan_validation_layers.data(),
.enabledExtensionCount = static_cast<std::uint32_t>(required_extensions.size()),
.ppEnabledExtensionNames = required_extensions.data()
};
this->vk_inst = std::make_unique<vk::raii::Instance>(*this->vk_ctx, instance_create_info);
#if defined(ENABLE_VULKAN_VALIDATION)
this->vk_debug_utils_messenger = std::make_unique<vk::raii::DebugUtilsMessengerEXT>(*this->vk_inst, debug_message_info);
// SDL specific, optional (does it even work?)
/*constexpr vk::DebugReportCallbackCreateInfoEXT debug_callback_create_info = {
.flags = vk::DebugReportFlagBitsEXT::eError | vk::DebugReportFlagBitsEXT::eWarning,
.pfnCallback = VulkanReportCallback
};
static const auto SDL2_vkCreateDebugReportCallbackEXT = (PFN_vkCreateDebugReportCallbackEXT)SDL_Vulkan_GetVkGetInstanceProcAddr(); // https://gist.github.com/YukiSnowy/dc31f47448ac61dd6aedee18b5d53858
assert(SDL2_vkCreateDebugReportCallbackEXT);
VkDebugReportCallbackEXT debug_report_callback;
SDL2_vkCreateDebugReportCallbackEXT(**this->vk_inst, &static_cast<const VkDebugReportCallbackCreateInfoEXT&>(debug_callback_create_info), 0, &debug_report_callback);
this->vk_debug_report_callback = std::make_unique<vk::raii::DebugReportCallbackEXT>(*this->vk_inst, debug_report_callback);*/
#endif
}
{ // Pick device
auto physical_cards = vk::raii::PhysicalDevices(*this->vk_inst);
if (physical_cards.empty())
throw std::runtime_error("failed to find GFX CARD with Vulkan support!");
// int top_gpu_count =
std::optional<VulkanDeviceQueriedInfo> found_search_info;
const decltype(physical_cards.begin()) found_physical_card = std::find_if(physical_cards.begin(), physical_cards.end(), [&](const auto& physical_card) -> bool {
const auto VulkanIsDeviceSuitable = [this](const vk::PhysicalDevice& gfx_card) -> VulkanDeviceQueriedInfo {
VulkanDeviceQueriedInfo ret; // accessing the class members may happen before they exist, avoid using this->gfx_card as it will fail! - debugging it is p easy but it happens more than you think!
const auto device_properties = gfx_card.getProperties();
const auto device_features = gfx_card.getFeatures();
const auto queue_families = gfx_card.getQueueFamilyProperties();
if (!(((allow_swrast && device_properties.deviceType == vk::PhysicalDeviceType::eCpu) || device_properties.deviceType == vk::PhysicalDeviceType::eDiscreteGpu) && device_features.geometryShader))
return ret;
const auto found_graphics_family = std::find_if(queue_families.begin(), queue_families.end(), [](const auto& queue_family_to_test) {
return queue_family_to_test.queueFlags & vk::QueueFlagBits::eGraphics;
});
if (found_graphics_family == queue_families.end())
return ret;
const auto found_graphics_family_idx = std::distance(queue_families.begin(), found_graphics_family);
ret.graphics_family = found_graphics_family_idx;
const auto found_screen_surface = VulkanCreateSurface(*this->window, *this->vk_inst);
const auto found_present_family = gfx_card.getSurfaceSupportKHR(found_graphics_family_idx, **found_screen_surface) ? found_graphics_family : [&]() -> decltype(queue_families)::const_iterator { // https://github.com/KhronosGroup/Vulkan-Hpp/blob/6f72ceca515d59f40d64b64cf2734f6261e1f9f2/RAII_Samples/05_InitSwapchain/05_InitSwapchain.cpp#L50
decltype(queue_families)::const_iterator queue_family_to_test;
for (queue_family_to_test = queue_families.begin(); queue_family_to_test != queue_families.end(); queue_family_to_test++) {
const auto queue_family_idx_to_test = std::distance(queue_families.begin(), queue_family_to_test);
if ((queue_family_to_test->queueFlags & vk::QueueFlagBits::eGraphics) && gfx_card.getSurfaceSupportKHR(queue_family_idx_to_test, **found_screen_surface))
break;
}
if (queue_family_to_test == queue_families.end()) {
for (queue_family_to_test = queue_families.begin(); queue_family_to_test != queue_families.end(); queue_family_to_test++) {
const auto queue_family_idx_to_test = std::distance(queue_families.begin(), queue_family_to_test);
if (gfx_card.getSurfaceSupportKHR(queue_family_idx_to_test, **found_screen_surface))
break;
}
}
return queue_family_to_test;
}();
if (found_present_family == queue_families.end())
return ret;
const auto found_present_family_idx = std::distance(queue_families.begin(), found_present_family);
ret.present_family = found_present_family_idx;
const auto VulkanCheckDeviceExtensionSupport = [](const vk::PhysicalDevice& gfx_card) -> bool {
const auto available_extensions = gfx_card.enumerateDeviceExtensionProperties();
for (const std::string_view required_ext_name : required_vulkan_device_extensions) {
const auto find_wanted_ext = std::find_if(available_extensions.begin(), available_extensions.end(), [&](const auto& ext_to_test) { return std::string_view(ext_to_test.extensionName) == required_ext_name; });
if (find_wanted_ext == available_extensions.end())
return false;
}
return true;
};
if (!VulkanCheckDeviceExtensionSupport(gfx_card))
return ret;
ret.surface_capabilities = gfx_card.getSurfaceCapabilitiesKHR(*found_screen_surface);
const auto surface_present_modes = gfx_card.getSurfacePresentModesKHR(*found_screen_surface);
const auto surface_formats = gfx_card.getSurfaceFormatsKHR(*found_screen_surface);
if (surface_formats.empty() || surface_present_modes.empty())
return ret;
ret.screen_surface = std::make_unique<vk::raii::SurfaceKHR>(std::move(*found_screen_surface));
ret.surface_formats = std::move(surface_formats);
ret.surface_present_modes = std::move(surface_present_modes);
return ret;
};
auto _found_search_info = VulkanIsDeviceSuitable(physical_card);
const auto good_card = _found_search_info.IsGoodCard();
if (good_card) // if (found_search_info.ranking > top_gpu_count) {top_gpu_count = found_search_info.ranking}
found_search_info = std::move(_found_search_info);
return good_card;
});
if (found_physical_card == physical_cards.end())
throw std::runtime_error("Unable to choose a Suitable GRAPHICS DEVICE from the ones availiable!");
this->vk_gfx_card = std::make_unique<vk::raii::PhysicalDevice>(std::move(*found_physical_card));
this->vk_screen_surface = std::move(found_search_info->screen_surface);
this->vk_physical_card_info = std::move(*found_search_info);
}
{ // Setup device
static constexpr float queue_priority = 1.0f;
const std::vector<vk::DeviceQueueCreateInfo> device_queue_create_infos = [](const std::uint32_t graphics_family, const std::uint32_t present_family) {
std::vector<vk::DeviceQueueCreateInfo> device_queues_we_need;
const auto GetQueuesToUse = [&graphics_family, &present_family]() {
std::vector<std::uint32_t> wanted_queues = { graphics_family };
if (graphics_family != present_family)
wanted_queues.push_back(present_family);
return wanted_queues;
};
for (const std::uint32_t queue_family : GetQueuesToUse()) {
const vk::DeviceQueueCreateInfo device_queue_create_info {
.queueFamilyIndex = queue_family,
.queueCount = 1,
.pQueuePriorities = &queue_priority
};
device_queues_we_need.push_back(device_queue_create_info);
}
return device_queues_we_need;
}(this->vk_physical_card_info.graphics_family.value(), this->vk_physical_card_info.present_family.value());
constexpr vk::PhysicalDeviceFeatures device_features {};
const vk::DeviceCreateInfo device_create_info {
.queueCreateInfoCount = static_cast<uint32_t>(device_queue_create_infos.size()),
.pQueueCreateInfos = device_queue_create_infos.data(),
.enabledExtensionCount = static_cast<uint32_t>(required_vulkan_device_extensions.size()),
.ppEnabledExtensionNames = required_vulkan_device_extensions.data(),
.pEnabledFeatures = &device_features,
};
this->vk_gpu = std::make_unique<vk::raii::Device>(*this->vk_gfx_card, device_create_info);
this->vk_queue_graphics = std::make_unique<vk::raii::Queue>(*this->vk_gpu, this->vk_physical_card_info.graphics_family.value(), 0);
this->vk_queue_present = std::make_unique<vk::raii::Queue>(*this->vk_gpu, this->vk_physical_card_info.present_family.value(), 0);
}
{ // Swapchain setup
const vk::SurfaceFormatKHR surface_format = [](const std::vector<vk::SurfaceFormatKHR>& available_formats) -> vk::SurfaceFormatKHR {
vk::SurfaceFormatKHR chosen_format = available_formats.at(0);
if (available_formats.size() == 1) {
if (available_formats[0].format == vk::Format::eUndefined) {
chosen_format.format = required_vulkan_default_format;
chosen_format.colorSpace = required_vulkan_default_screen_colorspace;
}
} else {
for (const auto& format_we_want : required_vulkan_screen_formats) {
const auto find = std::find_if(available_formats.begin(), available_formats.end(), [&](const auto& format_to_test) { return format_to_test.format == format_we_want && format_to_test.colorSpace == required_vulkan_screen_colorspace; });
if (find != available_formats.end()) {
chosen_format = *find;
break;
}
}
}
return chosen_format;
}(this->vk_physical_card_info.surface_formats);
const vk::PresentModeKHR present_mode = [](const std::vector<vk::PresentModeKHR>& available_present_modes) -> vk::PresentModeKHR {
for (const auto& present_mode_to_test : available_present_modes)
if (present_mode_to_test == vk::PresentModeKHR::eMailbox)
return present_mode_to_test;
return vk::PresentModeKHR::eFifo;
}(this->vk_physical_card_info.surface_present_modes);
const vk::Extent2D extent = [this](const vk::SurfaceCapabilitiesKHR& capabilities) -> vk::Extent2D {
if (capabilities.currentExtent.width != std::numeric_limits<std::uint32_t>::max()) {
return capabilities.currentExtent;
} else {
int sdl_width = 0, sdl_height = 0;
SDL_Vulkan_GetDrawableSize(this->window->Get(), &sdl_width, &sdl_height); // using equivalent of glfwGetFramebufferSize(window, &width, &height); // https://wiki.libsdl.org/SDL2/SDL_Vulkan_GetDrawableSize
return {
std::clamp(static_cast<std::uint32_t>(sdl_width), capabilities.minImageExtent.width, capabilities.maxImageExtent.width),
std::clamp(static_cast<std::uint32_t>(sdl_height), capabilities.minImageExtent.height, capabilities.maxImageExtent.height)
};
}
}(this->vk_physical_card_info.surface_capabilities);
const std::uint32_t image_count = [this]() {
std::uint32_t image_count = this->vk_physical_card_info.surface_capabilities.minImageCount + 1;
if (this->vk_physical_card_info.surface_capabilities.maxImageCount > 0 && image_count > this->vk_physical_card_info.surface_capabilities.maxImageCount)
image_count = this->vk_physical_card_info.surface_capabilities.maxImageCount;
return image_count;
}();
const auto swapchain_create_info = [&]() -> vk::SwapchainCreateInfoKHR {
vk::SwapchainCreateInfoKHR swapchain_create_info {
.surface = **this->vk_screen_surface,
.minImageCount = image_count,
.imageFormat = surface_format.format,
.imageColorSpace = surface_format.colorSpace,
.imageExtent = extent,
.imageArrayLayers = 1,
.imageUsage = vk::ImageUsageFlagBits::eColorAttachment | vk::ImageUsageFlagBits::eTransferSrc,
.preTransform = this->vk_physical_card_info.surface_capabilities.currentTransform,
.compositeAlpha = vk::CompositeAlphaFlagBitsKHR::eOpaque, // for window manager, we dont need transparency with windows...
.presentMode = present_mode,
.clipped = vk::True,
.oldSwapchain = nullptr
};
const std::array<std::uint32_t, 2> queue_family_indices = { this->vk_physical_card_info.graphics_family.value(), this->vk_physical_card_info.present_family.value() };
if ((this->vk_physical_card_info.graphics_family.has_value() && this->vk_physical_card_info.present_family.has_value()) && this->vk_physical_card_info.graphics_family.value() != this->vk_physical_card_info.present_family.value()) { // https://docs.vulkan.org/tutorial/latest/03_Drawing_a_triangle/01_Presentation/01_Swap_chain.html#_creating_the_swap_chain
swapchain_create_info.imageSharingMode = vk::SharingMode::eConcurrent;
swapchain_create_info.queueFamilyIndexCount = queue_family_indices.size();
swapchain_create_info.pQueueFamilyIndices = queue_family_indices.data();
} else {
swapchain_create_info.imageSharingMode = vk::SharingMode::eExclusive;
swapchain_create_info.queueFamilyIndexCount = 0; // Optional
swapchain_create_info.pQueueFamilyIndices = nullptr; // Optional
}
return swapchain_create_info;
}();
this->vk_swapchain = std::make_unique<vk::raii::SwapchainKHR>(*this->vk_gpu, swapchain_create_info);
auto swapchain_images = this->vk_swapchain->getImages();
this->vk_swapchain_image_format = surface_format.format;
this->vk_swapchain_extent = extent;
for (const auto& image : swapchain_images) { // requires images
const auto imageview_create_info = vk::ImageViewCreateInfo {
.image = image,
.viewType = vk::ImageViewType::e2D,
.format = this->vk_swapchain_image_format,
.components = {
.r = vk::ComponentSwizzle::eIdentity,
.g = vk::ComponentSwizzle::eIdentity,
.b = vk::ComponentSwizzle::eIdentity,
.a = vk::ComponentSwizzle::eIdentity },
.subresourceRange = { .aspectMask = vk::ImageAspectFlagBits::eColor, .baseMipLevel = 0, .levelCount = 1, .baseArrayLayer = 0, .layerCount = 1 },
};
this->vk_swapchain_image_views.emplace_back(*this->vk_gpu, imageview_create_info);
}
}
{ // Load Shaders
this->vk_shader_vertex = std::make_unique<vk::raii::ShaderModule>(*this->vk_gpu, vk::ShaderModuleCreateInfo { .codeSize = embeded_shader_vertex_glsl_spv.size, .pCode = reinterpret_cast<const std::uint32_t*>(embeded_shader_vertex_glsl_spv.begin) });
this->vk_shader_frag = std::make_unique<vk::raii::ShaderModule>(*this->vk_gpu, vk::ShaderModuleCreateInfo { .codeSize = embeded_shader_frag_glsl_spv.size, .pCode = reinterpret_cast<const std::uint32_t*>(embeded_shader_frag_glsl_spv.begin) });
}
{ // Init graphics pipeline/renderpass
const vk::PipelineShaderStageCreateInfo shader_stage_create_info_vertex {
.stage = vk::ShaderStageFlagBits::eVertex,
.module = **this->vk_shader_vertex,
.pName = "main"
};
const vk::PipelineShaderStageCreateInfo shader_stage_create_info_frag {
.stage = vk::ShaderStageFlagBits::eFragment,
.module = **this->vk_shader_frag,
.pName = "main"
};
const vk::PipelineShaderStageCreateInfo shader_stages_create_info[] = { shader_stage_create_info_vertex, shader_stage_create_info_frag };
constexpr std::array<vk::DynamicState, 2> dynamic_states = {
vk::DynamicState::eViewport,
vk::DynamicState::eScissor
};
const vk::PipelineDynamicStateCreateInfo dynamic_state_create_info {
.dynamicStateCount = static_cast<std::uint32_t>(dynamic_states.size()),
.pDynamicStates = dynamic_states.data()
};
constexpr vk::PipelineVertexInputStateCreateInfo vertex_input_create_info {
.vertexBindingDescriptionCount = 0,
.pVertexBindingDescriptions = nullptr, // Optional
.vertexAttributeDescriptionCount = 0,
.pVertexAttributeDescriptions = nullptr // Optional
};
constexpr vk::PipelineInputAssemblyStateCreateInfo input_assembly_create_info {
.topology = vk::PrimitiveTopology::eTriangleList,
.primitiveRestartEnable = vk::False
};
constexpr vk::PipelineViewportStateCreateInfo viewport_state { // https://docs.vulkan.org/tutorial/latest/03_Drawing_a_triangle/02_Graphics_pipeline_basics/02_Fixed_functions.html
.viewportCount = 1,
.scissorCount = 1
};
constexpr vk::PipelineRasterizationStateCreateInfo rasterizer_create_info { // https://docs.vulkan.org/tutorial/latest/03_Drawing_a_triangle/02_Graphics_pipeline_basics/02_Fixed_functions.html // these require GPU features...
.depthClampEnable = vk::False,
.rasterizerDiscardEnable = vk::False,
.polygonMode = vk::PolygonMode::eFill,
.cullMode = vk::CullModeFlagBits::eBack,
.frontFace = vk::FrontFace::eClockwise,
.depthBiasEnable = vk::False,
.depthBiasConstantFactor = 0.0f, // Optional
.depthBiasClamp = 0.0f, // Optional
.depthBiasSlopeFactor = 0.0f, // Optional
.lineWidth = 1.0f
};
constexpr vk::PipelineMultisampleStateCreateInfo multisampling_create_info {
.rasterizationSamples = vk::SampleCountFlagBits::e1,
.sampleShadingEnable = vk::False,
.minSampleShading = 1.0f, // Optional
.pSampleMask = nullptr, // Optional
.alphaToCoverageEnable = vk::False, // Optional
.alphaToOneEnable = vk::False // Optional
};
constexpr vk::PipelineColorBlendAttachmentState color_blend_attachment {
.blendEnable = vk::False,
.srcColorBlendFactor = vk::BlendFactor::eOne, // Optional
.dstColorBlendFactor = vk::BlendFactor::eZero, // Optional
.colorBlendOp = vk::BlendOp::eAdd, // Optional
.srcAlphaBlendFactor = vk::BlendFactor::eOne, // Optional
.dstAlphaBlendFactor = vk::BlendFactor::eZero, // Optional
.alphaBlendOp = vk::BlendOp::eAdd, // Optional
.colorWriteMask = vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA
};
const vk::PipelineColorBlendStateCreateInfo color_blending_create_info {
.logicOpEnable = vk::False,
.logicOp = vk::LogicOp::eCopy, // Optional
.attachmentCount = 1,
.pAttachments = &color_blend_attachment,
.blendConstants = std::array<float, 4> {
0.0f,
0.0f, // Optional
0.0f, // Optional
0.0f // Optional
} // Optional
};
// Descriptor Layouts, appears required.
constexpr auto descriptor_set_layout_binding = vk::DescriptorSetLayoutBinding {
.binding = 0,
//.descriptorType = vk::DescriptorType::eUniformBuffer,
//.descriptorCount = 1,
//.stageFlags = vk::ShaderStageFlagBits::eVertex
};
const auto descriptor_set_layout_create_info = vk::DescriptorSetLayoutCreateInfo {
.bindingCount = 1,
.pBindings = &descriptor_set_layout_binding
};
this->vk_descriptor_set_layout = std::make_unique<vk::raii::DescriptorSetLayout>(*this->vk_gpu, descriptor_set_layout_create_info);
// Pipeline
const vk::PipelineLayoutCreateInfo pipeline_layout_create_info {
.setLayoutCount = 1, // Optional
.pSetLayouts = &**this->vk_descriptor_set_layout, // Optional
//.pushConstantRangeCount = 0, // Optional
//.pPushConstantRanges = nullptr // Optional
};
this->vk_pipeline_layout = std::make_unique<vk::raii::PipelineLayout>(*this->vk_gpu, pipeline_layout_create_info);
// descriptors
constexpr vk::DescriptorPoolCreateInfo discriptor_pool_create_info {
.flags = vk::DescriptorPoolCreateFlagBits::eFreeDescriptorSet,
.maxSets = 1
};
assert(discriptor_pool_create_info.flags & vk::DescriptorPoolCreateFlagBits::eFreeDescriptorSet);
this->vk_descriptor_pool = std::make_unique<vk::raii::DescriptorPool>(*this->vk_gpu, discriptor_pool_create_info);
const vk::DescriptorSetAllocateInfo descriptor_set_allocate_info {
.descriptorPool = **this->vk_descriptor_pool,
.descriptorSetCount = 1,
.pSetLayouts = &**this->vk_descriptor_set_layout
};
this->vk_descriptor_sets = std::make_unique<vk::raii::DescriptorSets>(*this->vk_gpu, descriptor_set_allocate_info);
const vk::AttachmentDescription color_attachment {
.format = this->vk_swapchain_image_format,
.samples = vk::SampleCountFlagBits::e1,
.loadOp = vk::AttachmentLoadOp::eClear,
.storeOp = vk::AttachmentStoreOp::eStore,
.stencilLoadOp = vk::AttachmentLoadOp::eDontCare,
.stencilStoreOp = vk::AttachmentStoreOp::eDontCare,
.initialLayout = vk::ImageLayout::eUndefined,
.finalLayout = vk::ImageLayout::ePresentSrcKHR
};
constexpr vk::AttachmentReference color_attachment_ref {
.attachment = 0,
.layout = vk::ImageLayout::eColorAttachmentOptimal
};
const vk::SubpassDescription subpass_description {
.pipelineBindPoint = vk::PipelineBindPoint::eGraphics,
.colorAttachmentCount = 1,
.pColorAttachments = &color_attachment_ref
};
const vk::SubpassDependency subpass_dependency {
.srcSubpass = vk::SubpassExternal,
.dstSubpass = 0,
.srcStageMask = vk::PipelineStageFlagBits::eColorAttachmentOutput,
.dstStageMask = vk::PipelineStageFlagBits::eColorAttachmentOutput,
.srcAccessMask = vk::AccessFlagBits::eNone,
.dstAccessMask = vk::AccessFlagBits::eColorAttachmentWrite
};
const vk::RenderPassCreateInfo render_pass_create_info {
.attachmentCount = 1,
.pAttachments = &color_attachment,
.subpassCount = 1,
.pSubpasses = &subpass_description,
.dependencyCount = 1,
.pDependencies = &subpass_dependency
};
this->vk_render_pass = std::make_unique<vk::raii::RenderPass>(*this->vk_gpu, render_pass_create_info);
const vk::GraphicsPipelineCreateInfo pipeline_create_info {
.stageCount = 2,
.pStages = shader_stages_create_info,
.pVertexInputState = &vertex_input_create_info,
.pInputAssemblyState = &input_assembly_create_info,
.pViewportState = &viewport_state,
.pRasterizationState = &rasterizer_create_info,
.pMultisampleState = &multisampling_create_info,
.pDepthStencilState = nullptr, // Optional
.pColorBlendState = &color_blending_create_info,
.pDynamicState = &dynamic_state_create_info,
.layout = **this->vk_pipeline_layout,
.renderPass = **this->vk_render_pass,
.subpass = 0,
.basePipelineHandle = nullptr, // Optional
.basePipelineIndex = -1 // Optional
};
this->vk_pipeline = std::make_unique<vk::raii::Pipeline>(*this->vk_gpu, nullptr, pipeline_create_info);
}
{ // command pool setup
for (const auto& i : this->vk_swapchain_image_views) {
const std::array<vk::ImageView, 1> attachments = { *i };
const vk::FramebufferCreateInfo framebuffer_create_info {
.renderPass = **this->vk_render_pass,
.attachmentCount = attachments.size(),
.pAttachments = attachments.data(),
.width = this->vk_swapchain_extent.width,
.height = this->vk_swapchain_extent.height,
.layers = 1
};
this->vk_swapchain_framebuffers.emplace_back(*this->vk_gpu, framebuffer_create_info);
}
const vk::CommandPoolCreateInfo command_pool_create_info { // https://docs.vulkan.org/tutorial/latest/03_Drawing_a_triangle/03_Drawing/01_Command_buffers.html
.flags = vk::CommandPoolCreateFlagBits::eResetCommandBuffer,
.queueFamilyIndex = this->vk_physical_card_info.graphics_family.value()
};
this->vk_command_pool = std::make_unique<vk::raii::CommandPool>(*this->vk_gpu, command_pool_create_info);
const vk::CommandBufferAllocateInfo command_buffer_alloc_info {
.commandPool = **this->vk_command_pool,
.level = vk::CommandBufferLevel::ePrimary,
.commandBufferCount = 1
};
this->vk_command_buffers = std::make_unique<vk::raii::CommandBuffers>(*this->vk_gpu, command_buffer_alloc_info);
}
{ // syncronizing vars
this->vk_semephore_image_available = std::make_unique<vk::raii::Semaphore>(*this->vk_gpu, vk::SemaphoreCreateInfo {});
this->vk_semephore_render_finished = std::make_unique<vk::raii::Semaphore>(*this->vk_gpu, vk::SemaphoreCreateInfo {});
this->vk_fence_in_flight = std::make_unique<vk::raii::Fence>(*this->vk_gpu, vk::FenceCreateInfo { .flags = vk::FenceCreateFlagBits::eSignaled });
}
} catch (const vk::SystemError& e) {
std::cout << "Received Vulkan-Specific Error during process init: " << e.what() << std::endl
<< "Going to rethrow!" << std::endl;
throw e;
} catch (const std::exception& e) {
std::cout << "Received Error during process init: " << e.what() << std::endl
<< "Going to rethrow!" << std::endl;
throw e;
} catch (...) {
std::cout << "Received Unknown Error during process init..." << std::endl;
throw "Unknown Exception, throwing...";
}
}
void RecordDynamic(const vk::raii::CommandBuffer& command_buffer) const {
const vk::Viewport viewport {
.x = 0.0f,
.y = 0.0f,
.width = (float)this->vk_swapchain_extent.width,
.height = (float)this->vk_swapchain_extent.height,
.minDepth = 0.0f,
.maxDepth = 1.0f
};
const vk::Rect2D scissor {
.offset = { 0, 0 },
.extent = this->vk_swapchain_extent
};
command_buffer.setViewport(0, viewport);
command_buffer.setScissor(0, scissor);
}
void RecordCommandBuffers(const vk::raii::CommandBuffer& command_buffer, std::uint32_t image_index) const {
constexpr vk::CommandBufferBeginInfo command_buffer_begin_info {
//.flags = vk::CommandBufferUsageFlagBits::, // Optional
//.pInheritanceInfo = nullptr // Optional
};
command_buffer.begin(command_buffer_begin_info);
constexpr std::array<vk::ClearValue, 1> clear_colors = { vk::ClearValue { .color = std::array<float, 4> { 0.0f, 0.0f, 0.0f, 1.0f } } };
const vk::RenderPassBeginInfo render_pass_info {
.renderPass = **this->vk_render_pass,
.framebuffer = *this->vk_swapchain_framebuffers.at(image_index),
.renderArea = {
.offset = { 0, 0 },
.extent = this->vk_swapchain_extent },
.clearValueCount = clear_colors.size(),
.pClearValues = clear_colors.data()
};
command_buffer.beginRenderPass(render_pass_info, vk::SubpassContents::eInline);
command_buffer.bindPipeline(vk::PipelineBindPoint::eGraphics, **this->vk_pipeline);
command_buffer.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, *this->vk_pipeline_layout, 0, { this->vk_descriptor_sets->front() }, nullptr);
this->RecordDynamic(command_buffer);
command_buffer.draw(3, 1, 0, 0);
command_buffer.endRenderPass();
command_buffer.end();
};
void DrawFrame() const {
const std::array<vk::Fence, 1> wait_fences = { *this->vk_fence_in_flight };
const vk::Result fence_result = this->vk_gpu->waitForFences(wait_fences, vk::True, std::numeric_limits<std::uint64_t>::max());
if (fence_result != vk::Result::eSuccess)
throw std::runtime_error("failed to wait for frame fence!");
this->vk_gpu->resetFences(wait_fences);
const auto next_image = this->vk_swapchain->acquireNextImage(std::numeric_limits<std::uint64_t>::max(), *this->vk_semephore_image_available);
if (next_image.first != vk::Result::eSuccess) {
if (next_image.first == vk::Result::eNotReady) // i think its best to just return...
return;
if (next_image.first != vk::Result::eSuboptimalKHR)
throw std::runtime_error("failed to aquire next image!: " + std::to_string((int)next_image.first)); // vk::Result::eTimeout and everything else throws!
}
this->vk_command_buffers->front().reset();
this->RecordCommandBuffers(this->vk_command_buffers->front(), next_image.second);
const std::array<vk::Semaphore, 1> wait_semaphores = { *this->vk_semephore_image_available };
constexpr auto wait_stages = vk::PipelineStageFlags(vk::PipelineStageFlagBits::eColorAttachmentOutput);
const std::array<vk::Semaphore, 1> signal_semaphores = { *this->vk_semephore_render_finished };
const std::vector<vk::CommandBuffer> command_buffers(this->vk_command_buffers->begin(), this->vk_command_buffers->end());
const vk::SubmitInfo submit_info {
.waitSemaphoreCount = wait_semaphores.size(),
.pWaitSemaphores = wait_semaphores.data(),
.pWaitDstStageMask = &wait_stages,
.commandBufferCount = static_cast<std::uint32_t>(command_buffers.size()),
.pCommandBuffers = command_buffers.data(),
.signalSemaphoreCount = signal_semaphores.size(),
.pSignalSemaphores = signal_semaphores.data()
};
const std::array<vk::SubmitInfo, 1> submit_queue = { submit_info };
this->vk_queue_graphics->submit(submit_queue, **this->vk_fence_in_flight);
const std::array<vk::SwapchainKHR, 1> swapchains = { *this->vk_swapchain };
const vk::PresentInfoKHR present_info {
.waitSemaphoreCount = signal_semaphores.size(),
.pWaitSemaphores = signal_semaphores.data(),
.swapchainCount = swapchains.size(),
.pSwapchains = swapchains.data(),
.pImageIndices = &next_image.second,
.pResults = nullptr // Optional
};
const vk::Result present_result = this->vk_queue_present->presentKHR(present_info);
if (present_result != vk::Result::eSuccess)
throw std::runtime_error("failed to present image!");
}
void Run() {
bool running = true;
while (running) {
SDL_Event window_event;
while (SDL_PollEvent(&window_event)) {
if (window_event.type == SDL_QUIT) {
running = false;
break;
}
}
this->DrawFrame();
}
}
void RunTests() {
constexpr auto amount_of_frames_needed = 15000;
std::cout << "Starting Render Tests with: " << std::to_string(amount_of_frames_needed) << " frames!" << std::endl;
std::uintptr_t posted_about = 0;
for (std::uintptr_t drawn_frames = 0; drawn_frames < amount_of_frames_needed; drawn_frames++) {
this->DrawFrame();
const auto amount_of_thousands = drawn_frames / 1000;
if (amount_of_thousands > posted_about) {
std::cout << "DrawFrame Count: " << std::to_string(drawn_frames) << std::endl;
posted_about = amount_of_thousands;
}
}
std::cout << "Completed tests with: " << std::to_string(amount_of_frames_needed) << " frames!" << std::endl;
}
private:
static std::unique_ptr<vk::raii::SurfaceKHR> VulkanCreateSurface(const SDL2pp::Window& window, const vk::raii::Instance& vk_inst) {
VkSurfaceKHR _screen_surface;
SDL_Vulkan_CreateSurface(window.Get(), static_cast<VkInstance>(static_cast<vk::Instance>(vk_inst)), &_screen_surface);
return std::make_unique<vk::raii::SurfaceKHR>(vk_inst, _screen_surface);
}
private:
static constexpr auto app_name = "VulkZample";
static constexpr bool allow_swrast = true;
#if defined(ENABLE_VULKAN_VALIDATION)
static constexpr auto debug_message_info = vk::DebugUtilsMessengerCreateInfoEXT {
.messageSeverity = vk::DebugUtilsMessageSeverityFlagBitsEXT::eVerbose | vk::DebugUtilsMessageSeverityFlagBitsEXT::eWarning | vk::DebugUtilsMessageSeverityFlagBitsEXT::eError | vk::DebugUtilsMessageSeverityFlagBitsEXT::eInfo,
.messageType = vk::DebugUtilsMessageTypeFlagBitsEXT::eGeneral | vk::DebugUtilsMessageTypeFlagBitsEXT::eValidation | vk::DebugUtilsMessageTypeFlagBitsEXT::ePerformance,
.pfnUserCallback = &VulkanDebugCallback
};
#endif
static constexpr std::array<const char*, 1> required_vulkan_device_extensions = { vk::KHRSwapchainExtensionName };
static constexpr std::array<const char*, 1> required_vulkan_validation_layers = { "VK_LAYER_KHRONOS_validation" };
static constexpr vk::Format required_vulkan_default_format = vk::Format::eR8G8B8A8Unorm; // formats Preffered front to back. FIFO
static constexpr std::array<vk::Format, 4> required_vulkan_screen_formats = { vk::Format::eB8G8R8A8Unorm, vk::Format::eR8G8B8A8Unorm, vk::Format::eB8G8R8Unorm, vk::Format::eR8G8B8Unorm }; // used similar ones from, seemed optimal... https://github.com/KhronosGroup/Vulkan-Hpp/blob/6f72ceca515d59f40d64b64cf2734f6261e1f9f2/samples/utils/utils.cpp#L537
static constexpr vk::ColorSpaceKHR required_vulkan_default_screen_colorspace = vk::ColorSpaceKHR::eSrgbNonlinear;
static constexpr vk::ColorSpaceKHR required_vulkan_screen_colorspace = vk::ColorSpaceKHR::eSrgbNonlinear;
};
#if defined(ENABLE_VULKAN_VALIDATION)
static VKAPI_ATTR VkBool32 VKAPI_CALL VulkanDebugCallback(
VkDebugUtilsMessageSeverityFlagBitsEXT message_severity,
VkDebugUtilsMessageTypeFlagsEXT message_type,
const VkDebugUtilsMessengerCallbackDataEXT* callback_data,
void* user_data) {
std::cerr << "[debug log] validation layer: " << callback_data->pMessage << std::endl;
return vk::False;
}
/*static VKAPI_ATTR VkBool32 VKAPI_CALL VulkanReportCallback(
VkDebugReportFlagsEXT flags,
VkDebugReportObjectTypeEXT type,
uint64_t obj,
size_t location,
int32_t code,
const char* layer_prefix,
const char* msg,
void* user_data) {
printf("[debug log] report layer: %s\n", msg);
return vk::False;
}*/
#endif
int main() {
try {
VulkanExampleApplication app;
#if !defined(ENABLE_TESTS)
app.Run();
#else
app.RunTests();
#endif
} catch (const vk::SystemError& e) {
std::cerr << e.what() << std::endl;
return EXIT_FAILURE;
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
return EXIT_FAILURE;
} catch (...) {
std::cerr << "Received Unknown Error in Main()..." << std::endl;
throw "Unknown Exception, throwing...";
}
return EXIT_SUCCESS;
}

36
test.sh Normal file
View File

@ -0,0 +1,36 @@
#!/bin/sh -e
unset ENABLE_DEBUG
unset ENABLE_SWRAST
export CMAKE_ENABLE_TESTS=ON
check_failure() {
if [ $? -ne 0 ]; then
echo "Test Failed: $1"
exit 1
fi
}
run_and_grep() {
OUTPUT=$($1 2>&1)
echo "$OUTPUT" | grep "Completed tests"
check_failure "$2"
echo "Test Success: $2"
}
echo "Testing Debug"
sh clean.sh
ENABLE_TESTS=1 ENABLE_DEBUG=1 sh build.sh >/dev/null 2>&1
check_failure "Build Debug"
time ENABLE_SWRAST=1 run_and_grep "sh run.sh" "Debug CPU Test"
time run_and_grep "sh run.sh" "Debug GPU Test"
echo "Testing Release"
sh clean.sh
ENABLE_TESTS=1 sh build.sh >/dev/null 2>&1
check_failure "Build Release"
time ENABLE_SWRAST=1 run_and_grep "sh run.sh" "Release CPU Test"
time run_and_grep "sh run.sh" "Release GPU Test"
echo "Tests Succeeded"