Skip to content

Commit 6983eca

Browse files
authored
Merge pull request #8 from ThalesGroup/master
Update distanceTo method for GSegment
2 parents 5e18270 + cfba7d5 commit 6983eca

File tree

3 files changed

+31
-6
lines changed

3 files changed

+31
-6
lines changed

src/.properties

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
{
2-
#format : #tonel
3-
}
2+
#format : #tonel,
3+
#version : #'1.0'
4+
}

src/Geometry-Tests/GSegmentTest.class.st

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,10 @@ GSegmentTest >> testDistanceTo [
4444
self assert: ((GSegment with: -2 , 4 with: 2 , 4) distanceTo: -2 , 4) equals: 0.
4545
self assert: ((GSegment with: -2 , 4 with: 2 , 4) distanceTo: 2 , 4) equals: 0.
4646
self assert: ((GSegment with: 477 / 11 , (149 / 2) with: -56.73661227723915 , 143.3189209406019) distanceTo: 36819 / 1022 , (82249 / 1022)) =~ 0.7697676365059569.
47-
self assert: ((GSegment with: 838 / 41 , (4811 / 82) with: 57583 / 914 , (56095 / 914)) distanceTo: 57.998905906959145 , 61.11074842728413) =~ (2 * 0.02757564283371476)
47+
self assert: ((GSegment with: 838 / 41 , (4811 / 82) with: 57583 / 914 , (56095 / 914)) distanceTo: 57.998905906959145 , 61.11074842728413) =~ (2 * 0.02757564283371476).
48+
49+
self assert: ((GSegment with: -2 , 4 with: 2 , 4) distanceTo: 3 , 4) equals: 1.
50+
self assert: ((GSegment with: -2 , 4 with: 2 , 4) distanceTo: -2 , 5) equals: 1.
4851
]
4952

5053
{ #category : #tests }

src/Geometry/GSegment.class.st

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -68,10 +68,31 @@ GSegment >> asGLine [
6868

6969
{ #category : #properties }
7070
GSegment >> distanceTo: aGPoint [
71-
self flag: #todo. "«The distance between segments and rays may not be the same as the distance between their extended lines. » http://geomalgorithms.com/a07-_distance.html
71+
72+
| vectSegment vectPoint t distance closestPoint|
73+
74+
"See:https://paulbourke.net/geometry/pointlineplane/
75+
and: https://gist.github.com/mattdesl/47412d930dcd8cd765c871a65532ffac"
76+
77+
distance := SmallInteger maxVal.
78+
79+
"Vector from v1 to v2"
80+
vectSegment := (v2 asPoint) - (v1 asPoint).
81+
vectSegment isZero ifTrue:[ ^distance ].
82+
"Vector from v1 to P"
83+
vectPoint := (aGPoint asPoint) - (v1 asPoint).
84+
t := (vectSegment dotProduct: vectPoint) / (vectSegment dotProduct: vectSegment).
85+
"Clamp t to [0, 1] to restrict to the segment"
86+
t := (t max: 0) min: 1.
87+
88+
"Closest point on segment to P"
89+
closestPoint := (v1 asPoint) + (vectSegment * t).
90+
distance := (aGPoint asPoint) distanceTo: closestPoint.
91+
92+
^distance
93+
94+
7295

73-
So apparently this implementation is wrong."
74-
^ self asGLine distanceTo: aGPoint
7596
]
7697

7798
{ #category : #comparing }

0 commit comments

Comments
 (0)