comparison OrthancStone/Sources/Toolbox/GeometryToolbox.cpp @ 2156:340bde744884

added DebugDrawing2D and GeometryToolbox::IntersectLineAndSegment()
author Sebastien Jodogne <s.jodogne@gmail.com>
date Fri, 27 Sep 2024 22:14:36 +0200
parents 16c01cc201e7
children
comparison
equal deleted inserted replaced
2155:71d6ad7036b7 2156:340bde744884
563 else 563 else
564 { 564 {
565 return false; 565 return false;
566 } 566 }
567 } 567 }
568
569
570 static bool SolveLineIntersectionSystem(double& x,
571 double& y,
572 double& s,
573 double& t,
574 double x1, double y1,
575 double x2, double y2,
576 double x3, double y3,
577 double x4, double y4)
578 {
579 // https://en.wikipedia.org/wiki/Intersection_(geometry)#Two_line_segments
580 const double a1 = x2 - x1;
581 const double b1 = -x4 + x3;
582 const double c1 = x3 - x1;
583 const double a2 = y2 - y1;
584 const double b2 = -y4 + y3;
585 const double c2 = y3 - y1;
586
587 const double denominator = a1 * b2 - a2 * b1;
588 if (LinearAlgebra::IsCloseToZero(denominator))
589 {
590 return false;
591 }
592 else
593 {
594 // This is Cramer's rule
595 s = (c1 * b2 - c2 * b1) / denominator;
596 t = (a1 * c2 - a2 * c1) / denominator;
597 x = x1 + s * (x2 - x1);
598 y = y1 + s * (y2 - y1);
599 return true;
600 }
601 }
602
603
604 bool IntersectTwoLines(double& x,
605 double& y,
606 double ax1,
607 double ay1,
608 double ax2,
609 double ay2,
610 double bx1,
611 double by1,
612 double bx2,
613 double by2)
614 {
615 double s, t;
616 return SolveLineIntersectionSystem(x, y, s, t, ax1, ay1, ax2, ay2, bx1, by1, bx2, by2);
617 }
618
619
620 bool IntersectLineAndSegment(double& x,
621 double& y,
622 double lineX1,
623 double lineY1,
624 double lineX2,
625 double lineY2,
626 double segmentX1,
627 double segmentY1,
628 double segmentX2,
629 double segmentY2)
630 {
631 double s, t;
632 if (SolveLineIntersectionSystem(x, y, s, t, lineX1, lineY1, lineX2, lineY2, segmentX1, segmentY1, segmentX2, segmentY2))
633 {
634 return (t >= 0 && t <= 1);
635 }
636 else
637 {
638 return false;
639 }
640 }
568 } 641 }
569 } 642 }