diff --git a/README.md b/README.md index fc0e545..2cb6bd2 100644 --- a/README.md +++ b/README.md @@ -1,32 +1,24 @@ Instructions - Vulkan Grass Rendering ======================== -This is due **Sunday 11/4, evening at midnight**. +* Henry Zhu +* [Github](https://github.com/Maknee), [LinkedIn](https://www.linkedin.com/in/henry-zhu-347233121/), [personal website](https://maknee.github.io/), [twitter](https://twitter.com/maknees1), etc. +* Tested on: Windows 10 Home, Intel i7-4710HQ @ 2.50GHz 22GB, GTX 870M (Own computer) -**Summary:** -In this project, you will use Vulkan to implement a grass simulator and renderer. You will -use compute shaders to perform physics calculations on Bezier curves that represent individual -grass blades in your application. Since rendering every grass blade on every frame will is fairly -inefficient, you will also use compute shaders to cull grass blades that don't contribute to a given frame. -The remaining blades will be passed to a graphics pipeline, in which you will write several shaders. -You will write a vertex shader to transform Bezier control points, tessellation shaders to dynamically create -the grass geometry from the Bezier curves, and a fragment shader to shade the grass blades. +# With no movement +![](everything.gif) -The base code provided includes all of the basic Vulkan setup, including a compute pipeline that will run your compute -shaders and two graphics pipelines, one for rendering the geometry that grass will be placed on and the other for -rendering the grass itself. Your job will be to write the shaders for the grass graphics pipeline and the compute pipeline, -as well as binding any resources (descriptors) you may need to accomplish the tasks described in this assignment. +# With movement (no culling) +![](mov.gif) -![](img/grass.gif) ![](img/grass2.gif) +# With orientation culling +![](orientationcull.gif) -You are not required to use this base code if you don't want -to. You may also change any part of the base code as you please. -**This is YOUR project.** The above .gifs are just examples that you -can use as a reference to compare to. Feel free to get creative with your implementations! +# With view culling +![](viewcull.gif) -**Important:** -- If you are not in CGGT/DMD, you may replace this project with a GPU compute -project. You MUST get this pre-approved by Ottavio before continuing! +# With distance culling +![](distancecull.gif) ### Contents @@ -34,220 +26,87 @@ project. You MUST get this pre-approved by Ottavio before continuing! * `shaders/` glsl shader source files * `images/` images used as textures within graphics pipelines * `external/` Includes and static libraries for 3rd party libraries. -* `img/` Screenshots and images to use in your READMEs -### Installing Vulkan +### Overview -In order to run a Vulkan project, you first need to download and install the [Vulkan SDK](https://vulkan.lunarg.com/). -Make sure to run the downloaded installed as administrator so that the installer can set the appropriate environment -variables for you. +Using the techniques described in this [paper](https://www.cg.tuwien.ac.at/research/publications/2017/JAHRMANN-2017-RRTG/JAHRMANN-2017-RRTG-draft.pdf), I was able to create a simulation of grass. -Once you have done this, you need to make sure your GPU driver supports Vulkan. Download and install a -[Vulkan driver](https://developer.nvidia.com/vulkan-driver) from NVIDIA's website. +The following sections describe each component of the system -Finally, to check that Vulkan is ready for use, go to your Vulkan SDK directory (`C:/VulkanSDK/` unless otherwise specified) -and run the `cube.exe` example within the `Bin` directory. IF you see a rotating gray cube with the LunarG logo, then you -are all set! - -### Running the code - -While developing your grass renderer, you will want to keep validation layers enabled so that error checking is turned on. -The project is set up such that when you are in `debug` mode, validation layers are enabled, and when you are in `release` mode, -validation layers are disabled. After building the code, you should be able to run the project without any errors. You will see a plane with a grass texture on it to begin with. - -![](img/cube_demo.png) - -## Requirements - -**Ask on the mailing list for any clarifications.** - -In this project, you are given the following code: - -* The basic setup for a Vulkan project, including the swapchain, physical device, logical device, and the pipelines described above. -* Structs for some of the uniform buffers you will be using. -* Some buffer creation utility functions. -* A simple interactive camera using the mouse. - -You need to implement the following features/pipeline stages: - -* Compute shader (`shaders/compute.comp`) -* Grass pipeline stages - * Vertex shader (`shaders/grass.vert') - * Tessellation control shader (`shaders/grass.tesc`) - * Tessellation evaluation shader (`shaders/grass.tese`) - * Fragment shader (`shaders/grass.frag`) -* Binding of any extra descriptors you may need - -See below for more guidance. - -## Base Code Tour - -Areas that you need to complete are -marked with a `TODO` comment. Functions that are useful -for reference are marked with the comment `CHECKITOUT`. - -* `src/main.cpp` is the entry point of our application. -* `src/Instance.cpp` sets up the application state, initializes the Vulkan library, and contains functions that will create our -physical and logical device handles. -* `src/Device.cpp` manages the logical device and sets up the queues that our command buffers will be submitted to. -* `src/Renderer.cpp` contains most of the rendering implementation, including Vulkan setup and resource creation. You will -likely have to make changes to this file in order to support changes to your pipelines. -* `src/Camera.cpp` manages the camera state. -* `src/Model.cpp` manages the state of the model that grass will be created on. Currently a plane is hardcoded, but feel free to -update this with arbitrary model loading! -* `src/Blades.cpp` creates the control points corresponding to the grass blades. There are many parameters that you can play with -here that will change the behavior of your rendered grass blades. -* `src/Scene.cpp` manages the scene state, including the model, blades, and simualtion time. -* `src/BufferUtils.cpp` provides helper functions for creating buffers to be used as descriptors. - -We left out descriptions for a couple files that you likely won't have to modify. Feel free to investigate them to understand their -importance within the scope of the project. - -## Grass Rendering - -This project is an implementation of the paper, [Responsive Real-Time Grass Rendering for General 3D Scenes](https://www.cg.tuwien.ac.at/research/publications/2017/JAHRMANN-2017-RRTG/JAHRMANN-2017-RRTG-draft.pdf). -Please make sure to use this paper as a primary resource while implementing your grass renderers. It does a great job of explaining -the key algorithms and math you will be using. Below is a brief description of the different components in chronological order of how your renderer will -execute, but feel free to develop the components in whatever order you prefer. - -We recommend starting with trying to display the grass blades without any forces on them before trying to add any forces on the blades themselves. Here is an example of what that may look like: - -![](img/grass_basic.gif) - -### Representing Grass as Bezier Curves - -In this project, grass blades will be represented as Bezier curves while performing physics calculations and culling operations. -Each Bezier curve has three control points. -* `v0`: the position of the grass blade on the geomtry -* `v1`: a Bezier curve guide that is always "above" `v0` with respect to the grass blade's up vector (explained soon) -* `v2`: a physical guide for which we simulate forces on - -We also need to store per-blade characteristics that will help us simulate and tessellate our grass blades correctly. -* `up`: the blade's up vector, which corresponds to the normal of the geometry that the grass blade resides on at `v0` -* Orientation: the orientation of the grass blade's face -* Height: the height of the grass blade -* Width: the width of the grass blade's face -* Stiffness coefficient: the stiffness of our grass blade, which will affect the force computations on our blade - -We can pack all this data into four `vec4`s, such that `v0.w` holds orientation, `v1.w` holds height, `v2.w` holds width, and -`up.w` holds the stiffness coefficient. - -![](img/blade_model.jpg) - -### Simulating Forces - -In this project, you will be simulating forces on grass blades while they are still Bezier curves. This will be done in a compute -shader using the compute pipeline that has been created for you. Remember that `v2` is our physical guide, so we will be -applying transformations to `v2` initially, then correcting for potential errors. We will finally update `v1` to maintain the appropriate -length of our grass blade. - -#### Binding Resources - -In order to update the state of your grass blades on every frame, you will need to create a storage buffer to maintain the grass data. -You will also need to pass information about how much time has passed in the simulation and the time since the last frame. To do this, -you can extend or create descriptor sets that will be bound to the compute pipeline. +### Total force on the grass #### Gravity -Given a gravity direction, `D.xyz`, and the magnitude of acceleration, `D.w`, we can compute the environmental gravity in -our scene as `gE = normalize(D.xyz) * D.w`. +Gravity is the downward/side ways force consisting of environment gravity and front gravity. -We then determine the contribution of the gravity with respect to the front facing direction of the blade, `f`, -as a term called the "front gravity". Front gravity is computed as `gF = (1/4) * ||gE|| * f`. +The environment gravity is a vector of the gravitational constant (~9.81) downwards on y. -We can then determine the total gravity on the grass blade as `g = gE + gF`. +The front gravity is front vector of the grass blade multiplied by the gravity constant * 1/4. This makes the grass blade slide forward slightly. #### Recovery -Recovery corresponds to the counter-force that brings our grass blade back into equilibrium. This is derived in the paper using Hooke's law. -In order to determine the recovery force, we need to compare the current position of `v2` to its original position before -simulation started, `iv2`. At the beginning of our simulation, `v1` and `v2` are initialized to be a distance of the blade height along the `up` vector. - -Once we have `iv2`, we can compute the recovery forces as `r = (iv2 - v2) * stiffness`. +Recovery is done by using Hook's law. This can be done by computing a vector that points towards the top of the grass while it is sitting straight up from the current location of the point of the blade. #### Wind -In order to simulate wind, you are at liberty to create any wind function you want! In order to have something interesting, -you can make the function depend on the position of `v0` and a function that changes with time. Consider using some combination -of sine or cosine functions. - -Your wind function will determine a wind direction that is affecting the blade, but it is also worth noting that wind has a larger impact on -grass blades whose forward directions are parallel to the wind direction. The paper describes this as a "wind alignment" term. We won't go -over the exact math here, but use the paper as a reference when implementing this. It does a great job of explaining this! - -Once you have a wind direction and a wind alignment term, your total wind force (`w`) will be `windDirection * windAlignment`. +Wind is complex. It is described in the paper by creating two forces that get mulitiplied and then time is factored into the case to make sure the wind goes from strong to weak to strong, back and forth. #### Total force -We can then determine a translation for `v2` based on the forces as `tv2 = (gravity + recovery + wind) * deltaTime`. However, we can't simply -apply this translation and expect the simulation to be robust. Our forces might push `v2` under the ground! Similarly, moving `v2` but leaving -`v1` in the same position will cause our grass blade to change length, which doesn't make sense. - -Read section 5.2 of the paper in order to learn how to determine the corrected final positions for `v1` and `v2`. +These forces are combined and mulitiplied by the deltaTime (current iteration) and then the new vertices for the top of the grass blade and the new tip of the grass is computed. ### Culling tests -Although we need to simulate forces on every grass blade at every frame, there are many blades that we won't need to render -due to a variety of reasons. Here are some heuristics we can use to cull blades that won't contribute positively to a given frame. +There are blades that should not be rendered. For example, blades that are facing away from us should not be drawned. #### Orientation culling -Consider the scenario in which the front face direction of the grass blade is perpendicular to the view vector. Since our grass blades -won't have width, we will end up trying to render parts of the grass that are actually smaller than the size of a pixel. This could -lead to aliasing artifacts. +This cull is done by checking the dot product between the front vector of the grass and the view angle. Basically, if the grass blade is facing (almost) perpendicular to the camera, the grass blade will not be drawn -In order to remedy this, we can cull these blades! Simply do a dot product test to see if the view vector and front face direction of -the blade are perpendicular. The paper uses a threshold value of `0.9` to cull, but feel free to use what you think looks best. +##### Performance: + +![](orientation_per.png) #### View-frustum culling -We also want to cull blades that are outside of the view-frustum, considering they won't show up in the frame anyway. To determine if -a grass blade is in the view-frustum, we want to compare the visibility of three points: `v0, v2, and m`, where `m = (1/4)v0 * (1/2)v1 * (1/4)v2`. -Notice that we aren't using `v1` for the visibility test. This is because the `v1` is a Bezier guide that doesn't represent a position on the grass blade. -We instead use `m` to approximate the midpoint of our Bezier curve. +View frustum culling is done by checking if the three points of the blade is within the view frustrum. + +##### Performance: + +![](view_per.png) -If all three points are outside of the view-frustum, we will cull the grass blade. The paper uses a tolerance value for this test so that we are culling -blades a little more conservatively. This can help with cases in which the Bezier curve is technically not visible, but we might be able to see the blade -if we consider its width. +View frustum culling is improved even more as more grass blades are behind the screen/not in the view of the user. + +*this is measure 1/2 in the grass* #### Distance culling -Similarly to orientation culling, we can end up with grass blades that at large distances are smaller than the size of a pixel. This could lead to additional -artifacts in our renders. In this case, we can cull grass blades as a function of their distance from the camera. +This is done by checking the distance from the camera. We place the blades into buckets and if the are in not in the distance, the blades are culled -You are free to define two parameters here. -* A max distance afterwhich all grass blades will be culled. -* A number of buckets to place grass blades between the camera and max distance into. +##### Performance: -Define a function such that the grass blades in the bucket closest to the camera are kept while an increasing number of grass blades -are culled with each farther bucket. +![](distance_per.png) -#### Occlusion culling (extra credit) +*this is measured when ~ half the grass is culled* -This type of culling only makes sense if our scene has additional objects aside from the plane and the grass blades. We want to cull grass blades that -are occluded by other geometry. Think about how you can use a depth map to accomplish this! +Distance culling is more effective when more grass is culled (aka more distance is between the grass and camera) -### Tessellating Bezier curves into grass blades +### Performance Analysis -In this project, you should pass in each Bezier curve as a single patch to be processed by your grass graphics pipeline. You will tessellate this patch into -a quad with a shape of your choosing (as long as it looks sufficiently like grass of course). The paper has some examples of grass shapes you can use as inspiration. +#### Increasing grass blades (with culling enabled) -In the tessellation control shader, specify the amount of tessellation you want to occur. Remember that you need to provide enough detail to create the curvature of a grass blade. +![](grass_per.png) -The generated vertices will be passed to the tessellation evaluation shader, where you will place the vertices in world space, respecting the width, height, and orientation information -of each blade. Once you have determined the world space position of each vector, make sure to set the output `gl_Position` in clip space! +*this is measured when ~ half the grass is culled* -** Extra Credit**: Tessellate to varying levels of detail as a function of how far the grass blade is from the camera. For example, if the blade is very far, only generate four vertices in the tessellation control shader. +The FPS decreases over time, but really goes downward towards the end. -To build more intuition on how tessellation works, I highly recommend playing with the [helloTessellation sample](https://github.com/CIS565-Fall-2018/Vulkan-Samples/tree/master/samples/5_helloTessellation) -and reading this [tutorial on tessellation](http://in2gpu.com/2014/07/12/tessellation-tutorial-opengl-4-3/). +#### The culling performances are described above. ## Resources ### Links -The following resources may be useful for this project. - * [Responsive Real-Time Grass Grass Rendering for General 3D Scenes](https://www.cg.tuwien.ac.at/research/publications/2017/JAHRMANN-2017-RRTG/JAHRMANN-2017-RRTG-draft.pdf) * [CIS565 Vulkan samples](https://github.com/CIS565-Fall-2018/Vulkan-Samples) * [Official Vulkan documentation](https://www.khronos.org/registry/vulkan/) @@ -255,46 +114,3 @@ The following resources may be useful for this project. * [RenderDoc blog on Vulkan](https://renderdoc.org/vulkan-in-30-minutes.html) * [Tessellation tutorial](http://in2gpu.com/2014/07/12/tessellation-tutorial-opengl-4-3/) - -## Third-Party Code Policy - -* Use of any third-party code must be approved by asking on our Google Group. -* If it is approved, all students are welcome to use it. Generally, we approve - use of third-party code that is not a core part of the project. For example, - for the path tracer, we would approve using a third-party library for loading - models, but would not approve copying and pasting a CUDA function for doing - refraction. -* Third-party code **MUST** be credited in README.md. -* Using third-party code without its approval, including using another - student's code, is an academic integrity violation, and will, at minimum, - result in you receiving an F for the semester. - - -## README - -* A brief description of the project and the specific features you implemented. -* GIFs of your project in its different stages with the different features being added incrementally. -* A performance analysis (described below). - -### Performance Analysis - -The performance analysis is where you will investigate how... -* Your renderer handles varying numbers of grass blades -* The improvement you get by culling using each of the three culling tests - -## Submit - -If you have modified any of the `CMakeLists.txt` files at all (aside from the -list of `SOURCE_FILES`), mentions it explicity. -Beware of any build issues discussed on the Google Group. - -Open a GitHub pull request so that we can see that you have finished. -The title should be "Project 6: YOUR NAME". -The template of the comment section of your pull request is attached below, you can do some copy and paste: - -* [Repo Link](https://link-to-your-repo) -* (Briefly) Mentions features that you've completed. Especially those bells and whistles you want to highlight - * Feature 0 - * Feature 1 - * ... -* Feedback on the project itself, if any. diff --git a/distance_per.png b/distance_per.png new file mode 100644 index 0000000..a364732 Binary files /dev/null and b/distance_per.png differ diff --git a/distancecull.gif b/distancecull.gif new file mode 100644 index 0000000..84857f8 Binary files /dev/null and b/distancecull.gif differ diff --git a/everything.gif b/everything.gif new file mode 100644 index 0000000..df64f5a Binary files /dev/null and b/everything.gif differ diff --git a/grass_per.png b/grass_per.png new file mode 100644 index 0000000..e24bde7 Binary files /dev/null and b/grass_per.png differ diff --git a/main.gif b/main.gif new file mode 100644 index 0000000..178f155 Binary files /dev/null and b/main.gif differ diff --git a/not-moving.gif b/not-moving.gif new file mode 100644 index 0000000..9233674 Binary files /dev/null and b/not-moving.gif differ diff --git a/orientation_per.png b/orientation_per.png new file mode 100644 index 0000000..4e821f8 Binary files /dev/null and b/orientation_per.png differ diff --git a/orientationcull.gif b/orientationcull.gif new file mode 100644 index 0000000..ff43f52 Binary files /dev/null and b/orientationcull.gif differ diff --git a/src/Blades.h b/src/Blades.h index 9bd1eed..914dc1d 100644 --- a/src/Blades.h +++ b/src/Blades.h @@ -4,7 +4,7 @@ #include #include "Model.h" -constexpr static unsigned int NUM_BLADES = 1 << 13; +constexpr static unsigned int NUM_BLADES = 1 << 14; constexpr static float MIN_HEIGHT = 1.3f; constexpr static float MAX_HEIGHT = 2.5f; constexpr static float MIN_WIDTH = 0.1f; diff --git a/src/Renderer.cpp b/src/Renderer.cpp index b445d04..e04d910 100644 --- a/src/Renderer.cpp +++ b/src/Renderer.cpp @@ -198,6 +198,39 @@ void Renderer::CreateComputeDescriptorSetLayout() { // TODO: Create the descriptor set layout for the compute pipeline // Remember this is like a class definition stating why types of information // will be stored at each binding + + VkDescriptorSetLayoutBinding blades_layout_binding = {}; + blades_layout_binding.binding = 0; + blades_layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + blades_layout_binding.descriptorCount = 1; + blades_layout_binding.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT; + blades_layout_binding.pImmutableSamplers = nullptr; + + VkDescriptorSetLayoutBinding culled_layout_binding = {}; + culled_layout_binding.binding = 1; + culled_layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + culled_layout_binding.descriptorCount = 1; + culled_layout_binding.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT; + culled_layout_binding.pImmutableSamplers = nullptr; + + VkDescriptorSetLayoutBinding blades_num_layout_binding = {}; + blades_num_layout_binding.binding = 2; + blades_num_layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + blades_num_layout_binding.descriptorCount = 1; + blades_num_layout_binding.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT; + blades_num_layout_binding.pImmutableSamplers = nullptr; + + std::vector bindings{ blades_layout_binding, culled_layout_binding, blades_num_layout_binding }; + + // Create the descriptor set layout + VkDescriptorSetLayoutCreateInfo layoutInfo = {}; + layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; + layoutInfo.bindingCount = static_cast(bindings.size()); + layoutInfo.pBindings = bindings.data(); + + if (vkCreateDescriptorSetLayout(logicalDevice, &layoutInfo, nullptr, &compute_descriptor_set_layout) != VK_SUCCESS) { + throw std::runtime_error("Failed to create descriptor set layout"); + } } void Renderer::CreateDescriptorPool() { @@ -216,8 +249,10 @@ void Renderer::CreateDescriptorPool() { { VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER , 1 }, // TODO: Add any additional types and counts of descriptors you will need to allocate + { VK_DESCRIPTOR_TYPE_STORAGE_BUFFER , static_cast(compute_descriptor_set_layout_size * scene->GetBlades().size()) } }; + VkDescriptorPoolCreateInfo poolInfo = {}; poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; poolInfo.poolSizeCount = static_cast(poolSizes.size()); @@ -320,6 +355,42 @@ void Renderer::CreateModelDescriptorSets() { void Renderer::CreateGrassDescriptorSets() { // TODO: Create Descriptor sets for the grass. // This should involve creating descriptor sets which point to the model matrix of each group of grass blades + grass_descriptor_sets.resize(scene->GetBlades().size()); + + // Describe the desciptor set + VkDescriptorSetLayout layouts[] = { modelDescriptorSetLayout }; + VkDescriptorSetAllocateInfo allocInfo = {}; + allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; + allocInfo.descriptorPool = descriptorPool; + allocInfo.descriptorSetCount = static_cast(grass_descriptor_sets.size()); + allocInfo.pSetLayouts = layouts; + + // Allocate descriptor sets + if (vkAllocateDescriptorSets(logicalDevice, &allocInfo, grass_descriptor_sets.data()) != VK_SUCCESS) { + throw std::runtime_error("Failed to allocate descriptor set"); + } + + std::vector descriptorWrites(grass_descriptor_sets.size()); + + for (uint32_t i = 0; i < scene->GetBlades().size(); ++i) { + VkDescriptorBufferInfo modelBufferInfo = {}; + modelBufferInfo.buffer = scene->GetBlades()[i]->GetBladesBuffer(); + modelBufferInfo.offset = 0; + modelBufferInfo.range = sizeof(ModelBufferObject); + + descriptorWrites[i].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + descriptorWrites[i].dstSet = grass_descriptor_sets[i]; + descriptorWrites[i].dstBinding = 0; + descriptorWrites[i].dstArrayElement = 0; + descriptorWrites[i].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; + descriptorWrites[i].descriptorCount = 1; + descriptorWrites[i].pBufferInfo = &modelBufferInfo; + descriptorWrites[i].pImageInfo = nullptr; + descriptorWrites[i].pTexelBufferView = nullptr; + } + + // Update descriptor sets + vkUpdateDescriptorSets(logicalDevice, static_cast(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr); } void Renderer::CreateTimeDescriptorSet() { @@ -360,6 +431,77 @@ void Renderer::CreateTimeDescriptorSet() { void Renderer::CreateComputeDescriptorSets() { // TODO: Create Descriptor sets for the compute pipeline // The descriptors should point to Storage buffers which will hold the grass blades, the culled grass blades, and the output number of grass blades + compute_descriptor_sets.resize(scene->GetBlades().size()); + + // Describe the desciptor set + VkDescriptorSetLayout layouts[] = { compute_descriptor_set_layout }; + VkDescriptorSetAllocateInfo allocInfo = {}; + allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; + allocInfo.descriptorPool = descriptorPool; + allocInfo.descriptorSetCount = static_cast(compute_descriptor_sets.size()); + allocInfo.pSetLayouts = layouts; + + // Allocate descriptor sets + if (vkAllocateDescriptorSets(logicalDevice, &allocInfo, compute_descriptor_sets.data()) != VK_SUCCESS) { + throw std::runtime_error("Failed to allocate descriptor set"); + } + + std::vector descriptorWrites(compute_descriptor_set_layout_size * compute_descriptor_sets.size()); + + for (uint32_t i = 0; i < scene->GetBlades().size(); ++i) { + VkDescriptorBufferInfo blades_buffer_info = {}; + blades_buffer_info.buffer = scene->GetBlades()[i]->GetBladesBuffer(); + blades_buffer_info.offset = 0; + blades_buffer_info.range = NUM_BLADES * sizeof(Blade); + + // Bind image and sampler resources to the descriptor + VkDescriptorBufferInfo cull_buffer_info = {}; + cull_buffer_info.buffer = scene->GetBlades()[i]->GetCulledBladesBuffer(); + cull_buffer_info.offset = 0; + cull_buffer_info.range = NUM_BLADES * sizeof(Blade); + + VkDescriptorBufferInfo blades_num_buffer_info = {}; + blades_num_buffer_info.buffer = scene->GetBlades()[i]->GetNumBladesBuffer(); + blades_num_buffer_info.offset = 0; + blades_num_buffer_info.range = sizeof(BladeDrawIndirect); + + int blades_index = compute_descriptor_set_layout_size * i; + int cull_index = compute_descriptor_set_layout_size * i + 1; + int blades_num_index = compute_descriptor_set_layout_size * i + 2; + + descriptorWrites[blades_index].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + descriptorWrites[blades_index].dstSet = compute_descriptor_sets[i]; + descriptorWrites[blades_index].dstBinding = 0; + descriptorWrites[blades_index].dstArrayElement = 0; + descriptorWrites[blades_index].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + descriptorWrites[blades_index].descriptorCount = 1; + descriptorWrites[blades_index].pBufferInfo = &blades_buffer_info; + descriptorWrites[blades_index].pImageInfo = nullptr; + descriptorWrites[blades_index].pTexelBufferView = nullptr; + + descriptorWrites[cull_index].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + descriptorWrites[cull_index].dstSet = compute_descriptor_sets[i]; + descriptorWrites[cull_index].dstBinding = 1; + descriptorWrites[cull_index].dstArrayElement = 0; + descriptorWrites[cull_index].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + descriptorWrites[cull_index].descriptorCount = 1; + descriptorWrites[cull_index].pBufferInfo = &cull_buffer_info; + descriptorWrites[cull_index].pImageInfo = nullptr; + descriptorWrites[cull_index].pTexelBufferView = nullptr; + + descriptorWrites[blades_num_index].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + descriptorWrites[blades_num_index].dstSet = compute_descriptor_sets[i]; + descriptorWrites[blades_num_index].dstBinding = 2; + descriptorWrites[blades_num_index].dstArrayElement = 0; + descriptorWrites[blades_num_index].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + descriptorWrites[blades_num_index].descriptorCount = 1; + descriptorWrites[blades_num_index].pBufferInfo = &blades_num_buffer_info; + descriptorWrites[blades_num_index].pImageInfo = nullptr; + descriptorWrites[blades_num_index].pTexelBufferView = nullptr; + } + + // Update descriptor sets + vkUpdateDescriptorSets(logicalDevice, static_cast(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr); } void Renderer::CreateGraphicsPipeline() { @@ -717,7 +859,7 @@ void Renderer::CreateComputePipeline() { computeShaderStageInfo.pName = "main"; // TODO: Add the compute dsecriptor set layout you create to this list - std::vector descriptorSetLayouts = { cameraDescriptorSetLayout, timeDescriptorSetLayout }; + std::vector descriptorSetLayouts = { cameraDescriptorSetLayout, timeDescriptorSetLayout, compute_descriptor_set_layout }; // Create pipeline layout VkPipelineLayoutCreateInfo pipelineLayoutInfo = {}; @@ -884,6 +1026,10 @@ void Renderer::RecordComputeCommandBuffer() { vkCmdBindDescriptorSets(computeCommandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, computePipelineLayout, 1, 1, &timeDescriptorSet, 0, nullptr); // TODO: For each group of blades bind its descriptor set and dispatch + for(const auto& compute_descriptor_set : compute_descriptor_sets) { + vkCmdBindDescriptorSets(computeCommandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, computePipelineLayout, 2, 1, &compute_descriptor_set, 0, nullptr); + vkCmdDispatch(computeCommandBuffer, (NUM_BLADES + WORKGROUP_SIZE - 1) / WORKGROUP_SIZE, 1, 1); + } // ~ End recording ~ if (vkEndCommandBuffer(computeCommandBuffer) != VK_SUCCESS) { @@ -976,13 +1122,14 @@ void Renderer::RecordCommandBuffers() { VkBuffer vertexBuffers[] = { scene->GetBlades()[j]->GetCulledBladesBuffer() }; VkDeviceSize offsets[] = { 0 }; // TODO: Uncomment this when the buffers are populated - // vkCmdBindVertexBuffers(commandBuffers[i], 0, 1, vertexBuffers, offsets); + vkCmdBindVertexBuffers(commandBuffers[i], 0, 1, vertexBuffers, offsets); // TODO: Bind the descriptor set for each grass blades model + vkCmdBindDescriptorSets(commandBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, graphicsPipelineLayout, 1, 1, &grass_descriptor_sets[j], 0, nullptr); // Draw // TODO: Uncomment this when the buffers are populated - // vkCmdDrawIndirect(commandBuffers[i], scene->GetBlades()[j]->GetNumBladesBuffer(), 0, 1, sizeof(BladeDrawIndirect)); + vkCmdDrawIndirect(commandBuffers[i], scene->GetBlades()[j]->GetNumBladesBuffer(), 0, 1, sizeof(BladeDrawIndirect)); } // End render pass @@ -1042,6 +1189,8 @@ Renderer::~Renderer() { vkDeviceWaitIdle(logicalDevice); // TODO: destroy any resources you created + vkDestroyDescriptorSetLayout(logicalDevice, compute_descriptor_set_layout, nullptr); + vkFreeCommandBuffers(logicalDevice, graphicsCommandPool, static_cast(commandBuffers.size()), commandBuffers.data()); vkFreeCommandBuffers(logicalDevice, computeCommandPool, 1, &computeCommandBuffer); diff --git a/src/Renderer.h b/src/Renderer.h index 95e025f..ae429fc 100644 --- a/src/Renderer.h +++ b/src/Renderer.h @@ -63,6 +63,11 @@ class Renderer { std::vector modelDescriptorSets; VkDescriptorSet timeDescriptorSet; + VkDescriptorSetLayout compute_descriptor_set_layout; + static constexpr int compute_descriptor_set_layout_size = 3; + std::vector compute_descriptor_sets; + std::vector grass_descriptor_sets; + VkPipelineLayout graphicsPipelineLayout; VkPipelineLayout grassPipelineLayout; VkPipelineLayout computePipelineLayout; diff --git a/src/shaders/compute.comp b/src/shaders/compute.comp index 0fd0224..17244c5 100644 --- a/src/shaders/compute.comp +++ b/src/shaders/compute.comp @@ -36,6 +36,21 @@ struct Blade { // uint firstInstance; // = 0 // } numBlades; +layout(set = 2, binding = 0) buffer blades { + Blade blades_[]; +}; + +layout(set = 2, binding = 1) buffer CullBlades { + Blade cullBlades[]; +}; + +layout(set = 2, binding = 2) buffer NumBlades { + uint vertexCount; // Write the number of blades remaining here + uint instanceCount; // = 1 + uint firstVertex; // = 0 + uint firstInstance; // = 0 +} numBlades; + bool inBounds(float value, float bounds) { return (value >= -bounds) && (value <= bounds); } @@ -43,14 +58,126 @@ bool inBounds(float value, float bounds) { void main() { // Reset the number of blades to 0 if (gl_GlobalInvocationID.x == 0) { - // numBlades.vertexCount = 0; + numBlades.vertexCount = 0; } barrier(); // Wait till all threads reach this point + + uint i = gl_GlobalInvocationID.x; + Blade cur_blade = blades_[i]; + + // Position and direction + vec3 v0 = cur_blade.v0.xyz; + float direction = cur_blade.v0.w; + + // Bezier point and height + vec3 v1 = cur_blade.v1.xyz; + float height = cur_blade.v1.w; + + // Physical model guide and width + vec3 v2 = cur_blade.v2.xyz; + float width = cur_blade.v2.w; + + // Up vector and stiffness coefficient + vec3 up = cur_blade.up.xyz; + float stiffness = cur_blade.up.w; + + //r = (Iv2 - v2) * s + //basically a direction upwards towards v1 + vec3 total_height = v0 + up * height; + vec3 recovery_force = (total_height - v2) * stiffness; + + // environmental gravity (GE) + // It can be a global gravity direction that is the same for the whole scene + vec3 GE = vec3(0.0, -9.81, 0.0); + + // front gravity (GF) + // gf = 1/4 |GE| * front direction (perpendicular to width of blade) + float x_direction = cos(direction); + float y_direction = sin(direction); + vec3 right = vec3(x_direction, 0.0, y_direction); + vec3 front = normalize(cross(right, up)); + vec3 GF = 1.0 / 4.0 * abs(-9.81) * front; + + //total gravitational force + vec3 gravity = GE + GF; + + //wind calculations from the paper + vec3 wind_direction = vec3(1.0); + float FD = 1.0 - abs(dot(normalize(wind_direction), normalize(v2 - v0))); + float FR = dot(v2 - v0, up) / height; - // TODO: Apply forces on every blade and update the vertices in the buffer + //calculate total wind based on time + float wind_multiple = 3.0; + vec3 wind = wind_multiple * wind_direction * FD * FR * cos(totalTime); + + //add all forces together and multiply by delta time + vec3 trans_dt = (recovery_force + wind + gravity) * deltaTime; + + //state validation + //calculating new v2 + v2 = v2 + trans_dt; + v2 = v2 - up * min(dot(up, (v2 - v0)), 0.0); + + //calculating new v1 + vec3 l_projection = abs(v2 - v0 - up * dot((v2 - v0), up)); + v1 = v0 + height * up * max((1.0 - l_projection) / height, 0.05 * max((l_projection/height), 1.0)); + + //approximate bezier curve + //lengths of points + //L0 indicates the distance between the first and the last control + //point and L1 is the sum of all distances between a control point and + //its subsequent one + float L0 = distance(v0, v2); + float L1 = distance(v0, v1) + distance(v1, v2); + + //length of beizer + float n = 1.5; + float L = (n * L0 + (n - 1.0) * L1) / (n + 1.0); + float r = height / L; + + vec3 v1_c = v0 + r * (v1 - v0); + vec3 v2_c = v1_c + r * (v2 - v1); + + blades_[i].v1.xyz = v1_c; + blades_[i].v2.xyz = v2_c; + + //culling + + + //orientation test + vec3 dir_b = front; + vec4 eye_world = inverse(camera.view) * vec4(0.0, 0.0, 0.0, 1.0); + vec3 dir_c = eye_world.xyz - v0; + + if(0.6 < dot(dir_c, dir_b)) + { + return; + } + + //view frustrum cull + vec4 v0_cull = camera.proj * camera.view * vec4(v0, 1.0); + vec4 v2_cull = camera.proj * camera.view * vec4(v2, 1.0); + vec4 m_cull = camera.proj * camera.view * vec4(v0 * 0.25 + v1 * 0.5 + v2 * 0.25, 1.0); + float t_ = 0.5; + if(!inBounds(v0_cull.x, v0_cull.w + t_) || !inBounds(v0_cull.y, v0_cull.w + t_) || + !inBounds(v2_cull.x, v2_cull.w + t_) || !inBounds(v2_cull.y, v2_cull.w + t_) || + !inBounds(m_cull.x, m_cull.w + t_) || !inBounds(m_cull.y, m_cull.w + t_) + ) + { + return; + } + + //distance cull + float n_ = 5.0; + float d_proj = length(v0 - eye_world.xyz - dot((v0 - eye_world.xyz), up) * up); + float d_max = 30.0; + if(floor(n_ * (1.0 - d_proj/d_max)) < mod(i, n_)) + { + return; + } + - // TODO: Cull blades that are too far away or not in the camera frustum and write them - // to the culled blades buffer - // Note: to do this, you will need to use an atomic operation to read and update numBlades.vertexCount - // You want to write the visible blades to the buffer without write conflicts between threads + //update the vertex cound and index the cull blades + uint new_v = atomicAdd(numBlades.vertexCount, 1); + cullBlades[new_v] = blades_[i]; } diff --git a/src/shaders/grass.frag b/src/shaders/grass.frag index c7df157..3d66cd0 100644 --- a/src/shaders/grass.frag +++ b/src/shaders/grass.frag @@ -7,11 +7,14 @@ layout(set = 0, binding = 0) uniform CameraBufferObject { } camera; // TODO: Declare fragment shader inputs - -layout(location = 0) out vec4 outColor; +layout(location = 0) in vec4 normal; +layout(location = 0) out vec3 outColor; void main() { // TODO: Compute fragment color - outColor = vec4(1.0); + vec3 light_green = vec3(0.0, 0.93, 0.0); + vec3 dark_green = vec3(0.0, 0.55, 0.20); + + outColor = vec3(normal.w * light_green + (1.0 - normal.w) * dark_green); } diff --git a/src/shaders/grass.tesc b/src/shaders/grass.tesc index f9ffd07..210d614 100644 --- a/src/shaders/grass.tesc +++ b/src/shaders/grass.tesc @@ -9,18 +9,28 @@ layout(set = 0, binding = 0) uniform CameraBufferObject { } camera; // TODO: Declare tessellation control shader inputs and outputs +layout(location = 0) in vec4 o_v0[]; +layout(location = 1) in vec4 o_v1[]; +layout(location = 2) in vec4 o_v2[]; + +layout(location = 0) out vec4 t_v0[]; +layout(location = 1) out vec4 t_v1[]; +layout(location = 2) out vec4 t_v2[]; void main() { // Don't move the origin location of the patch gl_out[gl_InvocationID].gl_Position = gl_in[gl_InvocationID].gl_Position; // TODO: Write any shader outputs + t_v0[gl_InvocationID] = o_v0[gl_InvocationID]; + t_v1[gl_InvocationID] = o_v1[gl_InvocationID]; + t_v2[gl_InvocationID] = o_v2[gl_InvocationID]; // TODO: Set level of tesselation - // gl_TessLevelInner[0] = ??? - // gl_TessLevelInner[1] = ??? - // gl_TessLevelOuter[0] = ??? - // gl_TessLevelOuter[1] = ??? - // gl_TessLevelOuter[2] = ??? - // gl_TessLevelOuter[3] = ??? + gl_TessLevelInner[0] = 5; + gl_TessLevelInner[1] = 5; + gl_TessLevelOuter[0] = 5; + gl_TessLevelOuter[1] = 5; + gl_TessLevelOuter[2] = 5; + gl_TessLevelOuter[3] = 5; } diff --git a/src/shaders/grass.tese b/src/shaders/grass.tese index 751fff6..b185f97 100644 --- a/src/shaders/grass.tese +++ b/src/shaders/grass.tese @@ -9,10 +9,41 @@ layout(set = 0, binding = 0) uniform CameraBufferObject { } camera; // TODO: Declare tessellation evaluation shader inputs and outputs +layout(location = 0) in vec4 t_v0[]; +layout(location = 1) in vec4 t_v1[]; +layout(location = 2) in vec4 t_v2[]; + +layout(location = 0) out vec4 normal; void main() { float u = gl_TessCoord.x; float v = gl_TessCoord.y; - // TODO: Use u and v to parameterize along the grass blade and output positions for each vertex of the grass blade + vec3 v0 = t_v0[0].xyz; + vec3 v1 = t_v1[0].xyz; + vec3 v2 = t_v2[0].xyz; + + float width = t_v2[0].w; + float direction = t_v0[0].w; + vec3 t1 = vec3(cos(direction), 0.0, sin(direction)); + + float threshold = 0.9; + + //perform the same as described in paper + + vec3 a = v0 + v * (v1 - v0); + vec3 b = v1 + v * (v2 - v1); + vec3 c = a + v * (b - a); + + vec3 c0 = c - width * t1; + vec3 c1 = c + width * t1; + + normal.xyz = normalize(b - a); + normal.w = v; + + float t = 0.5 + (u - 0.5) * (1.0 - (max(v - threshold, 0.0) / (1.0 - threshold))); + vec3 position = (1.0 - t) * c0 + t * c1; + + //transfer to world space + gl_Position = camera.proj * camera.view * vec4(position, 1.0); } diff --git a/src/shaders/grass.vert b/src/shaders/grass.vert index db9dfe9..be65f97 100644 --- a/src/shaders/grass.vert +++ b/src/shaders/grass.vert @@ -8,10 +8,24 @@ layout(set = 1, binding = 0) uniform ModelBufferObject { // TODO: Declare vertex shader inputs and outputs +layout(location = 0) in vec4 i_v0; +layout(location = 1) in vec4 i_v1; +layout(location = 2) in vec4 i_v2; + +layout(location = 0) out vec4 o_v0; +layout(location = 1) out vec4 o_v1; +layout(location = 2) out vec4 o_v2; + out gl_PerVertex { vec4 gl_Position; }; void main() { // TODO: Write gl_Position and any other shader outputs + + o_v0 = i_v0; + o_v1 = i_v1; + o_v2 = i_v2; + + gl_Position = vec4(i_v0.x, i_v0.y, i_v0.z, 1.0); } diff --git a/view_per.png b/view_per.png new file mode 100644 index 0000000..4f5a94d Binary files /dev/null and b/view_per.png differ diff --git a/viewcull.gif b/viewcull.gif new file mode 100644 index 0000000..5930600 Binary files /dev/null and b/viewcull.gif differ