diff --git a/.gitignore b/.gitignore index 378eac2..9eca9b6 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ build +bin diff --git a/Instruction.md b/Instruction.md new file mode 100644 index 0000000..35bd73b --- /dev/null +++ b/Instruction.md @@ -0,0 +1,313 @@ +Grass Tessellation on Vulkan +====================== + +**University of Pennsylvania, CIS 565: GPU Programming and Architecture, Project 5** + +**Anantha Srinivas** +[LinkedIn](https://www.linkedin.com/in/anantha-srinivas-00198958/), [Twitter](https://twitter.com/an2tha) + +**Tested on:** +* Windows 10, i7-8700 @ 3.20GHz 16GB, GTX 1080 8097MB (PC) + +# Introduction + + +# Implementation Details + +# Performance Analysis + +**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. + +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. + +![](img/grass.gif) ![](img/grass2.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! + +**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! + +### Contents + +* `src/` C++/Vulkan source files. + * `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 + +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. + +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. + +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. + +#### 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`. + +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`. + +We can then determine the total gravity on the grass blade as `g = gE + gF`. + +#### 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`. + +#### 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`. + +#### 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`. + +### 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. + +#### 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. + +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. + +#### 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. + +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. + +#### 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. + +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. + +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. + +#### Occlusion culling (extra credit) + +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! + +### Tessellating Bezier curves into grass blades + +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. + +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. + +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! + +** 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. + +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/). + +## 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/) +* [Vulkan tutorial](https://vulkan-tutorial.com/) +* [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/README.md b/README.md index fc0e545..b83d612 100644 --- a/README.md +++ b/README.md @@ -1,252 +1,85 @@ -Instructions - Vulkan Grass Rendering -======================== +Grass Tessellation on Vulkan +====================== -This is due **Sunday 11/4, evening at midnight**. +**University of Pennsylvania, CIS 565: GPU Programming and Architecture, Project 5** -**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. +**Anantha Srinivas** +[LinkedIn](https://www.linkedin.com/in/anantha-srinivas-00198958/), [Twitter](https://twitter.com/an2tha) -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. +**Tested on:** +* Windows 10, i7-8700 @ 3.20GHz 16GB, GTX 1080 8097MB (PC) -![](img/grass.gif) ![](img/grass2.gif) +![](img/output.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! +# Introduction -**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! - -### Contents - -* `src/` C++/Vulkan source files. - * `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 - -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. - -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. - -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. +This implementation of grass rendering is based on the paper [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) ![](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. +In its most basic form, each blade of grass can be thought of as a Bezier curve, with three control points v0, v1 and v2 as shown in the figure. Using tessellation shader we either add more points or reduce them based on factors such as distance from camera. -#### Binding Resources +# Implementation Details -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. +## Simulating forces +1) Gravity: -#### Gravity +|No gravity| Gravity| +|----| ----| +|![](img/no_gravity.PNG)|![](img/gravity.PNG)| -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`. +2) Recovery: +This is the force that brings back the grass to its initial rest position. Seen in Figure 1. -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`. +3) Wind Force: +An external force that changes the orienation of the grass blade. Seen in Figure 1. -We can then determine the total gravity on the grass blade as `g = gE + gF`. +## Culling tests -#### Recovery +1) Orientation Culling -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. +|No Culling| With Culling| +|----| ----| +|![](img/no_orient_culling.PNG)|![](img/orient_culling.PNG)| -Once we have `iv2`, we can compute the recovery forces as `r = (iv2 - v2) * stiffness`. +2) View-frustrum culling -#### Wind +Here we cull the grass blades that do not lie in the view frustrum. Unfortunalty we wont be able to see its effect, since it will be offscreen. However, we can always refer to the performance improvements. -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. +3) Distance Culling -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! +|No Culling| With Culling| +|----| ----| +|![](img/with_distance_culling.PNG)|![](img/distance_culling.PNG)| -Once you have a wind direction and a wind alignment term, your total wind force (`w`) will be `windDirection * windAlignment`. +# Performance Analysis -#### Total force +## Testing Conditions +1) V-Sync turned off +2) Run in Debug mdoe +3) Performance read using VK_LAYER_LUNARG_monitor extension +4) Number of grass blades = 2 ^ 20. Dimensions of quad is 150 x 150 -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. +## Performance of different types of culling -Read section 5.2 of the paper in order to learn how to determine the corrected final positions for `v1` and `v2`. +![](img/performance.png) -### Culling tests +From the above graph we can clearly see that culling of unnecessary geometry has a great performance impact. We can conclude: -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. +1) Frustum culling has the best performance improvements. +2) Distance culling also has levels of improvements, however with this testing scenario, the max distance was close to full size to simulate game like situation. +3) Orientation culling can only slightly depending upon the threshold chosen for angle cutoff. -#### Orientation culling +## Performance of different levels of tessellations -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. +![](img/performance2.png) -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. +* In case of constant tessellations, the outer edges were subdivided into 15 regions. +* In case of distance based tessellation, the outer edges were subdivided betwwen 1 and 15 subedges, depending upon the distance of the grass blade from camera. -#### View-frustum culling +# Credits -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. - -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. - -#### 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. - -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. - -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. - -#### Occlusion culling (extra credit) - -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! - -### Tessellating Bezier curves into grass blades - -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. - -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. - -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! - -** 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. - -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/). - -## Resources - -### Links - -The following resources may be useful for this project. +The following resources were used in the implementation of 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) @@ -254,47 +87,3 @@ The following resources may be useful for this project. * [Vulkan tutorial](https://vulkan-tutorial.com/) * [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/img/distance_culling.PNG b/img/distance_culling.PNG new file mode 100644 index 0000000..5ba62c9 Binary files /dev/null and b/img/distance_culling.PNG differ diff --git a/img/gravity.PNG b/img/gravity.PNG new file mode 100644 index 0000000..5de97f6 Binary files /dev/null and b/img/gravity.PNG differ diff --git a/img/no_gravity.PNG b/img/no_gravity.PNG new file mode 100644 index 0000000..3101511 Binary files /dev/null and b/img/no_gravity.PNG differ diff --git a/img/no_orient_culling.PNG b/img/no_orient_culling.PNG new file mode 100644 index 0000000..43505a4 Binary files /dev/null and b/img/no_orient_culling.PNG differ diff --git a/img/orient_culling.PNG b/img/orient_culling.PNG new file mode 100644 index 0000000..5e391bd Binary files /dev/null and b/img/orient_culling.PNG differ diff --git a/img/output.gif b/img/output.gif new file mode 100644 index 0000000..092ae97 Binary files /dev/null and b/img/output.gif differ diff --git a/img/performance.png b/img/performance.png new file mode 100644 index 0000000..4a8e37e Binary files /dev/null and b/img/performance.png differ diff --git a/img/performance2.png b/img/performance2.png new file mode 100644 index 0000000..3c33288 Binary files /dev/null and b/img/performance2.png differ diff --git a/img/with_distance_culling.PNG b/img/with_distance_culling.PNG new file mode 100644 index 0000000..bcf1c73 Binary files /dev/null and b/img/with_distance_culling.PNG differ diff --git a/src/Blades.cpp b/src/Blades.cpp index 80e3d76..a8652a1 100644 --- a/src/Blades.cpp +++ b/src/Blades.cpp @@ -44,8 +44,8 @@ Blades::Blades(Device* device, VkCommandPool commandPool, float planeDim) : Mode indirectDraw.firstVertex = 0; indirectDraw.firstInstance = 0; - BufferUtils::CreateBufferFromData(device, commandPool, blades.data(), NUM_BLADES * sizeof(Blade), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, bladesBuffer, bladesBufferMemory); - BufferUtils::CreateBuffer(device, NUM_BLADES * sizeof(Blade), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, culledBladesBuffer, culledBladesBufferMemory); + BufferUtils::CreateBufferFromData(device, commandPool, blades.data(), NUM_BLADES * sizeof(Blade), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT , bladesBuffer, bladesBufferMemory); + BufferUtils::CreateBuffer(device, NUM_BLADES * sizeof(Blade), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT , VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, culledBladesBuffer, culledBladesBufferMemory); BufferUtils::CreateBufferFromData(device, commandPool, &indirectDraw, sizeof(BladeDrawIndirect), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT, numBladesBuffer, numBladesBufferMemory); } diff --git a/src/Blades.h b/src/Blades.h index 9bd1eed..ed7e2de 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 << 20; 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/Instance.cpp b/src/Instance.cpp index 7c4d9a2..8387f09 100644 --- a/src/Instance.cpp +++ b/src/Instance.cpp @@ -11,7 +11,8 @@ const bool ENABLE_VALIDATION = true; namespace { const std::vector validationLayers = { - "VK_LAYER_LUNARG_standard_validation" + "VK_LAYER_LUNARG_standard_validation", + "VK_LAYER_LUNARG_monitor" }; // Get the required list of extensions based on whether validation layers are enabled diff --git a/src/Renderer.cpp b/src/Renderer.cpp index b445d04..7dd6006 100644 --- a/src/Renderer.cpp +++ b/src/Renderer.cpp @@ -19,6 +19,7 @@ Renderer::Renderer(Device* device, SwapChain* swapChain, Scene* scene, Camera* c CreateRenderPass(); CreateCameraDescriptorSetLayout(); CreateModelDescriptorSetLayout(); + CreateGrassDescriptorSetLayout(); CreateTimeDescriptorSetLayout(); CreateComputeDescriptorSetLayout(); CreateDescriptorPool(); @@ -172,6 +173,30 @@ void Renderer::CreateModelDescriptorSetLayout() { } } +void Renderer::CreateGrassDescriptorSetLayout() +{ + // Describe the layout bindings for the model matrices for each of the grass blades + VkDescriptorSetLayoutBinding uboLayoutBinding = {}; + uboLayoutBinding.binding = 0; + uboLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; + uboLayoutBinding.descriptorCount = 1; + uboLayoutBinding.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT; + uboLayoutBinding.pImmutableSamplers = nullptr; + + std::vector bindings = { uboLayoutBinding }; + + // 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, &grassDescriptorSetLayout) != VK_SUCCESS) + { + throw std::runtime_error("Failed to create descriptor set layout"); + } +} + void Renderer::CreateTimeDescriptorSetLayout() { // Describe the binding of the descriptor set layout VkDescriptorSetLayoutBinding uboLayoutBinding = {}; @@ -195,9 +220,45 @@ void Renderer::CreateTimeDescriptorSetLayout() { } void Renderer::CreateComputeDescriptorSetLayout() { - // TODO: Create the descriptor set layout for the compute pipeline + // 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 + + // InputBlades + VkDescriptorSetLayoutBinding inputBladesDescriptorSet = {}; + inputBladesDescriptorSet.binding = 0; + inputBladesDescriptorSet.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + inputBladesDescriptorSet.descriptorCount = 1; + inputBladesDescriptorSet.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT; + inputBladesDescriptorSet.pImmutableSamplers = nullptr; + + // CulledBlades + VkDescriptorSetLayoutBinding culledBladesDescriptorSet = {}; + culledBladesDescriptorSet.binding = 1; + culledBladesDescriptorSet.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + culledBladesDescriptorSet.descriptorCount = 1; + culledBladesDescriptorSet.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT; + culledBladesDescriptorSet.pImmutableSamplers = nullptr; + + // Numblades + VkDescriptorSetLayoutBinding numBladesDescriptorSet = {}; + numBladesDescriptorSet.binding = 2; + numBladesDescriptorSet.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + numBladesDescriptorSet.descriptorCount = 1; + numBladesDescriptorSet.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT; + numBladesDescriptorSet.pImmutableSamplers = nullptr; + + std::vector bindings = { inputBladesDescriptorSet, culledBladesDescriptorSet, numBladesDescriptorSet}; + + // 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, &computeDescriptorSetLayout) != VK_SUCCESS) { + throw std::runtime_error("Failed to create descriptor set layout"); + } } void Renderer::CreateDescriptorPool() { @@ -215,7 +276,8 @@ void Renderer::CreateDescriptorPool() { // Time (compute) { VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER , 1 }, - // TODO: Add any additional types and counts of descriptors you will need to allocate + // Add any additional types and counts of descriptors you will need to allocate + { VK_DESCRIPTOR_TYPE_STORAGE_BUFFER , static_cast(scene->GetBlades().size() * 3) } }; VkDescriptorPoolCreateInfo poolInfo = {}; @@ -318,8 +380,47 @@ void Renderer::CreateModelDescriptorSets() { } void Renderer::CreateGrassDescriptorSets() { - // TODO: Create Descriptor sets for the grass. + // Create Descriptor sets for the grass. // This should involve creating descriptor sets which point to the model matrix of each group of grass blades + + grassDescriptorSets.resize(scene->GetBlades().size()); + + // Describe the desciptor set + VkDescriptorSetLayout layouts[] = { grassDescriptorSetLayout }; + VkDescriptorSetAllocateInfo allocInfo = {}; + allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; + allocInfo.descriptorPool = descriptorPool; + allocInfo.descriptorSetCount = static_cast(grassDescriptorSets.size()); + allocInfo.pSetLayouts = layouts; + + // Allocate descriptor sets + if (vkAllocateDescriptorSets(logicalDevice, &allocInfo, grassDescriptorSets.data()) != VK_SUCCESS) + { + throw std::runtime_error("Failed to allocate descriptor set"); + } + + std::vector descriptorWrites(grassDescriptorSets.size()); + + for (uint32_t i = 0; i < scene->GetBlades().size(); ++i) + { + VkDescriptorBufferInfo bladeBufferInfo = {}; + bladeBufferInfo.buffer = scene->GetBlades()[i]->GetModelBuffer(); + bladeBufferInfo.offset = 0; + bladeBufferInfo.range = sizeof(ModelBufferObject); + + descriptorWrites[i].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + descriptorWrites[i].dstSet = grassDescriptorSets[i]; + descriptorWrites[i].dstBinding = 0; + descriptorWrites[i].dstArrayElement = 0; + descriptorWrites[i].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; + descriptorWrites[i].descriptorCount = 1; + descriptorWrites[i].pBufferInfo = &bladeBufferInfo; + descriptorWrites[i].pImageInfo = nullptr; + descriptorWrites[i].pTexelBufferView = nullptr; + } + + // Update descriptor sets + vkUpdateDescriptorSets(logicalDevice, static_cast(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr); } void Renderer::CreateTimeDescriptorSet() { @@ -357,9 +458,82 @@ void Renderer::CreateTimeDescriptorSet() { vkUpdateDescriptorSets(logicalDevice, static_cast(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr); } -void Renderer::CreateComputeDescriptorSets() { - // TODO: Create Descriptor sets for the compute pipeline +void Renderer::CreateComputeDescriptorSets() +{ + // 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 + + computeDescriptorSets.resize(scene->GetBlades().size()); + + // Describe the desciptor set + VkDescriptorSetLayout layouts[] = { computeDescriptorSetLayout }; + VkDescriptorSetAllocateInfo allocInfo = {}; + allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; + allocInfo.descriptorPool = descriptorPool; + allocInfo.descriptorSetCount = static_cast(computeDescriptorSets.size()); + allocInfo.pSetLayouts = layouts; + + // Allocate descriptor sets + if (vkAllocateDescriptorSets(logicalDevice, &allocInfo, computeDescriptorSets.data()) != VK_SUCCESS) + { + throw std::runtime_error("Failed to allocate descriptor set"); + } + + std::vector descriptorWrites(computeDescriptorSets.size() * 3); + + for (uint32_t i = 0; i < scene->GetBlades().size(); ++i) + { + // InputBlades at Binding 0 + VkDescriptorBufferInfo inputBladesBufferInfo = {}; + inputBladesBufferInfo.buffer = scene->GetBlades()[i]->GetBladesBuffer(); + inputBladesBufferInfo.offset = 0; + inputBladesBufferInfo.range = NUM_BLADES * sizeof(Blade); + + descriptorWrites[3 * i + 0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + descriptorWrites[3 * i + 0].dstSet = computeDescriptorSets[i]; + descriptorWrites[3 * i + 0].dstBinding = 0; + descriptorWrites[3 * i + 0].dstArrayElement = 0; + descriptorWrites[3 * i + 0].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + descriptorWrites[3 * i + 0].descriptorCount = 1; + descriptorWrites[3 * i + 0].pBufferInfo = &inputBladesBufferInfo; + descriptorWrites[3 * i + 0].pImageInfo = nullptr; + descriptorWrites[3 * i + 0].pTexelBufferView = nullptr; + + // CulledBlades at Binding 1 + VkDescriptorBufferInfo culledBladesBufferInfo = {}; + culledBladesBufferInfo.buffer = scene->GetBlades()[i]->GetCulledBladesBuffer(); + culledBladesBufferInfo.offset = 0; + culledBladesBufferInfo.range = NUM_BLADES * sizeof(Blade); + + descriptorWrites[3 * i + 1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + descriptorWrites[3 * i + 1].dstSet = computeDescriptorSets[i]; + descriptorWrites[3 * i + 1].dstBinding = 1; + descriptorWrites[3 * i + 1].dstArrayElement = 0; + descriptorWrites[3 * i + 1].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + descriptorWrites[3 * i + 1].descriptorCount = 1; + descriptorWrites[3 * i + 1].pBufferInfo = &culledBladesBufferInfo; + descriptorWrites[3 * i + 1].pImageInfo = nullptr; + descriptorWrites[3 * i + 1].pTexelBufferView = nullptr; + + // Numblades at Binding 2 + VkDescriptorBufferInfo numBladesBufferInfo = {}; + numBladesBufferInfo.buffer = scene->GetBlades()[i]->GetNumBladesBuffer(); + numBladesBufferInfo.offset = 0; + numBladesBufferInfo.range = sizeof(BladeDrawIndirect); + + descriptorWrites[3 * i + 2].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + descriptorWrites[3 * i + 2].dstSet = computeDescriptorSets[i]; + descriptorWrites[3 * i + 2].dstBinding = 2; + descriptorWrites[3 * i + 2].dstArrayElement = 0; + descriptorWrites[3 * i + 2].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + descriptorWrites[3 * i + 2].descriptorCount = 1; + descriptorWrites[3 * i + 2].pBufferInfo = &numBladesBufferInfo; + descriptorWrites[3 * i + 2].pImageInfo = nullptr; + descriptorWrites[3 * i + 2].pTexelBufferView = nullptr; + } + + // Update descriptor sets + vkUpdateDescriptorSets(logicalDevice, static_cast(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr); } void Renderer::CreateGraphicsPipeline() { @@ -716,8 +890,8 @@ void Renderer::CreateComputePipeline() { computeShaderStageInfo.module = computeShaderModule; computeShaderStageInfo.pName = "main"; - // TODO: Add the compute dsecriptor set layout you create to this list - std::vector descriptorSetLayouts = { cameraDescriptorSetLayout, timeDescriptorSetLayout }; + // Add the compute dsecriptor set layout you create to this list + std::vector descriptorSetLayouts = { cameraDescriptorSetLayout, timeDescriptorSetLayout, computeDescriptorSetLayout}; // Create pipeline layout VkPipelineLayoutCreateInfo pipelineLayoutInfo = {}; @@ -883,7 +1057,12 @@ void Renderer::RecordComputeCommandBuffer() { // Bind descriptor set for time uniforms 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 each group of blades bind its descriptor set and dispatch + for (int i = 0; i < scene->GetBlades().size(); ++i) + { + vkCmdBindDescriptorSets(computeCommandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, computePipelineLayout, 2, 1, &computeDescriptorSets[i], 0, nullptr); + } + vkCmdDispatch(computeCommandBuffer, NUM_BLADES / WORKGROUP_SIZE, 1, 1); // ~ End recording ~ if (vkEndCommandBuffer(computeCommandBuffer) != VK_SUCCESS) { @@ -975,14 +1154,15 @@ void Renderer::RecordCommandBuffers() { for (uint32_t j = 0; j < scene->GetBlades().size(); ++j) { VkBuffer vertexBuffers[] = { scene->GetBlades()[j]->GetCulledBladesBuffer() }; VkDeviceSize offsets[] = { 0 }; - // TODO: Uncomment this when the buffers are populated - // vkCmdBindVertexBuffers(commandBuffers[i], 0, 1, vertexBuffers, offsets); + // Uncomment this when the buffers are populated + vkCmdBindVertexBuffers(commandBuffers[i], 0, 1, vertexBuffers, offsets); - // TODO: Bind the descriptor set for each grass blades model + // Bind the descriptor set for each grass blades model + vkCmdBindDescriptorSets(commandBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, grassPipelineLayout, 1, 1, &grassDescriptorSets[j], 0, nullptr); // Draw - // TODO: Uncomment this when the buffers are populated - // vkCmdDrawIndirect(commandBuffers[i], scene->GetBlades()[j]->GetNumBladesBuffer(), 0, 1, sizeof(BladeDrawIndirect)); + // Uncomment this when the buffers are populated + vkCmdDrawIndirect(commandBuffers[i], scene->GetBlades()[j]->GetNumBladesBuffer(), 0, 1, sizeof(BladeDrawIndirect)); } // End render pass @@ -1041,7 +1221,7 @@ void Renderer::Frame() { Renderer::~Renderer() { vkDeviceWaitIdle(logicalDevice); - // TODO: destroy any resources you created + // Destroy any resources you created vkFreeCommandBuffers(logicalDevice, graphicsCommandPool, static_cast(commandBuffers.size()), commandBuffers.data()); vkFreeCommandBuffers(logicalDevice, computeCommandPool, 1, &computeCommandBuffer); @@ -1057,6 +1237,8 @@ Renderer::~Renderer() { vkDestroyDescriptorSetLayout(logicalDevice, cameraDescriptorSetLayout, nullptr); vkDestroyDescriptorSetLayout(logicalDevice, modelDescriptorSetLayout, nullptr); vkDestroyDescriptorSetLayout(logicalDevice, timeDescriptorSetLayout, nullptr); + vkDestroyDescriptorSetLayout(logicalDevice, grassDescriptorSetLayout, nullptr); + vkDestroyDescriptorSetLayout(logicalDevice, computeDescriptorSetLayout, nullptr); vkDestroyDescriptorPool(logicalDevice, descriptorPool, nullptr); diff --git a/src/Renderer.h b/src/Renderer.h index 95e025f..bcc4b4f 100644 --- a/src/Renderer.h +++ b/src/Renderer.h @@ -18,6 +18,7 @@ class Renderer { void CreateCameraDescriptorSetLayout(); void CreateModelDescriptorSetLayout(); void CreateTimeDescriptorSetLayout(); + void CreateGrassDescriptorSetLayout(); void CreateComputeDescriptorSetLayout(); void CreateDescriptorPool(); @@ -56,11 +57,15 @@ class Renderer { VkDescriptorSetLayout cameraDescriptorSetLayout; VkDescriptorSetLayout modelDescriptorSetLayout; VkDescriptorSetLayout timeDescriptorSetLayout; + VkDescriptorSetLayout grassDescriptorSetLayout; + VkDescriptorSetLayout computeDescriptorSetLayout; VkDescriptorPool descriptorPool; VkDescriptorSet cameraDescriptorSet; std::vector modelDescriptorSets; + std::vector grassDescriptorSets; + std::vector computeDescriptorSets; VkDescriptorSet timeDescriptorSet; VkPipelineLayout graphicsPipelineLayout; diff --git a/src/images/sun.jpg b/src/images/sun.jpg new file mode 100644 index 0000000..99c41da Binary files /dev/null and b/src/images/sun.jpg differ diff --git a/src/main.cpp b/src/main.cpp index 8bf822b..e7c5d34 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -116,7 +116,7 @@ int main() { grassImageMemory ); - float planeDim = 15.f; + float planeDim = 150.f; float halfWidth = planeDim * 0.5f; Model* plane = new Model(device, transferCommandPool, { diff --git a/src/shaders/compute.comp b/src/shaders/compute.comp index 0fd0224..6587795 100644 --- a/src/shaders/compute.comp +++ b/src/shaders/compute.comp @@ -21,36 +21,151 @@ struct Blade { vec4 up; }; -// TODO: Add bindings to: // 1. Store the input blades +layout(set = 2, binding = 0) buffer InputBlades +{ + Blade inputBlades[]; +}; + // 2. Write out the culled blades -// 3. Write the total number of blades remaining +layout(set = 2, binding = 1) buffer CulledBlades +{ + Blade culledBlades[]; +}; -// The project is using vkCmdDrawIndirect to use a buffer as the arguments for a draw call -// This is sort of an advanced feature so we've showed you what this buffer should look like -// -// layout(set = ???, binding = ???) buffer NumBlades { -// uint vertexCount; // Write the number of blades remaining here -// uint instanceCount; // = 1 -// uint firstVertex; // = 0 -// uint firstInstance; // = 0 -// } numBlades; +// 3. Write the total number of blades remaining +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); } -void main() { +bool inBounds2(vec3 vectorVal, float bounds) +{ + return (inBounds(vectorVal.x, bounds) && inBounds(vectorVal.y, bounds) && inBounds(vectorVal.z, bounds)); +} + +void main() +{ + // Similar to thread ID + uint index = gl_GlobalInvocationID.x; + // Reset the number of blades to 0 - if (gl_GlobalInvocationID.x == 0) { - // numBlades.vertexCount = 0; + if (index == 0) + { + numBlades.vertexCount = 0; } barrier(); // Wait till all threads reach this point - // TODO: Apply forces on every blade and update the vertices in the buffer + // Apply forces on every blade and update the vertices in the buffer + + Blade blade = inputBlades[index]; + float orientation = blade.v0.w; + float height = blade.v1.w; + float width = blade.v2.w; + float stiffness = blade.up.w; + vec3 up = blade.up.xyz; + vec3 v0 = blade.v0.xyz; + vec3 v1 = blade.v1.xyz; + vec3 v2 = blade.v2.xyz; + + // Force 1: Recovery + vec3 Iv2 = v0 + height * (up); + float N = 0.0; // TODO: Dont even get me started!! + vec3 recoveryForce = (Iv2 - v2) * stiffness * max(1.0 - N, 0.1); + + // Force 2: Gravity + float mass = 1.0; + float t = 0.0; + vec4 D = vec4(0.0, -1.0, 0.0, 9.8); + vec3 C = vec3(0.0); // Hocus pocus + + float z = cos(orientation); // sin(90 - orientation) + float x = sin(orientation); // cos(90 - orientation) + float y = 0.0;// ??? + vec3 bit = vec3(x, 0.0, z); + + vec3 f = normalize(cross(up, bit)); + vec3 ge = mass * (normalize(D.xyz) * D.w * (1.0 - t) + C * t); + vec3 gravityForce = ge + (0.25 * normalize(ge) * f); + + // Force 3: Wind + vec3 wi_v0 = vec3(1.0, 0.0, 0.0) * sin(totalTime) + cos(totalTime * v0) * vec3(0.0, 0.0, 1.0); // Sample Wind force + vec3 v2_v0 = v2 - v0; + float fd = 1.0 - abs(dot(normalize(wi_v0), normalize(v2 - v0))); + float fr = dot(v2_v0, up) / height; + float theta = fd * fr; + vec3 windForce = wi_v0 * theta; - // 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 Pos of v2 + vec3 new_v2 = v2 + (recoveryForce + gravityForce + windForce) * deltaTime; + + // State Validation + new_v2 = new_v2 - up * min(dot(up, new_v2 - v0), 0.0); + float lproj = length(new_v2 - v0 - up * dot(new_v2 - v0, up)); + float temp_ratio = lproj/height; + // Ensures that grass is slightly curved + vec3 new_v1 = v0 + height * up * max(1.0 - temp_ratio, 0.05 * max(temp_ratio, 1.0)); + // Ensure length if bezier curve is not larger than height of grass + float L0 = length(new_v2 - v0); + float L1 = length(new_v1 - new_v2) + length(v0 - new_v1); + float degree = 2.0; // Quadratic + float L = (2.0 * L0 + (degree - 1) * L1) / (degree + 1); + + // Corrected Positions + float r = height / L; + vec3 v1_correct = v0 + r * (new_v1 - v0); + vec3 v2_correct = v1_correct + r * (new_v2 - new_v1); + + blade.v1 = vec4(v1_correct, height); + blade.v2 = vec4(v2_correct, width); + inputBlades[index] = blade; + + // Orientation Culling + mat4 inverseTransform = inverse(camera.view); + vec3 cameraVec = normalize(v0 - inverseTransform[3].xyz); + bool dontOrientCull = abs(dot(f, cameraVec)) > 0.9f; + + // View Frustrum Culling + mat4 VP = camera.proj * camera.view; + float h = 1.01; + + // Testing v0 + vec4 p_v0 = VP * vec4(v0, 1.0); + p_v0 /= p_v0.w; + bool isV0InBounds = inBounds2(p_v0.xyz, h); + + // Testing m + vec3 m = 0.25 * v0 + 0.5 * v1_correct + 0.25 * v2_correct; + vec4 p_m = VP * vec4(m, 1.0); + p_m /= p_m.w; + bool isMInBounds = inBounds2(p_m.xyz, h); + + // Testing v2 + vec4 p_v2 = VP * vec4(v0, 1.0); + p_v2 /= p_v2.w; + bool isV2InBounds = inBounds2(p_v2.xyz, h); + + bool dontFrustrumCull = !(isV0InBounds || isMInBounds || isV2InBounds); + + // Distance Culling + float dmax = 200.0; + float nBlades = 30; + + vec3 c = mat3(inverseTransform) * (-camera.view[3].xyz); + float dproj = length(v0 - c - up * (dot(v0 - c, up))); + + float X = floor(nBlades * (1.0 - dproj/dmax)); + bool dontDistanceCull = X < (mod(index, nBlades)); + + if(!dontOrientCull && !dontFrustrumCull && !dontDistanceCull) + { + culledBlades[atomicAdd(numBlades.vertexCount, 1)] = inputBlades[index]; + } } diff --git a/src/shaders/grass.frag b/src/shaders/grass.frag index c7df157..ac3b64c 100644 --- a/src/shaders/grass.frag +++ b/src/shaders/grass.frag @@ -7,11 +7,22 @@ layout(set = 0, binding = 0) uniform CameraBufferObject { } camera; // TODO: Declare fragment shader inputs +layout(location = 0) in vec4 in_pos; +layout(location = 1) in vec3 in_normal; +layout(location = 2) in vec2 in_tex; layout(location = 0) out vec4 outColor; -void main() { +void main() +{ // TODO: Compute fragment color + vec3 grassColor = vec3(0.23, 0.8, 0.47); + + // need light pos to do lamberts + vec3 lightVec = vec3(0.0, 1.0, -1.0); + vec3 ambient = vec3(0.1, 0.1, 0.1); + float lambert = clamp(dot(lightVec, in_normal), 0.3, 1.0); - outColor = vec4(1.0); + vec3 shadedColor = grassColor * lambert + ambient; + outColor = vec4(shadedColor, 1.0); } diff --git a/src/shaders/grass.tesc b/src/shaders/grass.tesc index f9ffd07..9f3d378 100644 --- a/src/shaders/grass.tesc +++ b/src/shaders/grass.tesc @@ -8,19 +8,42 @@ layout(set = 0, binding = 0) uniform CameraBufferObject { mat4 proj; } camera; -// TODO: Declare tessellation control shader inputs and outputs +// Declare tessellation control shader inputs and outputs +layout(location = 0) in vec4 in_v0[]; +layout(location = 1) in vec4 in_v1[]; +layout(location = 2) in vec4 in_v2[]; +layout(location = 3) in vec4 in_Up[]; + +layout(location = 0) out vec4 out_v0[]; +layout(location = 1) out vec4 out_v1[]; +layout(location = 2) out vec4 out_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 + out_v0[gl_InvocationID] = in_v0[gl_InvocationID]; + out_v1[gl_InvocationID] = in_v1[gl_InvocationID]; + out_v2[gl_InvocationID] = in_v2[gl_InvocationID]; + + mat4 inverseTransform = inverse(camera.view); + vec3 c = mat3(inverseTransform) * (-camera.view[3].xyz); + vec3 up = in_Up[gl_InvocationID].xyz; + vec3 v0 = in_v0[gl_InvocationID].xyz; + float distanceFromGeom = length(v0 - c - up * (dot(v0 - c, up))); + + float minLevel = 2.0; + float maxLevel = 15.0; + + float mixRatio = distanceFromGeom / 10.0; + float currLevel = mix(maxLevel, minLevel, clamp(mixRatio, 0.0, 1.0)); + + // Test Tesselation + gl_TessLevelInner[0] = 2.0; // Horizontal + gl_TessLevelInner[1] = 2.0; // Vertical + gl_TessLevelOuter[0] = currLevel; // edge 0~3 + gl_TessLevelOuter[1] = 1.0; // edge 3~2 + gl_TessLevelOuter[2] = currLevel; // edge 2~1 + gl_TessLevelOuter[3] = 1.0; // edge 1~0 - // TODO: Set level of tesselation - // gl_TessLevelInner[0] = ??? - // gl_TessLevelInner[1] = ??? - // gl_TessLevelOuter[0] = ??? - // gl_TessLevelOuter[1] = ??? - // gl_TessLevelOuter[2] = ??? - // gl_TessLevelOuter[3] = ??? } diff --git a/src/shaders/grass.tese b/src/shaders/grass.tese index 751fff6..0bfcf36 100644 --- a/src/shaders/grass.tese +++ b/src/shaders/grass.tese @@ -9,10 +9,54 @@ layout(set = 0, binding = 0) uniform CameraBufferObject { } camera; // TODO: Declare tessellation evaluation shader inputs and outputs +layout(location = 0) in vec4 in_v0[]; +layout(location = 1) in vec4 in_v1[]; +layout(location = 2) in vec4 in_v2[]; -void main() { +layout(location = 0) out vec4 out_pos; +layout(location = 1) out vec3 out_normal; +layout(location = 2) out vec2 out_tex; + +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 + vec4 v0 = in_v0[0]; + vec4 v1 = in_v1[0]; + vec4 v2 = in_v2[0]; + + float orientation = v0.w; + float width = v2.w; + + vec3 a = vec3(v0 + v * (v1 - v0)); + vec3 b = vec3(v1 + v * (v2 - v1)); + vec3 c = a + v * (b - a); + + // tangent + vec3 t0 = normalize(b - a); + + // bitangent - i am assuming it is perpendicular to grass plane + float z = cos(orientation); // sin(90 - orientation) + float x = sin(orientation); // cos(90 - orientation) + float y = 0.0;// ??? + vec3 t1 = vec3(x, 0.0, z); + + vec3 c0 = c - width * t1; + vec3 c1 = c + width * t1; + + vec3 normal = normalize(cross(t0, t1)); + + // TODO: Which one to use? + //float t = u; // quad + float t = u + 0.5 * v - u * v; // Triangle interpolation + //float t = u - u * v * v; // QUadratic + + vec3 pos = (1 - t) * c0 + t * c1; + + out_pos = camera.proj * camera.view * vec4(pos, 1.0); + out_normal = normal; + out_tex = vec2(u, v); + + gl_Position = out_pos; } diff --git a/src/shaders/grass.vert b/src/shaders/grass.vert index db9dfe9..40ebe6a 100644 --- a/src/shaders/grass.vert +++ b/src/shaders/grass.vert @@ -6,12 +6,28 @@ layout(set = 1, binding = 0) uniform ModelBufferObject { mat4 model; }; -// TODO: Declare vertex shader inputs and outputs +layout(location = 0) in vec4 v0; +layout(location = 1) in vec4 v1; +layout(location = 2) in vec4 v2; +layout(location = 3) in vec4 up; -out gl_PerVertex { +layout(location = 0) out vec4 out_v0; +layout(location = 1) out vec4 out_v1; +layout(location = 2) out vec4 out_v2; +layout(location = 3) out vec4 out_up; + +out gl_PerVertex +{ vec4 gl_Position; }; -void main() { - // TODO: Write gl_Position and any other shader outputs +void main() +{ + out_v0 = v0; + out_v1 = v1; + out_v2 = v2; + out_up = up; + + // v0.w holds the orientation + gl_Position = model * vec4(v0.xyz, 1.0); }