diff --git a/README.md b/README.md
index a744a2e..dbb209b 100644
--- a/README.md
+++ b/README.md
@@ -1,249 +1,134 @@
-Instructions - Vulkan Grass Rendering
+Vulkan Grass Rendering
========================
-This is due **Sunday 11/5, evening at midnight**.
+`Rishabh Shah`
-**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.
+`Tested on: Windows 10, i7-6700HQ @ 2.6GHz 16GB, GTX 960M 4096MB (Laptop)`
-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.
+
-
+*The scene was rendered in 1000x725 resolution with 216 grass blades (before culling optimizations). The number on top left shows the FPS count.*
-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.
+## 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!
+In this project, I implemented a grass simulator and renderer in Vulkan. The grass blades are represented as Bezier curves, and tessellated in tessellation shaders. The wind, gravity and recovery forces are simulated using a compute shader. Grass blades are culled in three different ways, which is explored in the following sections. The bezier control points are transformed in a vertex shader, tesselated in tesselation shaders, and shaded in fragment a shader.
-### 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.
-
-
-
-## 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.
+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).
-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
+## Code Tour
-See below for more guidance.
+#### Code Contents
-## Base Code Tour
+* `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
-Areas that you need to complete are
-marked with a `TODO` comment. Functions that are useful
-for reference are marked with the comment `CHECKITOUT`.
+#### Important Files
* `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/Renderer.cpp` contains most of the rendering implementation, including Vulkan setup and resource creation.
* `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/Model.cpp` manages the state of the model that grass will be created on. Currently a plane is hardcoded.
* `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.
+## Grass Rendering
### 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.
-
-
+* `v1`: a Bezier curve guide
+* `v2`: a physical guide which we simulate forces on
### 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.
+We first apply transformations to `v2` and then update `v1` to maintain the appropriate length of our grass blade.
-#### Gravity
+##### 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`.
+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`.
-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`.
+##### Recovery
-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.
+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
+##### Wind
+
+In order to simulate wind, I have used a combination of multiple sine and cosine waves.
-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.
+##### Total force
-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!
+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. We apply correction to ensure that the blades don't go below the ground level.
-Once you have a wind direction and a wind alignment term, your total wind force (`w`) will be `windDirection * windAlignment`.
-#### Total force
+### Culling Tests
-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.
+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.
-Read section 5.2 of the paper in order to learn how to determine the corrected final positions for `v1` and `v2`.
+##### Orientation culling
-### Culling tests
+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. These blades are culled using a simple dot product to check its orientation relative to the camera's look vector.
-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.
+*The gif below shows the blades that will be culled. Notice the blades in the distance that are causing aliasing.*
-#### 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
-#### 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.
-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.
+*The gif below shows an exaggerated view-frustum culling.*
-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
+##### 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.
+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. The probability of a blade to get drawn decreases with increasing distance.
-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.
+*The gif below shows the result of distance culling.*
-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)
+### Distance based tessellation of Bezier curves
-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!
+The grass blades are tesselated as quads with details based on distance. The blades farther away have less tesselation than those close to the camera. This [tutorial on tessellation ](http://in2gpu.com/2014/07/12/tessellation-tutorial-opengl-4-3/) was referenced for understanding tesselation shaders.
-### Tessellating Bezier curves into grass blades
+*The gif below shows the result of tesselation based on distance to get high details closer to the camera, and low-poly blades far away.*
-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.
+### Performance evaluation
-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!
+| Blades (2^) | All optimizations | w/o view frust cull | w/o dist cull | w/o orient cull | no culling |
+| ----- | ----- | ----- | ----- | ----- | ----- |
+|13 | 846| 719 | 644 | 820 | 540 |
+|16 |283 | 199 |180 | 270 | 165 |
+|19 |52 | 32 |31 |48 | 27 |
+|22 |7 | 5 | 5 | 7 | 4 |
-** 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.
+It is worth noting that orientation culling wasn't implemented for performance gain, but to reduce the aliasing artefact. The other two techniques give a significant boost.
-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/).
+Also, for tesselation based on distance, my implementation adds detail (up to 10 divisions in vertically and 4 divisions horizontally) to the base configuration (4 divisions in vertically and 2 divisions horizontally). So, the performance will decrease just a little bit when there are a large number of blades close to the camera, but the visual quality is significantly increased.
-## Resources
+
-### Links
+## References
-The following resources may be useful for this project.
+The following resources were 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)
@@ -251,47 +136,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.
-* 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/img/chart.png b/img/chart.png
new file mode 100644
index 0000000..58b3c22
Binary files /dev/null and b/img/chart.png differ
diff --git a/img/cull_dist.gif b/img/cull_dist.gif
new file mode 100644
index 0000000..a1ddc82
Binary files /dev/null and b/img/cull_dist.gif differ
diff --git a/img/cull_frust.gif b/img/cull_frust.gif
new file mode 100644
index 0000000..e7896c5
Binary files /dev/null and b/img/cull_frust.gif differ
diff --git a/img/cull_orient.gif b/img/cull_orient.gif
new file mode 100644
index 0000000..31a68a9
Binary files /dev/null and b/img/cull_orient.gif differ
diff --git a/img/demo.gif b/img/demo.gif
new file mode 100644
index 0000000..f026590
Binary files /dev/null and b/img/demo.gif differ
diff --git a/img/tess_dist.gif b/img/tess_dist.gif
new file mode 100644
index 0000000..4b2ce31
Binary files /dev/null and b/img/tess_dist.gif differ
diff --git a/src/Blades.h b/src/Blades.h
index 9bd1eed..5776858 100644
--- a/src/Blades.h
+++ b/src/Blades.h
@@ -4,11 +4,11 @@
#include
#include "Model.h"
-constexpr static unsigned int NUM_BLADES = 1 << 13;
-constexpr static float MIN_HEIGHT = 1.3f;
-constexpr static float MAX_HEIGHT = 2.5f;
-constexpr static float MIN_WIDTH = 0.1f;
-constexpr static float MAX_WIDTH = 0.14f;
+constexpr static unsigned int NUM_BLADES = 1 << 16; // 13;
+constexpr static float MIN_HEIGHT = 1.0f; // 1.3f;
+constexpr static float MAX_HEIGHT = 2.5f; // 2.5f;
+constexpr static float MIN_WIDTH = 0.05f; // 0.1f;
+constexpr static float MAX_WIDTH = 0.07f; // 0.14f;
constexpr static float MIN_BEND = 7.0f;
constexpr static float MAX_BEND = 13.0f;
diff --git a/src/Camera.cpp b/src/Camera.cpp
index 3afb5b8..732621c 100644
--- a/src/Camera.cpp
+++ b/src/Camera.cpp
@@ -9,10 +9,10 @@
#include "BufferUtils.h"
Camera::Camera(Device* device, float aspectRatio) : device(device) {
- r = 10.0f;
- theta = 0.0f;
- phi = 0.0f;
- cameraBufferObject.viewMatrix = glm::lookAt(glm::vec3(0.0f, 1.0f, 10.0f), glm::vec3(0.0f, 1.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f));
+ r = glm::length(glm::vec3(0.0f, 10.0f, 10.0f)); // 10.0f;
+ theta = 0.0f;
+ phi = -45.f; // 0.0f;
+ cameraBufferObject.viewMatrix = glm::lookAt(glm::vec3(0.0f, 10.0f, 10.0f), glm::vec3(0.0f, 1.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f));
cameraBufferObject.projectionMatrix = glm::perspective(glm::radians(45.0f), aspectRatio, 0.1f, 100.0f);
cameraBufferObject.projectionMatrix[1][1] *= -1; // y-coordinate is flipped
diff --git a/src/Renderer.cpp b/src/Renderer.cpp
index b445d04..197cff0 100644
--- a/src/Renderer.cpp
+++ b/src/Renderer.cpp
@@ -18,6 +18,7 @@ Renderer::Renderer(Device* device, SwapChain* swapChain, Scene* scene, Camera* c
CreateCommandPools();
CreateRenderPass();
CreateCameraDescriptorSetLayout();
+ CreateGrassDescriptorSetLayout();
CreateModelDescriptorSetLayout();
CreateTimeDescriptorSetLayout();
CreateComputeDescriptorSetLayout();
@@ -144,6 +145,35 @@ void Renderer::CreateCameraDescriptorSetLayout() {
}
}
+void Renderer::CreateGrassDescriptorSetLayout() {
+ // Describe the binding of the descriptor set layout
+ VkDescriptorSetLayoutBinding uboLayoutBinding = {};
+ uboLayoutBinding.binding = 0;
+ uboLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
+ uboLayoutBinding.descriptorCount = 1;
+ uboLayoutBinding.stageFlags = VK_SHADER_STAGE_VERTEX_BIT;
+ uboLayoutBinding.pImmutableSamplers = nullptr;
+
+ VkDescriptorSetLayoutBinding samplerLayoutBinding = {};
+ samplerLayoutBinding.binding = 1;
+ samplerLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
+ samplerLayoutBinding.descriptorCount = 1;
+ samplerLayoutBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
+ samplerLayoutBinding.pImmutableSamplers = nullptr;
+
+ std::vector bindings = { uboLayoutBinding, samplerLayoutBinding };
+
+ // 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("CreateGrassDescriptorSetLayout() : Failed to create descriptor set layout");
+ }
+}
+
void Renderer::CreateModelDescriptorSetLayout() {
VkDescriptorSetLayoutBinding uboLayoutBinding = {};
uboLayoutBinding.binding = 0;
@@ -198,6 +228,42 @@ 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
+
+ // A lot like Renderer::CreateTimeDescriptorSetLayout()..
+
+ VkDescriptorSetLayoutBinding inBladesBinding = {};
+ inBladesBinding.binding = 0;
+ inBladesBinding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; // storage buffer not uniform
+ inBladesBinding.descriptorCount = 1;
+ inBladesBinding.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT;
+ inBladesBinding.pImmutableSamplers = nullptr;
+
+ VkDescriptorSetLayoutBinding outBladesBinding = {};
+ outBladesBinding.binding = 1;
+ outBladesBinding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; // storage buffer not uniform
+ outBladesBinding.descriptorCount = 1;
+ outBladesBinding.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT;
+ outBladesBinding.pImmutableSamplers = nullptr;
+
+ VkDescriptorSetLayoutBinding numBladesBinding = {};
+ numBladesBinding.binding = 2;
+ numBladesBinding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; // storage buffer not uniform
+ numBladesBinding.descriptorCount = 1;
+ numBladesBinding.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT;
+ numBladesBinding.pImmutableSamplers = nullptr;
+
+ std::vector bindings =
+ { inBladesBinding, outBladesBinding, numBladesBinding };
+
+ // 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("CreateComputeDescriptorSetLayout() : Failed to create descriptor set layout");
+ }
}
void Renderer::CreateDescriptorPool() {
@@ -216,6 +282,7 @@ void Renderer::CreateDescriptorPool() {
{ VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER , 1 },
// TODO: Add any additional types and counts of descriptors you will need to allocate
+ { VK_DESCRIPTOR_TYPE_STORAGE_BUFFER , 3 * (uint32_t)scene->GetBlades().size() } // size*3 or just 3..??
};
VkDescriptorPoolCreateInfo poolInfo = {};
@@ -320,6 +387,49 @@ 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[] = { 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("CreateGrassDescriptorSets() : Failed to allocate descriptor set");
+ }
+
+ std::vector descriptorWrites(grassDescriptorSets.size()); // *2..??
+
+ for (uint32_t i = 0; i < scene->GetBlades().size(); ++i) {
+ VkDescriptorBufferInfo modelBufferInfo = {};
+ modelBufferInfo.buffer = scene->GetBlades()[i]->GetModelBuffer();
+ modelBufferInfo.offset = 0;
+ modelBufferInfo.range = sizeof(ModelBufferObject);
+
+ // TODO: DO SOMETHING HERE....????
+ // Bind image and sampler resources to the descriptor...????
+ /* VkDescriptorImageInfo imageInfo = {};
+ imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
+ imageInfo.imageView = scene->GetModels()[i]->GetTextureView();
+ imageInfo.sampler = scene->GetModels()[i]->GetTextureSampler();*/
+
+ 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 = &modelBufferInfo;
+ descriptorWrites[i].pImageInfo = nullptr;
+ descriptorWrites[i].pTexelBufferView = nullptr;
+ }
+
+ // Update descriptor sets
+ vkUpdateDescriptorSets(logicalDevice, static_cast(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr);
}
void Renderer::CreateTimeDescriptorSet() {
@@ -360,6 +470,72 @@ 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());
+
+ // 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("CreateComputeDescriptorSets() : Failed to allocate descriptor set");
+ }
+
+ std::vector descriptorWrites(3 * computeDescriptorSets.size());
+
+ for (uint32_t i = 0; i < scene->GetBlades().size(); ++i) {
+ VkDescriptorBufferInfo inBladesInfo= {};
+ inBladesInfo.buffer = scene->GetBlades()[i]->GetBladesBuffer();
+ inBladesInfo.offset = 0;
+ inBladesInfo.range = NUM_BLADES * sizeof(Blade);
+
+ VkDescriptorBufferInfo outBladesInfo = {};
+ outBladesInfo.buffer = scene->GetBlades()[i]->GetCulledBladesBuffer();
+ outBladesInfo.offset = 0;
+ outBladesInfo.range = NUM_BLADES * sizeof(Blade);
+
+ VkDescriptorBufferInfo numBladesInfo = {};
+ numBladesInfo.buffer = scene->GetBlades()[i]->GetNumBladesBuffer();
+ numBladesInfo.offset = 0;
+ numBladesInfo.range = sizeof(BladeDrawIndirect);
+
+ 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 = &inBladesInfo;
+ 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 = &outBladesInfo;
+ 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 = &numBladesInfo;
+ 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() {
@@ -426,7 +602,7 @@ void Renderer::CreateGraphicsPipeline() {
rasterizer.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
rasterizer.depthClampEnable = VK_FALSE;
rasterizer.rasterizerDiscardEnable = VK_FALSE;
- rasterizer.polygonMode = VK_POLYGON_MODE_FILL;
+ rasterizer.polygonMode = VK_POLYGON_MODE_FILL; // VK_POLYGON_MODE_LINE;
rasterizer.lineWidth = 1.0f;
rasterizer.cullMode = VK_CULL_MODE_BACK_BIT;
rasterizer.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
@@ -600,7 +776,7 @@ void Renderer::CreateGrassPipeline() {
rasterizer.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
rasterizer.depthClampEnable = VK_FALSE;
rasterizer.rasterizerDiscardEnable = VK_FALSE;
- rasterizer.polygonMode = VK_POLYGON_MODE_FILL;
+ rasterizer.polygonMode = VK_POLYGON_MODE_FILL; // VK_POLYGON_MODE_LINE;
rasterizer.lineWidth = 1.0f;
rasterizer.cullMode = VK_CULL_MODE_NONE;
rasterizer.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
@@ -717,7 +893,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 = {};
@@ -884,6 +1060,12 @@ void Renderer::RecordComputeCommandBuffer() {
vkCmdBindDescriptorSets(computeCommandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, computePipelineLayout, 1, 1, &timeDescriptorSet, 0, nullptr);
// TODO: For each group of blades bind its descriptor set and dispatch
+ for (size_t i = 0; i < scene->GetBlades().size(); i++) {
+ vkCmdBindDescriptorSets(computeCommandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, computePipelineLayout, 2, 1, &computeDescriptorSets[i], 0, nullptr);
+ // TODO: NOT SURE ABOUT THIS STEP..
+ int groupsX = ceil(NUM_BLADES / WORKGROUP_SIZE);
+ vkCmdDispatch(computeCommandBuffer, groupsX, 1, 1);
+ }
// ~ End recording ~
if (vkEndCommandBuffer(computeCommandBuffer) != VK_SUCCESS) {
@@ -976,13 +1158,14 @@ void Renderer::RecordCommandBuffers() {
VkBuffer vertexBuffers[] = { scene->GetBlades()[j]->GetCulledBladesBuffer() };
VkDeviceSize offsets[] = { 0 };
// TODO: Uncomment this when the buffers are populated
- // vkCmdBindVertexBuffers(commandBuffers[i], 0, 1, vertexBuffers, offsets);
+ vkCmdBindVertexBuffers(commandBuffers[i], 0, 1, vertexBuffers, offsets);
// TODO: Bind the descriptor set for each grass blades model
+ vkCmdBindDescriptorSets(commandBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, 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));
+ vkCmdDrawIndirect(commandBuffers[i], scene->GetBlades()[j]->GetNumBladesBuffer(), 0, 1, sizeof(BladeDrawIndirect));
}
// End render pass
@@ -1042,6 +1225,8 @@ Renderer::~Renderer() {
vkDeviceWaitIdle(logicalDevice);
// TODO: destroy any resources you created
+ vkDestroyDescriptorSetLayout(logicalDevice, computeDescriptorSetLayout, nullptr);
+ vkDestroyDescriptorSetLayout(logicalDevice, grassDescriptorSetLayout, nullptr);
vkFreeCommandBuffers(logicalDevice, graphicsCommandPool, static_cast(commandBuffers.size()), commandBuffers.data());
vkFreeCommandBuffers(logicalDevice, computeCommandPool, 1, &computeCommandBuffer);
diff --git a/src/Renderer.h b/src/Renderer.h
index 95e025f..2a35e40 100644
--- a/src/Renderer.h
+++ b/src/Renderer.h
@@ -16,6 +16,7 @@ class Renderer {
void CreateRenderPass();
void CreateCameraDescriptorSetLayout();
+ void CreateGrassDescriptorSetLayout();
void CreateModelDescriptorSetLayout();
void CreateTimeDescriptorSetLayout();
void CreateComputeDescriptorSetLayout();
@@ -56,12 +57,16 @@ class Renderer {
VkDescriptorSetLayout cameraDescriptorSetLayout;
VkDescriptorSetLayout modelDescriptorSetLayout;
VkDescriptorSetLayout timeDescriptorSetLayout;
+ VkDescriptorSetLayout computeDescriptorSetLayout; // todo
+ VkDescriptorSetLayout grassDescriptorSetLayout; // todo
VkDescriptorPool descriptorPool;
VkDescriptorSet cameraDescriptorSet;
std::vector modelDescriptorSets;
VkDescriptorSet timeDescriptorSet;
+ std::vector computeDescriptorSets; // todo
+ std::vector grassDescriptorSets; // todo
VkPipelineLayout graphicsPipelineLayout;
VkPipelineLayout grassPipelineLayout;
diff --git a/src/main.cpp b/src/main.cpp
index 8bf822b..3d9ef3f 100644
--- a/src/main.cpp
+++ b/src/main.cpp
@@ -67,7 +67,8 @@ namespace {
int main() {
static constexpr char* applicationName = "Vulkan Grass Rendering";
- InitializeWindow(640, 480, applicationName);
+ //InitializeWindow(640, 480, applicationName);
+ InitializeWindow(1000, 750, applicationName);
unsigned int glfwExtensionCount = 0;
const char** glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount);
@@ -90,7 +91,7 @@ int main() {
swapChain = device->CreateSwapChain(surface, 5);
- camera = new Camera(device, 640.f / 480.f);
+ camera = new Camera(device, 1000.f / 750.f);
VkCommandPoolCreateInfo transferPoolInfo = {};
transferPoolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
@@ -116,7 +117,7 @@ int main() {
grassImageMemory
);
- float planeDim = 15.f;
+ float planeDim = 30.f;// 15.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..82ce161 100644
--- a/src/shaders/compute.comp
+++ b/src/shaders/compute.comp
@@ -21,20 +21,23 @@ struct Blade {
vec4 up;
};
-// TODO: Add bindings to:
-// 1. Store the input blades
-// 2. Write out the culled blades
-// 3. Write the total number of blades remaining
-
-// 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;
+// Input blades array
+layout(set = 2, binding = 0) buffer InBlades {
+ Blade inBlades[];
+};
+
+// Culled blades array
+layout(set = 2, binding = 1) buffer OutBlades {
+ Blade outBlades[];
+};
+
+// NumBlades Info
+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);
@@ -42,15 +45,104 @@ bool inBounds(float value, float bounds) {
void main() {
// Reset the number of blades to 0
- if (gl_GlobalInvocationID.x == 0) {
- // numBlades.vertexCount = 0;
+ uint index = gl_GlobalInvocationID.x;
+ 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
+ // TODO: Apply forces on every blade and update the vertices in the buffer
+ Blade blade = inBlades[index]; // read a blade..
+ vec3 v0 = blade.v0.xyz;
+ vec3 v1 = blade.v1.xyz;
+ vec3 v2 = blade.v2.xyz;
+ vec3 up = blade.up.xyz;
+ float orientation = blade.v0.w;
+ float height = blade.v1.w;
+ float width = blade.v2.w;
+ float stiffness = blade.up.w;
+
+ // gravity
+ vec4 D = vec4(0.0, -1.0, 0.0, 9.81);
+ vec3 gE = normalize(D.xyz) * D.w;
+ vec3 orientVec = vec3(sin(orientation), 0.0, cos(orientation));
+ vec3 f = normalize(cross(up, orientVec));
+ vec3 gF = 0.25 * length(gE) * f;
+ vec3 g = gE + gF;
+
+ // recovery
+ vec3 iv2 = v0 + height * up;
+ vec3 rec = (iv2 - v2) * stiffness;
+
+ // wind
+ vec3 windDir = vec3(1.0, 0.0, 1.0);
+ float windComp = 2.0 * 2.0 * sin(totalTime * 5.0 + 0.3 * dot(windDir + vec3(0.0, 0.0, -1.0), v0))
+ + 2.0 * 3.0 * sin(totalTime * 5.0 + 0.3 * dot(windDir + vec3(1.0, 0.0, 1.0), v0));
+
+ float fd = 1.0 - abs(dot(normalize(windDir), normalize(v2 - v0)));
+ float fr = dot(v2 - v0, up) / height;
+ vec3 wind = windDir * windComp * fd * fr;
+
+ // total
+ vec3 vChange = (g + rec + wind)* deltaTime;
+ v2 += vChange;
+
+ // state validation
+ v2 = v2 - up * min(dot(up, (v2 - v0)), 0.0);
+ vec3 lproj = v2 - v0 - up * dot((v2 - v0), up);
+ float lph = length(lproj) / height;
+ v1 = v0 + height * up * max(1 - lph, 0.05 * max(lph, 1));
+
+ float L0 = distance(v0, v2);
+ float L1 = distance(v0, v1) + distance(v1, v2);
+ float n = 2.0;
+ float L = (2.0 * L0 + (n - 1.0) * L1) / (n + 1.0);
+ float r = height / L;
+ vec3 v1old = v1;
+ v1 = v0 + r * (v1 - v0);
+ v2 = v1 + r * (v2 - v1old);
+
+ // update inBlades[]..
+ blade.v1.xyz = v1;
+ blade.v2.xyz = v2;
+ inBlades[index] = blade;
// 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 // cull blades closer to 0.0 and keep the ones closer to 1.0
+ vec4 forward = normalize(inverse(camera.proj * camera.view) * vec4(0.0, 0.0, 1.0, 0.0));
+ bool cullOrientation = abs(dot(normalize(vec3(forward.x, 0.0, forward.z)), normalize(vec3(f.x, 0.0, f.z)))) < 0.1;
+
+ // view-frustum culling
+ vec4 v0Trans = camera.proj * camera.view * vec4(v0, 1.0);
+ v0Trans /= v0Trans.w;
+ vec4 v2Trans = camera.proj * camera.view * vec4(v2, 1.0);
+ v2Trans /= v2Trans.w;
+ vec3 m = 0.25 * v0 + 0.5 * v1 + 0.25 * v2;
+ vec4 mTrans = camera.proj * camera.view * vec4(m, 1.0);
+ mTrans /= mTrans.w;
+
+ bool cullViewFrust = false;
+ float th = 1.2; // threshold
+ if (v0Trans.x < -th || v0Trans.x > th || v0Trans.y < -th || v0Trans.y > th || v0Trans.z < 0.0 || v0Trans.z > 1.0 ||
+ v2Trans.x < -th || v2Trans.x > th || v2Trans.y < -th || v2Trans.y > th || v2Trans.z < 0.0 || v2Trans.z > 1.0 ||
+ mTrans.x < -th || mTrans.x > th || mTrans.y < -th || mTrans.y > th || mTrans.z < 0.0 || mTrans.z > 1.0) {
+ cullViewFrust = true;
+ }
+
+ // distance culling
+ // Because the blades are uniformly distributed, we can just delete the first few blades
+ // among the blades in a level, without forming gaps..
+ vec4 oPos = (camera.proj * camera.view * vec4(v0, 1.0));
+ oPos /= oPos.w;
+ float d = (40.0 - 40.0 * pow(oPos.z, 4.0));
+ bool cullDistance = index < float(1 << 16) / d * 0.1;
+
+ // cull
+ if (!cullOrientation && !cullViewFrust && !cullDistance) {
+ outBlades[atomicAdd(numBlades.vertexCount, 1)] = inBlades[index];
+ }
}
diff --git a/src/shaders/grass.frag b/src/shaders/grass.frag
index c7df157..4882c47 100644
--- a/src/shaders/grass.frag
+++ b/src/shaders/grass.frag
@@ -7,11 +7,20 @@ layout(set = 0, binding = 0) uniform CameraBufferObject {
} camera;
// TODO: Declare fragment shader inputs
+layout(location = 0) in vec4 inPos;
+layout(location = 1) in vec3 inNor;
+layout(location = 2) in vec2 inUv;
layout(location = 0) out vec4 outColor;
void main() {
- // TODO: Compute fragment color
+ // TODO: Compute fragment color
+ vec4 colTop = vec4(0.4, 0.4, 0.2, 1.0);
+ vec4 colBot = vec4(0.35, 0.35, 0.1, 1.0);
- outColor = vec4(1.0);
+ vec4 col = mix(colBot, colTop, inUv.y);
+
+ vec3 lightDir = normalize(vec3(1.0, 1.0, -1.0));
+ vec4 ambient = vec4(0.05, 0.2, 0.05, 1.0);
+ outColor = clamp(ambient + col * clamp(abs(dot(inNor, lightDir)), 0.1, 1.0), 0.1, 1.0);
}
diff --git a/src/shaders/grass.tesc b/src/shaders/grass.tesc
index f9ffd07..4412652 100644
--- a/src/shaders/grass.tesc
+++ b/src/shaders/grass.tesc
@@ -9,18 +9,41 @@ layout(set = 0, binding = 0) uniform CameraBufferObject {
} camera;
// TODO: Declare tessellation control shader inputs and outputs
+layout(location = 0) in vec4 inV0[];
+layout(location = 1) in vec4 inV1[];
+layout(location = 2) in vec4 inV2[];
+layout(location = 3) in vec4 inUp[];
+
+layout(location = 0) patch out vec4 outV0;
+layout(location = 1) patch out vec4 outV1;
+layout(location = 2) patch out vec4 outV2;
+layout(location = 3) patch out vec4 outUp;
void main() {
// Don't move the origin location of the patch
- gl_out[gl_InvocationID].gl_Position = gl_in[gl_InvocationID].gl_Position;
+ vec4 originPos = gl_in[gl_InvocationID].gl_Position;
+ gl_out[gl_InvocationID].gl_Position = originPos;
// TODO: Write any shader outputs
+ outV0 = inV0[gl_InvocationID];
+ outV1 = inV1[gl_InvocationID];
+ outV2 = inV2[gl_InvocationID];
+ outUp = inUp[gl_InvocationID];
+
+ // TODO: depth based tesselation..
+ vec4 forward = normalize(inverse(camera.proj * camera.view) * vec4(0.0, 0.0, 1.0, 0.0));
+ vec4 oPos = (camera.proj * camera.view * originPos);
+ oPos /= oPos.w;
+ int d = int(40.0 - 40.0 * pow(oPos.z, 4.0));
+ int h = min(d + 2, 4);
+ int v = min(d + 4, 10);
// TODO: Set level of tesselation
- // gl_TessLevelInner[0] = ???
- // gl_TessLevelInner[1] = ???
- // gl_TessLevelOuter[0] = ???
- // gl_TessLevelOuter[1] = ???
- // gl_TessLevelOuter[2] = ???
- // gl_TessLevelOuter[3] = ???
+ gl_TessLevelInner[0] = h; // 2; // horizontal
+ gl_TessLevelInner[1] = v; // 4; // vertical
+
+ gl_TessLevelOuter[0] = v; // 4; // edge 0-3
+ gl_TessLevelOuter[1] = h; // 2; // edge 3-2
+ gl_TessLevelOuter[2] = v; // 4; // edge 2-1
+ gl_TessLevelOuter[3] = h; // 2; // edge 1-0
}
diff --git a/src/shaders/grass.tese b/src/shaders/grass.tese
index 751fff6..731428d 100644
--- a/src/shaders/grass.tese
+++ b/src/shaders/grass.tese
@@ -9,10 +9,35 @@ layout(set = 0, binding = 0) uniform CameraBufferObject {
} camera;
// TODO: Declare tessellation evaluation shader inputs and outputs
+//layout(location = 0) patch in vec4 tese_v1;
+layout(location = 0) patch in vec4 inV0;
+layout(location = 1) patch in vec4 inV1;
+layout(location = 2) patch in vec4 inV2;
+layout(location = 3) patch in vec4 inUp;
+
+layout(location = 0) out vec4 outPos;
+layout(location = 1) out vec3 outNor;
+layout(location = 2) out vec2 outUv;
void main() {
- float u = gl_TessCoord.x;
- float v = gl_TessCoord.y;
+ float u = gl_TessCoord.x;
+ float v = gl_TessCoord.y;
+ outUv = vec2(u, v);
// TODO: Use u and v to parameterize along the grass blade and output positions for each vertex of the grass blade
+ vec3 a = mix(inV0.xyz, inV1.xyz, v);
+ vec3 b = mix(inV1.xyz, inV2.xyz, v);
+ vec3 c = mix(a, b, v);
+
+ vec3 tangent = normalize(b - a);
+ vec3 biTangent = vec3(sin(inV0.w), 0.0, cos(inV0.w));
+ float w = inV2.w;
+ vec3 c0 = c - w * biTangent;
+ vec3 c1 = c + w * biTangent;
+ outNor = normalize(cross(tangent, biTangent));
+
+ float t = u - u*v*v; // quad shape
+ vec3 p = mix(c0, c1, t);
+ outPos = camera.proj * camera.view * vec4(p, 1.0);
+ gl_Position = outPos;
}
diff --git a/src/shaders/grass.vert b/src/shaders/grass.vert
index db9dfe9..16ab900 100644
--- a/src/shaders/grass.vert
+++ b/src/shaders/grass.vert
@@ -7,6 +7,15 @@ layout(set = 1, binding = 0) uniform ModelBufferObject {
};
// TODO: Declare vertex shader inputs and outputs
+layout(location = 0) in vec4 inV0;
+layout(location = 1) in vec4 inV1;
+layout(location = 2) in vec4 inV2;
+layout(location = 3) in vec4 inUp;
+
+layout(location = 0) out vec4 outV0;
+layout(location = 1) out vec4 outV1;
+layout(location = 2) out vec4 outV2;
+layout(location = 3) out vec4 outUp;
out gl_PerVertex {
vec4 gl_Position;
@@ -14,4 +23,10 @@ out gl_PerVertex {
void main() {
// TODO: Write gl_Position and any other shader outputs
+ outV0 = inV0;
+ outV1 = inV1;
+ outV2 = inV2;
+ outUp = inUp;
+
+ gl_Position = vec4(outV0.xyz, 1.0);
}