1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
|
#include <iostream>
struct CVec3 {
float x, y, z;
CVec3 operator+(const CVec3& other) const {
return { x + other.x, y + other.y, z + other.z };
}
CVec3 operator-(const CVec3& other) const {
return { x - other.x, y - other.y, z - other.z };
}
CVec3 operator*(float scalar) const {
return { x * scalar, y * scalar, z * scalar };
}
};
int inline GetIntersection(float fDst1, float fDst2, CVec3 P1, CVec3 P2, CVec3& Hit) {
if ((fDst1 * fDst2) >= 0.0f) return 0;
if (fDst1 == fDst2) return 0;
Hit = P1 + (P2 - P1) * (-fDst1 / (fDst2 - fDst1));
return 1;
}
int inline InBox(CVec3 Hit, CVec3 B1, CVec3 B2, const int Axis) {
if (Axis == 1 && Hit.z > B1.z && Hit.z < B2.z && Hit.y > B1.y && Hit.y < B2.y) return 1;
if (Axis == 2 && Hit.z > B1.z && Hit.z < B2.z && Hit.x > B1.x && Hit.x < B2.x) return 1;
if (Axis == 3 && Hit.x > B1.x && Hit.x < B2.x && Hit.y > B1.y && Hit.y < B2.y) return 1;
return 0;
}
int CheckLineBox(CVec3 B1, CVec3 B2, CVec3 L1, CVec3 L2, CVec3& Hit) {
if (L2.x < B1.x && L1.x < B1.x) return false;
if (L2.x > B2.x && L1.x > B2.x) return false;
if (L2.y < B1.y && L1.y < B1.y) return false;
if (L2.y > B2.y && L1.y > B2.y) return false;
if (L2.z < B1.z && L1.z < B1.z) return false;
if (L2.z > B2.z && L1.z > B2.z) return false;
if (L1.x > B1.x && L1.x < B2.x &&
L1.y > B1.y && L1.y < B2.y &&
L1.z > B1.z && L1.z < B2.z) {
Hit = L1;
return true;
}
if ((GetIntersection(L1.x - B1.x, L2.x - B1.x, L1, L2, Hit) && InBox(Hit, B1, B2, 1))
|| (GetIntersection(L1.y - B1.y, L2.y - B1.y, L1, L2, Hit) && InBox(Hit, B1, B2, 2))
|| (GetIntersection(L1.z - B1.z, L2.z - B1.z, L1, L2, Hit) && InBox(Hit, B1, B2, 3))
|| (GetIntersection(L1.x - B2.x, L2.x - B2.x, L1, L2, Hit) && InBox(Hit, B1, B2, 1))
|| (GetIntersection(L1.y - B2.y, L2.y - B2.y, L1, L2, Hit) && InBox(Hit, B1, B2, 2))
|| (GetIntersection(L1.z - B2.z, L2.z - B2.z, L1, L2, Hit) && InBox(Hit, B1, B2, 3)))
return true;
return false;
}
int main() {
CVec3 B1{ 0.0f, 0.0f, 0.0f };
CVec3 B2{ 1.0f, 1.0f, 1.0f };
CVec3 L1{ -1.0f, -1.0f, -1.0f };
CVec3 L2{ 1.0f, 1.0f, 1.0f };
CVec3 Hit;
int result = CheckLineBox(B1, B2, L1, L2, Hit);
if (result) {
std::cout << "Line intersects with the box. Intersection point: (" << Hit.x << ", " << Hit.y << ", " << Hit.z << ")\n";
}
else {
std::cout << "Line does not intersect with the box.\n";
}
return 0;
}
|