From 68e8bf81531349c73f9b3309ccd8024695c1b77c Mon Sep 17 00:00:00 2001 From: karl Date: Sat, 16 Jan 2021 19:33:48 +0100 Subject: [PATCH] Add optimizations for working intersect_ray_recurse approach It's performant and functional now, yay --- Util/kdtree.h | 34 +++++++++++++++------------------- 1 file changed, 15 insertions(+), 19 deletions(-) diff --git a/Util/kdtree.h b/Util/kdtree.h index b754423..b60c5d2 100644 --- a/Util/kdtree.h +++ b/Util/kdtree.h @@ -23,9 +23,9 @@ class KDTree { const Triangle *intersect_ray(const Ray ray, Vector &result) { auto start = std::chrono::high_resolution_clock::now(); - float nearest = 1000.0; + float nearest = 1000.0; // Initial max distance const Triangle *nearest_triangle = nullptr; - intersect_ray_recurse(nearest_triangle, result, ray, root, 1000.0, 0, nearest); + intersect_ray_recurse(nearest_triangle, result, ray, root, 0, nearest); auto end = std::chrono::high_resolution_clock::now(); @@ -108,7 +108,7 @@ class KDTree { } void intersect_ray_recurse(const Triangle *&nearest_triangle, Vector &result, Ray ray, - Node *node, float max_distance, int depth, float &nearest) { + Node *node, int depth, float &nearest) { // Exit condition: There was no collision if (node == nullptr) { return; } @@ -131,24 +131,20 @@ class KDTree { Node *far = near == node->right ? node->left : node->right; if (ray.direction[node->axis] == 0.0) { - intersect_ray_recurse(nearest_triangle, result, ray, near, max_distance, depth + 1, - nearest); + intersect_ray_recurse(nearest_triangle, result, ray, near, depth + 1, nearest); } else { - /* float t = - (node->point->pos[node->axis] - ray.origin[node->axis]) / - ray.direction[node->axis]; + float t = + (node->point->pos[node->axis] - ray.origin[node->axis]) / ray.direction[node->axis]; - if (t >= 0.0 && t < max_distance) { - intersect_ray_recurse(nearest_triangle, result, ray, near, t, depth + 1, - nearest); intersect_ray_recurse(nearest_triangle, result, Ray(ray.origin + - ray.direction * t, ray.direction), far, max_distance - t, depth + 1, nearest); } else - { intersect_ray_recurse(nearest_triangle, result, ray, near, max_distance, depth + 1, - nearest); - } */ - intersect_ray_recurse(nearest_triangle, result, ray, near, max_distance, depth + 1, - nearest); - intersect_ray_recurse(nearest_triangle, result, ray, far, max_distance, depth + 1, - nearest); + // Check this side for intersections up to the distance of the currently best + // intersection + intersect_ray_recurse(nearest_triangle, result, ray, near, depth + 1, nearest); + + // If the far side is closer than the distance to the best current intersection, check + // that side too + if (t < nearest) { + intersect_ray_recurse(nearest_triangle, result, ray, far, depth + 1, nearest); + } } }