Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Hw Submission #12

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ add_definitions(-D_CRT_SECURE_NO_WARNINGS -D_SCL_SECURE_NO_WARNINGS)

# Options
include(CMakeDependentOption)
option(ENABLE_BSP "Use Binary Space Partitioning (BSP) Tree for optimized ray traversal" OFF)
option(ENABLE_BSP "Use Binary Space Partitioning (BSP) Tree for optimized ray traversal" ON)

add_executable(eyden-tracer ${INCLUDE} ${SOURCES} ${HEADERS})

Expand Down
12 changes: 6 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
**Dealine**: 28.10.2021

Please put your name here:
**Name:** .......
**Name:** Jackson Whiteley
## Problem 1
### Rendering complex geometry (Points 5)
Until now we have only hardcoded our scene geometry in main.cpp. This is of course not practical. In the new framework, a class ```CSolid``` is added. This class may contain complex geometry formed by multiple primitives. Such geometry may be saved / read from an .obj file. For this problem we will read _torus knot.obj_ file and rended this object, which consists of 12 960 triangles. To make the method work proceed as follows:
Expand All @@ -11,7 +11,7 @@ Until now we have only hardcoded our scene geometry in main.cpp. This is of cour
3. Have a look at the file _torus knot.obj_ and at the class ```CSolid```. Study how triangles are stored in the obj-format and in the class. The _v_ ’s indicate a single 3d-vertex position, and the _f_ ’s (faces) are indecies to 3 vertex numbers a triangle consits of (please note that the face indecies are starting with **1 and not 0**).
4. Implement function ```CScene::add(const CSolid& solid)``` which adds a solid to the scene.
5. Make sure that you work with Release and not Debug and disable BSP support in CMake (if it was enabled). Render the scene and write the time needed for 1 frame below:<br>
**T0:** .......
**T0:** 618.184 sec

> **Note:** Rendering may take several minutes.

Expand All @@ -29,8 +29,8 @@ In order to use not one but all cores of CPU proceed as follows:
1. Study the OpenCV function for parallel data processing ```parallel_for_```: [How to use the OpenCV parallel_for_ to parallelize your code](https://docs.opencv.org/master/d7/dff/tutorial_how_to_use_OpenCV_parallel_for_.html)
2. In main.cpp file rewrite the main rendering loop (lines 53 - 57), by paralellizing the loop ```for (int y = 0; y < img.rows; y++)``` with help of ```parallel_for_``` function and enclosing the inner body into a lambda-expression. You do not need to parallelize the inner loop ```for (int x = 0; x < img.cols; x++)```.
3. Render the scene and write the time needed for 1 frame T1 and speedup = T0 / T1 below:<br>
**T1:** .......<br>
**Speedup:** .......
**T1:** 213.9 sec<br>
**Speedup:** 2.89

## Problem 3
### Implementation of a kd-tree acceleration structure (Points 30)
Expand All @@ -52,8 +52,8 @@ If everything so far was implemented correctly, the Scene bounds will be: [-6, 0
For more information please read the chapter 7.2 in the [thesis of Dr. Ingo Wald](http://www.sci.utah.edu/~wald/PhD/wald_phd.pdf).
6. Implement the method ```std::shared_ptr<CBSPNode> build(const CBoundingBox& box, const std::vector<ptr_prim_t>& vpPrims, size_t depth)``` of the class ```CBSPTree```. Use the ideas presented at the lecture. As soon as you have reached a maximum depth (_e.g._ 20), or you have less then a minimum number of primitives (_e.g._ 3 or 4), stop subdividing and generate a leaf node. Otherweise, split your bounding box in the middle (in the maximum dimension), sort your current primitives into two vector left and right, and recursively call BuildTree with the respective bounding boxes and vector for left and right. Start subdivision with a list of all primitives, the total scene bounds, and an initial recursion depth of 0.<br>
9. Render the scene and write the time needed for 1 frame T2 and speedup = T0 / T2 below:<br>
**T2:** .......<br>
**Speedup:** .......
**T2:** 1.428 sec<br>
**Speedup:** 432.9

> A the solution for this problem can be found in OpenRT library: www.openrt.org However it is highly recommended to solve this problem using lecture slides only and resorting to the solution only as a last resort.

Expand Down
Binary file added renders/torus knot.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
31 changes: 27 additions & 4 deletions src/BSPNode.h
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,34 @@ class CBSPNode
bool intersect(Ray& ray, double t0, double t1) const
{
if (isLeaf()) {
// --- PUT YOUR CODE HERE ---
return false;
bool hit = false;
for (const auto prim : m_vpPrims) {
hit |= prim->intersect(ray);
}
return hit;
} else {
// --- PUT YOUR CODE HERE ---
return false;
// dist between split and ray
double dist = (m_splitVal - ray.org[m_splitDim]) / ray.dir[m_splitDim];

//determin which node is in front
ptr_bspnode_t front;
ptr_bspnode_t back;
if (ray.dir[m_splitDim] < 0) {
front = Right();
back = Left();
} else {
front = Left();
back = Right();
}

if (dist <= t0) { //try back
return back->intersect(ray, t0, t1);
}
if (dist >= t1) { //try front
return front->intersect(ray, t0, t1);
}
//try both
return front->intersect(ray, t0, dist) || back->intersect(ray, dist, t1);
}
}

Expand Down
50 changes: 43 additions & 7 deletions src/BSPTree.h
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,10 @@ namespace {
CBoundingBox calcBoundingBox(const std::vector<ptr_prim_t>& vpPrims)
{
CBoundingBox res;
// --- PUT YOUR CODE HERE ---
for (const auto prim : vpPrims) {
res.extend(prim->getBoundingBox());
}
return res;
}

// Returns the best dimension index for next split
Expand Down Expand Up @@ -54,8 +57,12 @@ class CBSPTree
*/
bool intersect(Ray& ray) const
{
// --- PUT YOUR CODE HERE ---
return false;
double t0, t1;
m_treeBoundingBox.clip(ray, t0, t1);
if (t1 < t0) {
return false;
}
return m_root->intersect(ray, t0, t1);
}


Expand All @@ -69,19 +76,43 @@ class CBSPTree
*/
ptr_bspnode_t build(const CBoundingBox& box, const std::vector<ptr_prim_t>& vpPrims, size_t depth)
{
// Check for stoppong criteria

// Check for stopping criteria
if (depth >= m_maxDepth || vpPrims.size() <= m_minPrimitives)
return std::make_shared<CBSPNode>(vpPrims); // => Create a leaf node and break recursion

// else -> prepare for creating a branch node
// First split the bounding volume into two halfes
int splitDim = MaxDim(box.getMaxPoint() - box.getMinPoint()); // Calculate split dimension as the dimension where the aabb is the widest
float splitVal = (box.getMinPoint()[splitDim] + box.getMaxPoint()[splitDim]) / 2; // Split the aabb exactly in two halfes

int splitDim = depth % 3; // Calculate split dimension as the dimension where the aabb is the widest
// int splitDim = MaxDim(box.getMaxPoint() - box.getMinPoint()); // Calculate split dimension as the dimension where the aabb is the widest


//average the location of all prims in node
// Vec3f avrg = Vec3f::all(0);
// for (const auto prim : vpPrims) {
// auto primBox = prim->getBoundingBox();
// avrg += 0.5 * (primBox.getMinPoint() - primBox.getMaxPoint()) + primBox.getMinPoint();
// }
// avrg *= 1.0f / vpPrims.size();

//find the mid point of all prims in node
// std::vector<float> foo;
// for (const auto prim : vpPrims) {
// auto primBox = prim->getBoundingBox();
// foo.push_back(0.5 * (primBox.getMinPoint()[splitDim] - primBox.getMaxPoint()[splitDim]) + primBox.getMinPoint()[splitDim]);
// }
// sort(foo.begin(), foo.end());

// float splitVal = (foo[foo.size()/2] + foo[foo.size()/2 +1]) / 2;
// float splitVal = avrg[splitDim];
float splitVal = (box.getMinPoint()[splitDim] + box.getMaxPoint()[splitDim]) / 2; // Split the aabb exactly in two halfes

auto splitBoxes = box.split(splitDim, splitVal);
CBoundingBox& lBox = splitBoxes.first;
CBoundingBox& rBox = splitBoxes.second;

// Second order the primitives into new nounding boxes
// Second order the primitives into new bounding boxes
std::vector<ptr_prim_t> lPrim;
std::vector<ptr_prim_t> rPrim;
for (auto pPrim : vpPrims) {
Expand All @@ -91,6 +122,11 @@ class CBSPTree
rPrim.push_back(pPrim);
}

// int diff = abs(lPrim.size() - rPrim.size());
// if (diff > 1) {
// std::cout << diff << std::endl;
// }

// Next build recursively 2 subtrees for both halfes
auto pLeft = build(lBox, lPrim, depth + 1);
auto pRight = build(rBox, rPrim, depth + 1);
Expand Down
45 changes: 37 additions & 8 deletions src/BoundingBox.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -15,29 +15,58 @@ namespace {

void CBoundingBox::extend(const Vec3f& p)
{
// --- PUT YOUR CODE HERE ---
m_minPoint = Min3f(m_minPoint, p);
m_maxPoint = Max3f(m_maxPoint, p);
}

void CBoundingBox::extend(const CBoundingBox& box)
{
// --- PUT YOUR CODE HERE ---
m_minPoint = Min3f(m_minPoint, box.getMinPoint());
m_maxPoint = Max3f(m_maxPoint, box.getMaxPoint());
}

std::pair<CBoundingBox, CBoundingBox> CBoundingBox::split(int dim, float val) const
{
// --- PUT YOUR CODE HERE ---
auto res = std::make_pair(*this, *this);
return res;
// create new box to represent up to val
CBoundingBox lBox;
lBox.extend(*this);
lBox.m_maxPoint[dim] = val;

//create new box to represent from val onwards
CBoundingBox rBox;
rBox.extend(*this);
rBox.m_minPoint[dim] = val;

return std::make_pair(lBox, rBox);
}

bool CBoundingBox::overlaps(const CBoundingBox& box) const
{
// --- PUT YOUR CODE HERE ---
return false;
//check for overlap in each axis, return false is an axis has no overlap
for (int i = 0; i < 3; i++) {
if (!((m_maxPoint[i] > box.getMaxPoint()[i] and box.getMaxPoint()[i] > m_minPoint[i]) or
(box.getMaxPoint()[i] > m_maxPoint[i] and m_maxPoint[i] > box.getMinPoint()[i]))) {
return false;
}
}
return true;
}

void CBoundingBox::clip(const Ray& ray, double& t0, double& t1) const
{
// --- PUT YOUR CODE HERE ---
for (int i = 0; i < 3; i++) {
if (ray.dir.val[i] != 0) {
if (ray.dir.val[i] > 0) {
t0 = MAX((m_minPoint.val[i] - ray.org.val[i]) / ray.dir.val[i], t0);
t1 = MIN((m_maxPoint.val[i] - ray.org.val[i]) / ray.dir.val[i], t1);
}
else {
t0 = MAX((m_maxPoint.val[i] - ray.org.val[i]) / ray.dir.val[i], t0);
t1 = MIN((m_minPoint.val[i] - ray.org.val[i]) / ray.dir.val[i], t1);
}
if (t0 > t1)
return;
}
}
}

2 changes: 1 addition & 1 deletion src/LightOmni.h
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#pragma once

#include "ILight.h"
#include "Ray.h"
#include "ray.h"

/**
* @brief Point light source class
Expand Down
3 changes: 2 additions & 1 deletion src/PrimPlane.h
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,8 @@ class CPrimPlane : public IPrim
virtual CBoundingBox getBoundingBox(void) const override
{
CBoundingBox bounds;
// --- PUT YOUR CODE HERE ---
bounds.extend(Vec3f::all(Infty));
bounds.extend(Vec3f::all(-Infty));
return bounds;
}

Expand Down
3 changes: 2 additions & 1 deletion src/PrimSphere.h
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,8 @@ class CPrimSphere : public IPrim
virtual CBoundingBox getBoundingBox(void) const override
{
CBoundingBox res;
// --- PUT YOUR CODE HERE ---
res.extend(m_origin + Vec3f::all(m_radius));
res.extend(m_origin - Vec3f::all(m_radius));
return res;
}

Expand Down
4 changes: 3 additions & 1 deletion src/PrimTriangle.h
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,9 @@ class CPrimTriangle : public IPrim
virtual CBoundingBox getBoundingBox(void) const override
{
CBoundingBox res;
// --- PUT YOUR CODE HERE ---
res.extend(m_a);
res.extend(m_b);
res.extend(m_c);
return res;
}

Expand Down
4 changes: 3 additions & 1 deletion src/Scene.h
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,9 @@ class CScene
*/
void add(const CSolid& solid)
{
// --- PUT YOUR CODE HERE ---
for (const auto prim : solid.getPrims()) {
m_vpPrims.push_back(prim);
}
}
/**
* @brief (Re-) Build the BSP tree for the current geometry present in scene
Expand Down
17 changes: 10 additions & 7 deletions src/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ Mat RenderFrame(void)
#ifdef WIN32
const std::string dataPath = "../data/";
#else
const std::string dataPath = "../../data/";
const std::string dataPath = "../data/";//"../../data/";
#endif
CSolid solid(pShader, dataPath + "Torus Knot.obj");
scene.add(solid);
Expand All @@ -48,13 +48,16 @@ Mat RenderFrame(void)
scene.add(std::make_shared<CLightOmni>(pointLightIntensity, lightPosition3));

Mat img(resolution, CV_32FC3); // image array
Ray ray; // primary ray

for (int y = 0; y < img.rows; y++)
for (int x = 0; x < img.cols; x++) {
scene.getActiveCamera()->InitRay(ray, x, y); // initialize ray
img.at<Vec3f>(y, x) = scene.RayTrace(ray);
parallel_for_(Range(0, img.rows), [&](const Range& range) {
for (int y = range.start; y < range.end; y++) {
Ray ray; //declare here so each thread has its own
for (int x = 0; x < img.cols; x++) {
scene.getActiveCamera()->InitRay(ray, x, y); // initialize ray
img.at<Vec3f>(y, x) = scene.RayTrace(ray);
}
}
});

img.convertTo(img, CV_8UC3, 255);
return img;
Expand All @@ -67,6 +70,6 @@ int main(int argc, char* argv[])
DirectGraphicalModels::Timer::stop();
imshow("Image", img);
waitKey();
imwrite("D:/renders/torus knot.jpg", img);
imwrite("./torus knot.jpg", img);
return 0;
}