diff --git a/README - Copy.md b/README - Copy.md new file mode 100644 index 0000000..a744a2e --- /dev/null +++ b/README - Copy.md @@ -0,0 +1,297 @@ +Instructions - Vulkan Grass Rendering +======================== + +This is due **Sunday 11/5, evening at midnight**. + +**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) + +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 .gif is just a simple example that you +can use as a reference to compare to. + +**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 Austin Eng 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. + +### 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-2017/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-2017/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. +* At least one screenshot of your project running. +* 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 a744a2e..a171ca5 100644 --- a/README.md +++ b/README.md @@ -1,110 +1,88 @@ -Instructions - Vulkan Grass Rendering -======================== +Vulkan Grass Rendering +====================== -This is due **Sunday 11/5, evening at midnight**. -**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. +**University of Pennsylvania, CIS 565: GPU Programming and Architecture, Project 6** -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. +* Name: Meghana Seshadri +* Tested on: Windows 10, i7-4870HQ @ 2.50GHz 16GB, GeForce GT 750M 2048MB (personal computer) -![](img/grass.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 .gif is just a simple example that you -can use as a reference to compare to. +## Project Overview -**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 Austin Eng before continuing! +The goal of this project was to get an introduction to Vulkan by implementing a grass simulator and renderer. [Vulkan](https://www.khronos.org/vulkan/) is graphics and compute API that is cross-platform. It is populary used amongst real-time 3D applications such as video games and other interactive media as it offers higher performance. -### Contents +![](renders/grass_2.gif) +![](renders/grass_3.gif) -* `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 +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). + +In this project, compute shaders were used to perform physics calculations on Bezier curves that represent individual grass blades. Since rendering every grass blade on every frame will is fairly inefficient, we also use compute shaders to cull grass blades that don't contribute to a given frame. The remaining blades are then passed to a graphics pipeline, in which several other shaders operate on them. A vertex shader is used 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. + +## Features -### Installing Vulkan +- Representing grass as Bezier curves -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. +- Simulating forces + - Gravity + - Recovery + - Wind -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. +- Culling tests + - Orientation culling + - View-frustum culling + - Distance culling -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! +- Tessellating Bezier curves into grass blades -### Running the code +'''Look at the Appendix section below for further explanation of the above features.''' -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. +## Performance Analysis -![](img/cube_demo.png) +### Varying blade count -## Requirements +![](renders/blades-graph.PNG) -**Ask on the mailing list for any clarifications.** +![](renders/blades-chart.PNG) -In this project, you are given the following code: +When rendering frames with varying blade count, there seems to be a huge spike after 1 << 21 blades (2097152). -* 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: +### Culling test comparison -* 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 +![](renders/cull-graph.PNG) -See below for more guidance. +![](renders/cull-chart.PNG) -## Base Code Tour +Here also, there seems to be a huge spike after 1 << 21 blades (2097152). What's interesting to note is that the culling tests don't seem to perform much differently from each other until you get to 1 << 21 number of blades. But even at 1 << 23, this varies a lot. From View Frustum not being the most optimized, the orientation culling technique becomes the least optimized at 1 << 23 blades. -Areas that you need to complete are -marked with a `TODO` comment. Functions that are useful -for reference are marked with the comment `CHECKITOUT`. +## Resources -* `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. +### Links -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. +The following resources were useful for this project. -## Grass Rendering +* [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-2017/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/) + +* [Calculating wind](https://www.cg.tuwien.ac.at/research/publications/2013/JAHRMANN-2013-IGR/JAHRMANN-2013-IGR-paper.pdf) +* [Orientation culling](https://gamedev.stackexchange.com/questions/22283/how-to-get-translation-from-view-matrix) +* [AtomicAdd](http://www.nvidia.com/content/siggraph/Rollin_Oster_OpenGL_CUDA.pdf +* [Tessellation control shader](https://www.khronos.org/opengl/wiki/Tessellation_Control_Shader) +* [Tessellation evaluation shader](https://www.khronos.org/opengl/wiki/Tessellation_Evaluation_Shader) + +* Getting front facing direction + - [Converting angle radians to heading vector](https://math.stackexchange.com/questions/180874/convert-angle-radians-to-a-heading-vector) + - [Get orientation from vectors](https://www.opengl.org/discussion_boards/showthread.php/178287-Get-orientation-from-vectors) + - [Cross product](https://en.wikipedia.org/wiki/Cross_product) + + + +## Grass Rendering - Appendix 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 @@ -219,11 +197,6 @@ You are free to define two parameters here. 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 @@ -238,60 +211,3 @@ of each blade. Once you have determined the world space position of each vector, To build more intuition on how tessellation works, I highly recommend playing with the [helloTessellation sample](https://github.com/CIS565-Fall-2017/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-2017/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. -* At least one screenshot of your project running. -* 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/bin/Debug/vulkan_grass_rendering.exe b/bin/Debug/vulkan_grass_rendering.exe new file mode 100644 index 0000000..7f90bfc Binary files /dev/null and b/bin/Debug/vulkan_grass_rendering.exe differ diff --git a/bin/Debug/vulkan_grass_rendering.ilk b/bin/Debug/vulkan_grass_rendering.ilk new file mode 100644 index 0000000..9fd031f Binary files /dev/null and b/bin/Debug/vulkan_grass_rendering.ilk differ diff --git a/bin/Debug/vulkan_grass_rendering.pdb b/bin/Debug/vulkan_grass_rendering.pdb new file mode 100644 index 0000000..8c0b2ad Binary files /dev/null and b/bin/Debug/vulkan_grass_rendering.pdb differ diff --git a/bin/Release/vulkan_grass_rendering.exe b/bin/Release/vulkan_grass_rendering.exe new file mode 100644 index 0000000..0269940 Binary files /dev/null and b/bin/Release/vulkan_grass_rendering.exe differ diff --git a/renders/blades-chart.PNG b/renders/blades-chart.PNG new file mode 100644 index 0000000..c12cea3 Binary files /dev/null and b/renders/blades-chart.PNG differ diff --git a/renders/blades-graph.PNG b/renders/blades-graph.PNG new file mode 100644 index 0000000..b62ede7 Binary files /dev/null and b/renders/blades-graph.PNG differ diff --git a/renders/cull-chart.PNG b/renders/cull-chart.PNG new file mode 100644 index 0000000..3305969 Binary files /dev/null and b/renders/cull-chart.PNG differ diff --git a/renders/cull-graph.PNG b/renders/cull-graph.PNG new file mode 100644 index 0000000..a321046 Binary files /dev/null and b/renders/cull-graph.PNG differ diff --git a/renders/grass_2.gif b/renders/grass_2.gif new file mode 100644 index 0000000..556780c Binary files /dev/null and b/renders/grass_2.gif differ diff --git a/renders/grass_3.gif b/renders/grass_3.gif new file mode 100644 index 0000000..b7c06b2 Binary files /dev/null and b/renders/grass_3.gif differ diff --git a/src/Renderer.cpp b/src/Renderer.cpp index b445d04..1ab1769 100644 --- a/src/Renderer.cpp +++ b/src/Renderer.cpp @@ -17,20 +17,26 @@ Renderer::Renderer(Device* device, SwapChain* swapChain, Scene* scene, Camera* c CreateCommandPools(); CreateRenderPass(); + CreateCameraDescriptorSetLayout(); CreateModelDescriptorSetLayout(); CreateTimeDescriptorSetLayout(); CreateComputeDescriptorSetLayout(); + CreateDescriptorPool(); + CreateCameraDescriptorSet(); CreateModelDescriptorSets(); CreateGrassDescriptorSets(); CreateTimeDescriptorSet(); CreateComputeDescriptorSets(); + CreateFrameResources(); + CreateGraphicsPipeline(); CreateGrassPipeline(); CreateComputePipeline(); + RecordCommandBuffers(); RecordComputeCommandBuffer(); } @@ -140,7 +146,7 @@ void Renderer::CreateCameraDescriptorSetLayout() { layoutInfo.pBindings = bindings.data(); if (vkCreateDescriptorSetLayout(logicalDevice, &layoutInfo, nullptr, &cameraDescriptorSetLayout) != VK_SUCCESS) { - throw std::runtime_error("Failed to create descriptor set layout"); + throw std::runtime_error("Failed to create camera descriptor set layout"); } } @@ -168,7 +174,7 @@ void Renderer::CreateModelDescriptorSetLayout() { layoutInfo.pBindings = bindings.data(); if (vkCreateDescriptorSetLayout(logicalDevice, &layoutInfo, nullptr, &modelDescriptorSetLayout) != VK_SUCCESS) { - throw std::runtime_error("Failed to create descriptor set layout"); + throw std::runtime_error("Failed to create model descriptor set layout"); } } @@ -190,7 +196,7 @@ void Renderer::CreateTimeDescriptorSetLayout() { layoutInfo.pBindings = bindings.data(); if (vkCreateDescriptorSetLayout(logicalDevice, &layoutInfo, nullptr, &timeDescriptorSetLayout) != VK_SUCCESS) { - throw std::runtime_error("Failed to create descriptor set layout"); + throw std::runtime_error("Failed to create time descriptor set layout"); } } @@ -198,10 +204,51 @@ 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 bladeLayoutBinding = {}; + //bladeLayoutBinding.binding = 0; + //bladeLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + //bladeLayoutBinding.descriptorCount = 1; + //bladeLayoutBinding.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT; //You only need this for the compute bit of the shader stages + //bladeLayoutBinding.pImmutableSamplers = nullptr; + + //VkDescriptorSetLayoutBinding culledBladeLayoutBinding = {}; + //culledBladeLayoutBinding.binding = 1; + //culledBladeLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + //culledBladeLayoutBinding.descriptorCount = 1; + //culledBladeLayoutBinding.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT; + //culledBladeLayoutBinding.pImmutableSamplers = nullptr; + + //VkDescriptorSetLayoutBinding numBladeLayoutBinding = {}; + //numBladeLayoutBinding.binding = 2; + //numBladeLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + //numBladeLayoutBinding.descriptorCount = 1; + //numBladeLayoutBinding.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT; + //numBladeLayoutBinding.pImmutableSamplers = nullptr; + + //std::vector bindings = { bladeLayoutBinding, culledBladeLayoutBinding, numBladeLayoutBinding }; + + // ANOTHER WAY TO WRITE ALL THE ABOVE (look at provided helloCompute Vulkan sample, line #465) + std::vector bindings = { + { 0, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_COMPUTE_BIT, nullptr }, + { 1, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_COMPUTE_BIT, nullptr }, + { 2, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_COMPUTE_BIT, nullptr }, + }; + + // 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 compute descriptor set layout"); + } } void Renderer::CreateDescriptorPool() { // Describe which descriptor types that the descriptor sets will contain + // Type, size std::vector poolSizes = { // Camera { VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER , 1}, @@ -216,6 +263,9 @@ void Renderer::CreateDescriptorPool() { { VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER , 1 }, // TODO: Add any additional types and counts of descriptors you will need to allocate + + // Blade (compute) + {VK_DESCRIPTOR_TYPE_STORAGE_BUFFER , static_cast(3 * scene->GetBlades().size()) }, }; VkDescriptorPoolCreateInfo poolInfo = {}; @@ -240,7 +290,7 @@ void Renderer::CreateCameraDescriptorSet() { // Allocate descriptor sets if (vkAllocateDescriptorSets(logicalDevice, &allocInfo, &cameraDescriptorSet) != VK_SUCCESS) { - throw std::runtime_error("Failed to allocate descriptor set"); + throw std::runtime_error("Failed to allocate camera descriptor set"); } // Configure the descriptors to refer to buffers @@ -277,7 +327,7 @@ void Renderer::CreateModelDescriptorSets() { // Allocate descriptor sets if (vkAllocateDescriptorSets(logicalDevice, &allocInfo, modelDescriptorSets.data()) != VK_SUCCESS) { - throw std::runtime_error("Failed to allocate descriptor set"); + throw std::runtime_error("Failed to allocate model descriptor set"); } std::vector descriptorWrites(2 * modelDescriptorSets.size()); @@ -320,6 +370,44 @@ 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 + + grassDescriptorSets.resize(scene->GetBlades().size()); + + VkDescriptorSetLayout layouts[] = { modelDescriptorSetLayout }; + 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 grass descriptor set."); + } + + std::vector descriptorWrites(grassDescriptorSets.size()); + + for (uint32_t i = 0; i < scene->GetBlades().size(); ++i) + { + VkDescriptorBufferInfo grassBufferInfo = {}; + grassBufferInfo.buffer = scene->GetBlades()[i]->GetModelBuffer(); + grassBufferInfo.offset = 0; + grassBufferInfo.range = sizeof(ModelBufferObject); + + descriptorWrites[i + 0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + descriptorWrites[i + 0].dstSet = grassDescriptorSets[i]; + descriptorWrites[i + 0].dstBinding = 0; + descriptorWrites[i + 0].dstArrayElement = 0; + descriptorWrites[i + 0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; + descriptorWrites[i + 0].descriptorCount = 1; + descriptorWrites[i + 0].pBufferInfo = &grassBufferInfo; + descriptorWrites[i + 0].pImageInfo = nullptr; + descriptorWrites[i + 0].pTexelBufferView = nullptr; + }//end for loop + + // Update descriptor sets + vkUpdateDescriptorSets(logicalDevice, static_cast(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr); + } void Renderer::CreateTimeDescriptorSet() { @@ -333,7 +421,7 @@ void Renderer::CreateTimeDescriptorSet() { // Allocate descriptor sets if (vkAllocateDescriptorSets(logicalDevice, &allocInfo, &timeDescriptorSet) != VK_SUCCESS) { - throw std::runtime_error("Failed to allocate descriptor set"); + throw std::runtime_error("Failed to allocate time descriptor set"); } // Configure the descriptors to refer to buffers @@ -360,6 +448,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 + + computeDescriptorSets.resize(scene->GetBlades().size()); + + 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 compute descriptor set."); + } + + std::vector descriptorWrites(3 * computeDescriptorSets.size()); + + for (uint32_t i = 0; i < scene->GetBlades().size(); ++i) + { + // Create the 3 buffers for blades, culled blades, and num blades + + VkDescriptorBufferInfo bladeBufferInfo = {}; + bladeBufferInfo.buffer = scene->GetBlades()[i]->GetBladesBuffer(); + bladeBufferInfo.offset = 0; + bladeBufferInfo.range = NUM_BLADES * sizeof(Blade); + + VkDescriptorBufferInfo culledBladeBufferInfo = {}; + culledBladeBufferInfo.buffer = scene->GetBlades()[i]->GetCulledBladesBuffer(); + culledBladeBufferInfo.offset = 0; + culledBladeBufferInfo.range = NUM_BLADES * sizeof(Blade); + + VkDescriptorBufferInfo numBladeBufferInfo = {}; + numBladeBufferInfo.buffer = scene->GetBlades()[i]->GetNumBladesBuffer(); + numBladeBufferInfo.offset = 0; + numBladeBufferInfo.range = sizeof(BladeDrawIndirect); //There's only one of this, so don't multiply by NUM_BLADES + + 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 = &bladeBufferInfo; + descriptorWrites[3 * i + 0].pImageInfo = nullptr; + descriptorWrites[3 * i + 0].pTexelBufferView = nullptr; + + 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 = &culledBladeBufferInfo; + descriptorWrites[3 * i + 1].pImageInfo = nullptr; + descriptorWrites[3 * i + 1].pTexelBufferView = nullptr; + + 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 = &numBladeBufferInfo; + descriptorWrites[3 * i + 2].pImageInfo = nullptr; + descriptorWrites[3 * i + 2].pTexelBufferView = nullptr; + + }//end for loop going through grass blade "patches" + + // Update descriptor sets + vkUpdateDescriptorSets(logicalDevice, static_cast(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr); + } void Renderer::CreateGraphicsPipeline() { @@ -717,7 +876,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 , computeDescriptorSetLayout}; // Create pipeline layout VkPipelineLayoutCreateInfo pipelineLayoutInfo = {}; @@ -885,6 +1044,18 @@ void Renderer::RecordComputeCommandBuffer() { // TODO: 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); + + // Number of local workgroups to dispatch in X dimension + // Similar to allocating blocks per grid + uint32_t groupCountX = int(ceil((NUM_BLADES + WORKGROUP_SIZE - 1) / WORKGROUP_SIZE)); + + // Dispatch the compute kernel, with one thread for each blade + vkCmdDispatch(computeCommandBuffer, groupCountX, 1, 1); + } + // ~ End recording ~ if (vkEndCommandBuffer(computeCommandBuffer) != VK_SUCCESS) { throw std::runtime_error("Failed to record compute command buffer"); @@ -975,14 +1146,18 @@ void Renderer::RecordCommandBuffers() { for (uint32_t j = 0; j < scene->GetBlades().size(); ++j) { VkBuffer vertexBuffers[] = { scene->GetBlades()[j]->GetCulledBladesBuffer() }; VkDeviceSize offsets[] = { 0 }; + + // NOTE: DO NOT uncomment the following until compute shader is completed + // 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, &grassDescriptorSets[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 @@ -1064,4 +1239,7 @@ Renderer::~Renderer() { DestroyFrameResources(); vkDestroyCommandPool(logicalDevice, computeCommandPool, nullptr); vkDestroyCommandPool(logicalDevice, graphicsCommandPool, nullptr); + + // Destroy compute info + vkDestroyDescriptorSetLayout(logicalDevice, computeDescriptorSetLayout, nullptr); } diff --git a/src/Renderer.h b/src/Renderer.h index 95e025f..36ff4fb 100644 --- a/src/Renderer.h +++ b/src/Renderer.h @@ -41,6 +41,7 @@ class Renderer { void Frame(); + private: Device* device; VkDevice logicalDevice; @@ -79,4 +80,14 @@ class Renderer { std::vector commandBuffers; VkCommandBuffer computeCommandBuffer; + + + // Descriptor set info for blades + VkDescriptorSetLayout computeDescriptorSetLayout; + // Since you can have more than 1 patch of grass in the scene, we have a vector of DescriptorSets (right now we have only 1) + std::vector computeDescriptorSets; + + // Descriptor set for grass + std::vector grassDescriptorSets; + }; diff --git a/src/shaders/compute.comp b/src/shaders/compute.comp index 0fd0224..a10cd83 100644 --- a/src/shaders/compute.comp +++ b/src/shaders/compute.comp @@ -36,21 +36,194 @@ struct Blade { // uint firstInstance; // = 0 // } numBlades; +layout(set = 2, binding = 0) buffer Blades { + Blade blades[]; +}; + +layout(set = 2, binding = 1) buffer CulledBlades { + Blade culledBlades[]; +}; + +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); } +// Constants +const float ACCELERATION = 9.8; +const vec4 GRAVITY = vec4(0.0, -1.0, 0.0, ACCELERATION); +const float PI = 3.14159265; + 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 // TODO: Apply forces on every blade and update the vertices in the buffer + + uint index = gl_GlobalInvocationID.x; + Blade currBlade = blades[index]; + + + // --------------------------------------- FORCE CALCULATIONS ----------------------------------------- + + vec3 v0_pos = currBlade.v0.xyz; + float theta = currBlade.v0.w; + + vec3 v1_pos = currBlade.v1.xyz; + float height = currBlade.v1.w; + + vec3 v2_pos = currBlade.v2.xyz; + float width = currBlade.v2.w; + + vec3 upVec = currBlade.up.xyz; + float stiffness = currBlade.up.w; + + // ---------- Calculate gravity ---------- + // g = gE + gF ---------- blade's v0.w = blade's orientation + + // Environmental gravity + vec3 gE = normalize(GRAVITY.xyz) * GRAVITY.w; + + // Front gravity + // Get front facing direction + // https://math.stackexchange.com/questions/180874/convert-angle-radians-to-a-heading-vector + // https://www.opengl.org/discussion_boards/showthread.php/178287-Get-orientation-from-vectors + // https://en.wikipedia.org/wiki/Cross_product + vec3 orientationVec = vec3(sin(theta), 0.0, cos(theta)); + vec3 frontDir = normalize(cross(upVec, orientationVec)); + vec3 gF = 0.25 * length(gE) * frontDir; + + vec3 g = gE + gF; + + // ---------- Calculate recovery ---------- + // r = (iv2 - v2) * stiffness ---------- v1.w = height and up.w = stiffness + vec3 iv2 = v0_pos + vec3(upVec * height); + vec3 r = (iv2 - v2_pos) * stiffness; + + // ---------- Calculate wind ---------- + + // Calculate wind equation based on position + // https://www.cg.tuwien.ac.at/research/publications/2013/JAHRMANN-2013-IGR/JAHRMANN-2013-IGR-paper.pdf + + vec3 windDir = normalize(vec3(1.0, 0.0, 1.0)); + float windSpeed = 5.0; + + float c1 = 0.2; + float c2 = 0.2; + float c3 = 0.2; + float epsilon = 0.00001; + float a_p = (PI * v0_pos.x) + totalTime + ((PI / 4.0) / (abs(cos(PI * v0_pos.z * c2)) + epsilon)); + float w_p = sin(c1 * a_p) * cos(c3 * a_p); + + vec3 windStrength = windDir * windSpeed * w_p; + + // Calculate alignment + float dirAlign = 1.0 - abs(dot(normalize(windStrength) , normalize(v2_pos - v0_pos))); + float heightRatio = dot((v2_pos - v0_pos), upVec) / height; + float alignment = dirAlign * heightRatio; + + vec3 w = windStrength * alignment; + + // ---------- Calculate total force ---------- + vec3 tv2 = (g + r + w) * deltaTime; + + // ---------- Update v2_pos ---------- + v2_pos += tv2; + + // ---------- State validation ---------- + // Condition 1: Make sure v2_pos is above local plane + v2_pos = v2_pos - upVec * min(dot(upVec, v2_pos - v0_pos), 0.0); + + // Condition 2: Set v1_pos according to v2_pos + float lproj = length(v2_pos - v0_pos - upVec * dot(v2_pos - v0_pos, upVec)); + v1_pos = v0_pos + height * upVec * max( (1 - lproj / height) , (0.05 * max(lproj / height, 1.0)) ); + + // Condition 3: Length of curve must be equal to height of grass blade + float L0 = distance(v0_pos, v2_pos); + float L1 = distance(v0_pos, v1_pos) + distance(v1_pos, v2_pos); + float n = 2.0; // Since this is a 2nd degree bezier curve + float L = ((2.0 * L0) + (n - 1.0) * L1) / (n + 1.0); + + // Final corrections + float ratio = height / L; + vec3 v1_corr = v0_pos + ratio * (v1_pos - v0_pos); + vec3 v2_corr = v1_corr + ratio * (v2_pos - v1_pos); + blades[index].v1.xyz = v1_corr; + blades[index].v2.xyz = v2_corr; + + // THIS IS WRONG - LESSON LEARNED + // THIS IS CHANGING THE COPY + //currBlade.v1.xyz = v0_pos + ratio * (v1_pos - v0_pos); + //currBlade.v2.xyz = currBlade.v1.xyz + ratio * (v2_pos - v1_pos); + + // ---------------------------------------- CULLING TESTS ---------------------------------------- // 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 + + + // Orientation culling ------------------------ + // https://gamedev.stackexchange.com/questions/22283/how-to-get-translation-from-view-matrix + mat4 inverseView = inverse(camera.view); + vec3 eyeWorldPos = (inverseView * vec4(0.0, 0.0, 0.0, 1.0)).xyz; + vec3 viewDir = normalize(eyeWorldPos - v0_pos); + float cullThreshold = 0.9; + bool orientationCull = abs(dot(viewDir, frontDir)) > cullThreshold; + + + // View-frustum culling ------------------------ + vec4 v0_ndc = camera.proj * camera.view * vec4(v0_pos, 1.0); + vec4 v2_ndc = camera.proj * camera.view * vec4(v2_pos, 1.0); + vec3 midpt = (0.25 * v0_pos) + (0.5 * v1_pos) + (0.25 + v2_pos); + vec4 midpt_ndc = camera.proj * camera.view * vec4(midpt, 1.0); + + float tolerance = 3.5; + + float v0_h = v0_ndc.w + tolerance; + float v2_h = v2_ndc.w + tolerance; + float midpt_h = midpt_ndc.w + tolerance; + + bool viewFrustCull = false; + + viewFrustCull = !(inBounds(v0_ndc.x, v0_h)) || !(inBounds(v0_ndc.y, v0_h)) || !(inBounds(v0_ndc.z, v0_h)); + + if(viewFrustCull) + { + bool midpt_test = !(inBounds(midpt_ndc.x, midpt_h)) || !(inBounds(midpt_ndc.y, midpt_h)) || !(inBounds(midpt_ndc.z, midpt_h)); + viewFrustCull = viewFrustCull && midpt_test; + } + + if(viewFrustCull) + { + bool v2_test = !(inBounds(v2_ndc.x, v2_h)) || !(inBounds(v2_ndc.y, v2_h)) || !(inBounds(v2_ndc.z, v2_h)); + viewFrustCull = viewFrustCull && v2_test; + } + + // Distance culling ------------------------ + float d_proj = length( v0_pos - eyeWorldPos - ( upVec * dot( v0_pos - eyeWorldPos, upVec ) ) ); + float d_max = 50.0; + float num_buckets = 10.0; + bool distanceCull = mod(index, num_buckets) > floor( num_buckets * (1.0 - d_proj / d_max) ); + + + // http://www.nvidia.com/content/siggraph/Rollin_Oster_OpenGL_CUDA.pdf (slide 21) + // index = atomicAdd(totalVerts, vertsInSurface) + + if(!orientationCull && !viewFrustCull && !distanceCull) + { + culledBlades[atomicAdd(numBlades.vertexCount, 1)] = currBlade; + } + } diff --git a/src/shaders/grass.frag b/src/shaders/grass.frag index c7df157..c8274ef 100644 --- a/src/shaders/grass.frag +++ b/src/shaders/grass.frag @@ -8,10 +8,35 @@ layout(set = 0, binding = 0) uniform CameraBufferObject { // TODO: Declare fragment shader inputs +// Input from tess. eval +layout (location = 0) in vec4 te_position; +layout (location = 1) in vec4 te_normal; +layout (location = 2) in vec2 te_uv; + layout(location = 0) out vec4 outColor; + +// Cubic approximation of gaussian curve so we falloff to exactly 0 at the light radius +float cubicGaussian(float h) { + if (h < 1.0) { + return 0.25 * pow(2.0 - h, 3.0) - pow(1.0 - h, 3.0); + } else if (h < 2.0) { + return 0.25 * pow(2.0 - h, 3.0); + } else { + return 0.0; + } +} + void main() { // TODO: Compute fragment color - outColor = vec4(1.0); + // Lambert + vec3 lightPosition = vec3(0.0, 5.0, 0.0); + vec3 fixedView = normalize(-te_position.xyz); + vec3 fixedNormal = faceforward(te_normal.xyz, fixedView, -te_normal.xyz); + float lambertTerm = clamp( dot( fixedNormal, normalize(lightPosition - te_position.xyz) ), 0.0, 1.0 ); + + vec4 ambientLight = vec4(1.25); + vec4 albedo = vec4(0.13, 0.56, 0.13, 1.0); + outColor = ambientLight * albedo * lambertTerm; } diff --git a/src/shaders/grass.tesc b/src/shaders/grass.tesc index f9ffd07..4e7610e 100644 --- a/src/shaders/grass.tesc +++ b/src/shaders/grass.tesc @@ -1,26 +1,60 @@ #version 450 #extension GL_ARB_separate_shader_objects : enable +// TESS. CONTROL = CONFIGURE TESSELLATION PARAMETERS HERE + + +// Number of vertices per patch according to (aka output patch size) +// http://in2gpu.com/2014/07/12/tessellation-tutorial-opengl-4-3/ layout(vertices = 1) out; + layout(set = 0, binding = 0) uniform CameraBufferObject { mat4 view; mat4 proj; } camera; + // TODO: Declare tessellation control shader inputs and outputs +// Input from vert shader +layout (location = 0) in vec4 v_v0[]; +layout (location = 1) in vec4 v_v1[]; +layout (location = 2) in vec4 v_v2[]; + +// Output from tess. control to the tess. eval shader +// Output as vertices or patches? -- > https://www.khronos.org/opengl/wiki/Tessellation_Control_Shader +layout (location = 0) out vec4 tc_v0[]; +layout (location = 1) out vec4 tc_v1[]; +layout (location = 2) out vec4 tc_v2[]; + + +/* + NOTES: + * gl_out and gl_in are arrays of vertices + * gl_InvocationID = identify each vertex + * gl_Position = position of vertex in vec4 +*/ + 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 + tc_v0[gl_InvocationID] = v_v0[gl_InvocationID]; + tc_v1[gl_InvocationID] = v_v1[gl_InvocationID]; + tc_v2[gl_InvocationID] = v_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] = ??? + // TODO: Set level of tessellation + // Note: These are per-patch outputs, only need to be written once + // QUESTION: Why not put it in "if(gl_InvocationID == 0)"??? + // Then you only write them from a single execution thread (http://prideout.net/blog/?p=48) + gl_TessLevelInner[0] = 2.0; // Horizontal tessellation + gl_TessLevelInner[1] = 5.0; // Vertical tessellation, make this the same + gl_TessLevelOuter[0] = 5.0; // Vertical edge 0-3, make this the same + gl_TessLevelOuter[1] = 2.0; // Horizontal edge 2-3 + gl_TessLevelOuter[2] = 5.0; // Vertical edge 1-2, make this the same + gl_TessLevelOuter[3] = 2.0; // Horizontal edge 0-1 } diff --git a/src/shaders/grass.tese b/src/shaders/grass.tese index 751fff6..9c0b8c6 100644 --- a/src/shaders/grass.tese +++ b/src/shaders/grass.tese @@ -1,6 +1,12 @@ #version 450 #extension GL_ARB_separate_shader_objects : enable +// TESS. EVAL = CONFIGURE VERTICES' WORLD POSITIONS +// https://www.khronos.org/opengl/wiki/Tessellation_Evaluation_Shader + +// This layout qualifier controls how Tessellator generates verts +// primitive mode, vertex spacing, and ordering +// http://prideout.net/blog/?p=48 layout(quads, equal_spacing, ccw) in; layout(set = 0, binding = 0) uniform CameraBufferObject { @@ -10,9 +16,59 @@ layout(set = 0, binding = 0) uniform CameraBufferObject { // TODO: Declare tessellation evaluation shader inputs and outputs +// Input from tess. control +layout (location = 0) in vec4 tc_v0[]; +layout (location = 1) in vec4 tc_v1[]; +layout (location = 2) in vec4 tc_v2[]; + +// Output from tess. eval to frag shader (make sure they're in clip space!) +layout (location = 0) out vec4 te_position; +layout (location = 1) out vec4 te_normal; +layout (location = 2) out vec2 te_uv; + + 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 + + // Direction vector along width of the blade + float width = tc_v2[0].w; + float theta = tc_v0[0].w; + vec3 bitangent = vec3(sin(theta), 0.0, cos(theta)); + + vec3 a = tc_v0[0].xyz + v * (tc_v1[0].xyz - tc_v0[0].xyz); + vec3 b = tc_v1[0].xyz + v * (tc_v2[0].xyz - tc_v1[0].xyz); + vec3 c = a + v * (b - a); + + // Create the curve points along bezier curve + vec3 c0 = c - width * bitangent; + vec3 c1 = c + width * bitangent; + + vec3 tangent = normalize(b - a); + vec3 normal = normalize(cross(tangent, bitangent)); + + // Create grass shape ------------------------------ + + // Quad + // float t = u; + + // Triangle + float t = u + (0.5 * v) - (u * v); + + // Quadratic + // float t = u - pow(u * v, 2); + + // Triangle-tip + // float tau = 0.5; + // float t = 0.5 + (u - 0.5) * (1.0 - (max(v - tau, 0.0) / (1.0 - tau))); + + vec3 position = mix(c0, c1, t); + te_position = vec4(position.xyz, 1.0); + te_normal = vec4(normal, 1.0); + te_uv = vec2(u, v); + + gl_Position = camera.proj * camera.view * te_position; + } diff --git a/src/shaders/grass.vert b/src/shaders/grass.vert index db9dfe9..6585c32 100644 --- a/src/shaders/grass.vert +++ b/src/shaders/grass.vert @@ -8,10 +8,37 @@ layout(set = 1, binding = 0) uniform ModelBufferObject { // TODO: Declare vertex shader inputs and outputs +// Input from compute shader/CPU +layout (location = 0) in vec4 v0; +layout (location = 1) in vec4 v1; +layout (location = 2) in vec4 v2; +layout (location = 3) in vec4 up; + +// Output from vert shader to tess. control shader +layout (location = 0) out vec4 v_v0; +layout (location = 1) out vec4 v_v1; +layout (location = 2) out vec4 v_v2; + out gl_PerVertex { vec4 gl_Position; }; void main() { // TODO: Write gl_Position and any other shader outputs + + // Multiplying by model matrix brings from local/tangent space to world space + + //vec4 world_v0 = model * vec4(v0.xyz, 1.0); + //v_v0 = vec4(world_v0.xyz, v0.w); + //v_v1 = vec4((model * vec4(v1.xyz, 1.0)).xyz, v1.w); + //v_v2 = vec4((model * vec4(v2.xyz, 1.0)).xyz, v2.w); + + // Send in v0 since that's the blade's position on the plane + //gl_Position = world_v0; + + + v_v0 = v0; + v_v1 = v1; + v_v2 = v2; + gl_Position = vec4(v0.xyz, 1.0); }