Skip to content

Commit 4baad24

Browse files
committed
Add shaderc
1 parent 7e2f438 commit 4baad24

File tree

10 files changed

+535
-0
lines changed

10 files changed

+535
-0
lines changed

CMakeLists.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ find_package(glfw3 CONFIG REQUIRED)
1717
find_package(glm CONFIG REQUIRED)
1818
find_package(Stb REQUIRED)
1919
find_package(tinyobjloader CONFIG REQUIRED)
20+
find_package(unofficial-shaderc CONFIG REQUIRED)
2021

2122
file(GLOB_RECURSE CXX_CPP_FILES "src/*.cpp")
2223
file(GLOB_RECURSE CXX_MODULE_FILES "src/*.cppm" "src/*.ixx")
@@ -32,6 +33,7 @@ target_link_libraries(main PRIVATE glm::glm)
3233
target_link_libraries(main PRIVATE glfw )
3334
target_include_directories(main PRIVATE ${Stb_INCLUDE_DIR})
3435
target_link_libraries(main PRIVATE tinyobjloader::tinyobjloader)
36+
target_link_libraries(main PRIVATE unofficial::shaderc::shaderc)
3537

3638
add_subdirectory(shaders)
3739

1.54 KB
Binary file not shown.
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
cmake_minimum_required(VERSION 4.0.0)
2+
3+
# 请自行设置模块实验性标准
4+
# set(CMAKE_EXPERIMENTAL_CXX_IMPORT_STD "......")
5+
6+
file(TO_CMAKE_PATH "$ENV{VCPKG_ROOT}" VCPKG_CMAKE_PATH)
7+
set(CMAKE_TOOLCHAIN_FILE "${VCPKG_CMAKE_PATH}/scripts/buildsystems/vcpkg.cmake")
8+
9+
project(HelloCppModule LANGUAGES CXX)
10+
11+
set(CMAKE_CXX_STANDARD 23)
12+
set(CMAKE_CXX_MODULE_STD 1)
13+
14+
include(cmake/VulkanHppModule.cmake)
15+
16+
find_package(glfw3 CONFIG REQUIRED)
17+
find_package(glm CONFIG REQUIRED)
18+
find_package(Stb REQUIRED)
19+
find_package(tinyobjloader CONFIG REQUIRED)
20+
find_package(unofficial-shaderc CONFIG REQUIRED)
21+
22+
file(GLOB_RECURSE CXX_CPP_FILES "src/*.cpp")
23+
file(GLOB_RECURSE CXX_MODULE_FILES "src/*.cppm" "src/*.ixx")
24+
add_executable(main ${CXX_CPP_FILES})
25+
target_sources(main PRIVATE
26+
FILE_SET cxx_modules
27+
TYPE CXX_MODULES
28+
FILES ${CXX_MODULE_FILES}
29+
)
30+
31+
target_link_libraries(main PRIVATE VulkanHppModule)
32+
target_link_libraries(main PRIVATE glm::glm)
33+
target_link_libraries(main PRIVATE glfw )
34+
target_include_directories(main PRIVATE ${Stb_INCLUDE_DIR})
35+
target_link_libraries(main PRIVATE tinyobjloader::tinyobjloader)
36+
target_link_libraries(main PRIVATE unofficial::shaderc::shaderc)
37+
38+
add_subdirectory(shaders)
39+
Lines changed: 244 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,244 @@
1+
export module GraphicsPipeline;
2+
3+
import std;
4+
import shaderc;
5+
import vulkan_hpp;
6+
7+
8+
import DataLoader;
9+
import Tools;
10+
import Device;
11+
import RenderPass;
12+
13+
const std::string VERT_CODE = R"_GLSL_(
14+
#version 450
15+
16+
layout(binding = 0) uniform UniformBufferObject {
17+
mat4 model;
18+
mat4 view;
19+
mat4 proj;
20+
} ubo;
21+
22+
layout(location = 0) in vec3 inPosition;
23+
layout(location = 1) in vec2 inTexCoord;
24+
25+
layout(location = 0) out vec2 fragTexCoord;
26+
27+
void main() {
28+
gl_Position = ubo.proj * ubo.view * ubo.model * vec4(inPosition, 1.0);
29+
fragTexCoord = inTexCoord;
30+
}
31+
)_GLSL_";
32+
33+
const std::string FRAG_CODE = R"_GLSL_(
34+
#version 450
35+
36+
layout(set = 1, binding = 0) uniform sampler2D texSampler;
37+
38+
layout(location = 0) in vec2 fragTexCoord;
39+
40+
layout(location = 0) out vec4 outColor;
41+
42+
void main() {
43+
outColor = texture(texSampler, fragTexCoord);
44+
}
45+
)_GLSL_";
46+
47+
48+
std::vector<std::uint32_t> compile_shader(
49+
const std::string& source, // 着色器源代码
50+
const shaderc::shader_kind kind, // 着色器类型
51+
const std::string& name = "shader" // 着色器名称(可选,默认为 "shader")
52+
) {
53+
// 创建编译器和编译选项
54+
shaderc::Compiler compiler;
55+
shaderc::CompileOptions options;
56+
57+
// 设置编译选项
58+
options.SetOptimizationLevel(shaderc::optimization_level::shaderc_optimization_level_performance);
59+
// 设置目标环境
60+
options.SetTargetEnvironment(shaderc::target_env::shaderc_target_env_vulkan, shaderc::env_version::shaderc_env_version_vulkan_1_4);
61+
// 设置源语言
62+
options.SetSourceLanguage(shaderc::source_language::shaderc_source_language_glsl);
63+
64+
// 编译着色器
65+
const shaderc::SpvCompilationResult result = compiler.CompileGlslToSpv(
66+
source, // 着色器源代码
67+
kind, // 着色器类型
68+
name.c_str(), // 着色器名称
69+
options // 编译选项
70+
);
71+
72+
// 检查编译结果
73+
if (result.GetCompilationStatus() != shaderc::compilation_status::shaderc_compilation_status_success) {
74+
throw std::runtime_error(result.GetErrorMessage());
75+
}
76+
77+
return {result.cbegin(), result.cend()};
78+
}
79+
80+
export namespace vht {
81+
82+
/**
83+
* @brief 图形管线相关
84+
* @details
85+
* - 依赖:
86+
* - m_device: 逻辑设备与队列
87+
* - m_render_pass: 渲染通道
88+
* - 工作:
89+
* - 创建描述符集布局
90+
* - 创建图形管线布局和图形管线
91+
* - 可访问成员:
92+
* - descriptor_set_layout(): 描述符集布局
93+
* - pipeline_layout(): 管线布局
94+
* - pipeline(): 图形管线
95+
*/
96+
class GraphicsPipeline {
97+
std::shared_ptr<vht::Device> m_device;
98+
std::shared_ptr<vht::RenderPass> m_render_pass;
99+
std::vector<vk::raii::DescriptorSetLayout> m_descriptor_set_layouts;
100+
vk::raii::PipelineLayout m_pipeline_layout{ nullptr };
101+
vk::raii::Pipeline m_pipeline{ nullptr };
102+
public:
103+
explicit GraphicsPipeline(std::shared_ptr<vht::Device> device, std::shared_ptr<vht::RenderPass> render_pass)
104+
: m_device(std::move(device)),
105+
m_render_pass(std::move(render_pass)) {
106+
init();
107+
}
108+
109+
[[nodiscard]]
110+
const std::vector<vk::raii::DescriptorSetLayout>& descriptor_set_layouts() const { return m_descriptor_set_layouts; }
111+
[[nodiscard]]
112+
const vk::raii::PipelineLayout& pipeline_layout() const { return m_pipeline_layout; }
113+
[[nodiscard]]
114+
const vk::raii::Pipeline& pipeline() const { return m_pipeline; }
115+
116+
private:
117+
void init() {
118+
create_descriptor_set_layout();
119+
create_graphics_pipeline();
120+
}
121+
// 创建描述符集布局
122+
void create_descriptor_set_layout() {
123+
vk::DescriptorSetLayoutBinding uboLayoutBinding;
124+
uboLayoutBinding.binding = 0;
125+
uboLayoutBinding.descriptorType = vk::DescriptorType::eUniformBuffer;
126+
uboLayoutBinding.descriptorCount = 1;
127+
uboLayoutBinding.stageFlags = vk::ShaderStageFlagBits::eVertex;
128+
129+
vk::DescriptorSetLayoutCreateInfo uboLayoutInfo;
130+
uboLayoutInfo.setBindings( uboLayoutBinding );
131+
m_descriptor_set_layouts.emplace_back( m_device->device().createDescriptorSetLayout( uboLayoutInfo ) );
132+
133+
vk::DescriptorSetLayoutBinding samplerLayoutBinding;
134+
samplerLayoutBinding.binding = 0;
135+
samplerLayoutBinding.descriptorType = vk::DescriptorType::eCombinedImageSampler;
136+
samplerLayoutBinding.descriptorCount = 1;
137+
samplerLayoutBinding.stageFlags = vk::ShaderStageFlagBits::eFragment;
138+
vk::DescriptorSetLayoutCreateInfo samplerLayoutInfo;
139+
140+
samplerLayoutInfo.setBindings( samplerLayoutBinding );
141+
m_descriptor_set_layouts.emplace_back( m_device->device().createDescriptorSetLayout( samplerLayoutInfo ) );
142+
}
143+
// 创建图形管线
144+
void create_graphics_pipeline() {
145+
// const std::vector<std::uint32_t>
146+
const auto vertex_shader_code = compile_shader(VERT_CODE, shaderc::shader_kind::shaderc_glsl_vertex_shader);
147+
const auto fragment_shader_code = compile_shader(FRAG_CODE, shaderc::shader_kind::shaderc_glsl_fragment_shader);
148+
const auto vertex_shader_module = m_device->device().createShaderModule(
149+
vk::ShaderModuleCreateInfo().setCode( vertex_shader_code )
150+
);
151+
const auto fragment_shader_module = m_device->device().createShaderModule(
152+
vk::ShaderModuleCreateInfo().setCode(fragment_shader_code)
153+
);
154+
155+
vk::PipelineShaderStageCreateInfo vertex_shader_create_info;
156+
vertex_shader_create_info.stage = vk::ShaderStageFlagBits::eVertex;
157+
vertex_shader_create_info.module = vertex_shader_module;
158+
vertex_shader_create_info.pName = "main";
159+
160+
vk::PipelineShaderStageCreateInfo fragment_shader_create_info;
161+
fragment_shader_create_info.stage = vk::ShaderStageFlagBits::eFragment;
162+
fragment_shader_create_info.module = fragment_shader_module;
163+
fragment_shader_create_info.pName = "main";
164+
165+
const auto shader_stages = { vertex_shader_create_info, fragment_shader_create_info };
166+
167+
const auto dynamic_states = { vk::DynamicState::eViewport, vk::DynamicState::eScissor };
168+
vk::PipelineDynamicStateCreateInfo dynamic_state;
169+
dynamic_state.setDynamicStates(dynamic_states);
170+
171+
const auto binding_description = vht::Vertex::get_binding_description();
172+
const auto attribute_description = vht::Vertex::get_attribute_description();
173+
vk::PipelineVertexInputStateCreateInfo vertex_input;
174+
vertex_input.setVertexBindingDescriptions(binding_description);
175+
vertex_input.setVertexAttributeDescriptions(attribute_description);
176+
177+
vk::PipelineInputAssemblyStateCreateInfo input_assembly;
178+
input_assembly.topology = vk::PrimitiveTopology::eTriangleList;
179+
180+
vk::PipelineViewportStateCreateInfo viewport_state;
181+
viewport_state.viewportCount = 1;
182+
viewport_state.scissorCount = 1;
183+
184+
vk::PipelineDepthStencilStateCreateInfo depth_stencil;
185+
depth_stencil.depthTestEnable = true;
186+
depth_stencil.depthWriteEnable = true;
187+
depth_stencil.depthCompareOp = vk::CompareOp::eLess;
188+
depth_stencil.depthBoundsTestEnable = false; // Optional
189+
depth_stencil.stencilTestEnable = false; // Optional
190+
191+
vk::PipelineRasterizationStateCreateInfo rasterizer;
192+
rasterizer.depthClampEnable = false;
193+
rasterizer.rasterizerDiscardEnable = false;
194+
rasterizer.polygonMode = vk::PolygonMode::eFill;
195+
rasterizer.lineWidth = 1.0f;
196+
rasterizer.cullMode = vk::CullModeFlagBits::eBack;
197+
rasterizer.frontFace = vk::FrontFace::eCounterClockwise;
198+
rasterizer.depthBiasEnable = false;
199+
200+
vk::PipelineMultisampleStateCreateInfo multisampling;
201+
multisampling.rasterizationSamples = vk::SampleCountFlagBits::e1;
202+
multisampling.sampleShadingEnable = false; // default
203+
204+
vk::PipelineColorBlendAttachmentState color_blend_attachment;
205+
color_blend_attachment.blendEnable = false; // default
206+
color_blend_attachment.colorWriteMask = vk::FlagTraits<vk::ColorComponentFlagBits>::allFlags;
207+
208+
vk::PipelineColorBlendStateCreateInfo color_blend;
209+
color_blend.logicOpEnable = false;
210+
color_blend.logicOp = vk::LogicOp::eCopy;
211+
color_blend.setAttachments( color_blend_attachment );
212+
213+
vk::PipelineLayoutCreateInfo layout_create_info;
214+
215+
// 将 raii 类型转换回 vk::DescriptorSetLayout
216+
const auto set_layouts = m_descriptor_set_layouts
217+
| std::views::transform([](const auto& layout) -> vk::DescriptorSetLayout { return layout; })
218+
| std::ranges::to<std::vector>();
219+
220+
layout_create_info.setSetLayouts( set_layouts );
221+
m_pipeline_layout = m_device->device().createPipelineLayout( layout_create_info );
222+
223+
vk::GraphicsPipelineCreateInfo create_info;
224+
create_info.layout = m_pipeline_layout;
225+
226+
create_info.setStages( shader_stages );
227+
create_info.pVertexInputState = &vertex_input;
228+
create_info.pInputAssemblyState = &input_assembly;
229+
create_info.pDynamicState = &dynamic_state;
230+
create_info.pViewportState = &viewport_state;
231+
create_info.pDepthStencilState = &depth_stencil;
232+
create_info.pRasterizationState = &rasterizer;
233+
create_info.pMultisampleState = &multisampling;
234+
create_info.pColorBlendState = &color_blend;
235+
236+
create_info.renderPass = m_render_pass->render_pass();
237+
create_info.subpass = 0;
238+
239+
m_pipeline = m_device->device().createGraphicsPipeline( nullptr, create_info );
240+
}
241+
};
242+
}
243+
244+
7.42 KB
Binary file not shown.

docs/codes/04/15_shaderc/shaderc.cppm

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
module;
2+
3+
#include <shaderc/shaderc.hpp>
4+
5+
export module shaderc;
6+
7+
export namespace shaderc {
8+
using target_env = ::shaderc_target_env;
9+
using env_version = ::shaderc_env_version;
10+
using spirv_version = ::shaderc_spirv_version;
11+
using compilation_status = ::shaderc_compilation_status;
12+
using source_language = ::shaderc_source_language;
13+
using shader_kind = ::shaderc_shader_kind;
14+
using profile = ::shaderc_profile;
15+
using optimization_level = ::shaderc_optimization_level;
16+
using limit = ::shaderc_limit;
17+
using uniform_kind = ::shaderc_uniform_kind;
18+
using include_result = ::shaderc_include_result;
19+
using include_type = ::shaderc_include_type;
20+
using shaderc::CompilationResult;
21+
using shaderc::Compiler;
22+
using shaderc::CompileOptions;
23+
using shaderc::SpvCompilationResult;
24+
using shaderc::AssemblyCompilationResult;
25+
using shaderc::PreprocessedSourceCompilationResult;
26+
}
27+
28+
1.07 MB
Binary file not shown.

0 commit comments

Comments
 (0)