gg/mx/triangle.go

116 lines
2 KiB
Go
Raw Normal View History

2024-05-28 11:24:12 +03:00
package mx
import (
"math"
//"github.com/hajimehoshi/ebiten/v2"
)
type Triangle [3]Vector
// Returns the area of the triangle.
func (t Triangle) Area() Float {
x1 := t[0].X
y1 := t[0].Y
x2 := t[1].X
y2 := t[1].Y
x3 := t[2].X
y3 := t[2].Y
return math.Abs(
( x1*(y2-y3) +
x2*(y3-y1) +
x3*(y1-y2))/2 )
}
// Return squares of lengths of sides of the triangle.
func (t Triangle) SideLengthSquares() ([3]Float) {
l1 := Line{t[0], t[1]}.LenSqr()
l2 := Line{t[1], t[2]}.LenSqr()
l3 := Line{t[2], t[0]}.LenSqr()
return [3]Float{l1, l2, l3}
}
// Check whether the point is in the triangle.
func (t Triangle) ContainsPoint(p Vector) bool {
d1 := Triangle{p, t[0], t[1]}.Sgn()
d2 := Triangle{p, t[1], t[2]}.Sgn()
d3 := Triangle{p, t[2], t[0]}.Sgn()
neg := (d1 < 0) || (d2 < 0) || (d3 < 0)
pos := (d1 > 0) || (d2 > 0) || (d3 > 0)
return !(neg && pos)
}
func (t Triangle) GetContainedPoints(pts Vectors) Vectors {
ret := make(Vectors, 0, len(pts))
for i := range pts {
if t.ContainsPoint(pts[i]) {
ret = append(ret, pts[i])
}
}
return ret
}
func (t Triangle) Sgn() Float {
return (t[0].X - t[2].X) * (t[1].Y - t[2].Y) -
(t[1].X - t[2].X) * (t[0].Y - t[2].Y)
}
func (t Triangle) GetEdges() Lines {
return Lines{
Line{t[0], t[1]},
Line{t[1], t[2]},
Line{t[2], t[0]},
}
}
func (t Triangle) GetVertices() Vectors {
return Vectors{
t[0], t[1], t[2],
}
}
type Triangles []Triangle
2024-06-01 16:07:28 +03:00
func (ts Triangles) ContainsPoint(pt Vector) bool {
for _, t := range ts {
if t.ContainsPoint(pt) {
return true
}
}
return false
}
2024-05-28 11:24:12 +03:00
func (ts Triangles) GetContainedPoints(
pts Vectors,
) Vectors {
ret := Vectors{}
for _, t := range ts {
ps := t.GetContainedPoints(pts)
ret = append(ret, ps...)
}
return ret
}
func (ts Triangles) GetVertices() Vectors {
ret := make(Vectors, 0, len(ts)*3)
for _, t := range ts {
ret = append(ret, t.GetVertices()...)
}
return ret
}
func (ts Triangles) GetEdges() Lines {
ret := make(Lines, 0, len(ts)*3)
for _, t := range ts {
ret = append(ret, t.GetEdges()...)
}
return ret
}