davideberly / GeometricTools

A collection of source code for computing in the fields of mathematics, geometry, graphics, image analysis and physics.
Boost Software License 1.0
1.08k stars 202 forks source link

Fix calculation of closest point to origin on 2D segment in canonical box/cylinder intersection test. #44

Closed tvf closed 1 year ago

tvf commented 1 year ago

Hi David, I noticed incorrect results when testing for box/cylinder intersection. I found a sign error in the code computing the squared distance of a 2D segment to the origin.

Here is a test program that gives an incorrect result before this fix and a correct result afterwards.

#include <Mathematics/IntrCanonicalBox3Cylinder3.h>

#include <iostream>

int main(int argc, char **argv) {

    gte::Line3<float> axis(
        gte::Vector3<float>({ -2.788151f, -2.091865f, 0.8015f }),
        gte::Vector3<float>({ 0.10444f, 0.328969f, 0.938548f })
    );

    gte::Cylinder3<float> cyl(axis, 0.39f, 2.1f);
    gte::CanonicalBox3<float> box(gte::Vector3<float>({ 2.5f, 2.5f, 1.35f }));

    gte::TIQuery<float, gte::CanonicalBox3<float>, gte::Cylinder3<float>> intersect_query;

    // Note that
    // * the origin of the cylinder lies less than 0.3 units from the -X side of the box
    // * the height of the cylinder exceeds the diameter of the cylinder, so the cylinder
    //   contains the sphere having the cylinder's diameter centred at the cylinder origin
    // so the cylinder and the box certainly collide.

    if (intersect_query(box, cyl).intersect) { std::cout << "PASS\n"; } else { std::cout << "FAIL\n"; }
}
davideberly commented 1 year ago

Hello Tom. Thank you for taking the time to let me know about this bug!