Борис обнови решението на 21.11.2018 16:37 (преди 9 месеца)
+package main
+
+import "fmt"
+import "github.com/fmi/go-homework/geom"
+
+type Sphere struct {
+ Origin geom.Vector
+ R float64
+}
+
+func (s Sphere) Intersect(ray geom.Ray) bool {
+ H := geom.Sub(ray.Origin, s.Origin)
+ A := ray.Direction.X*ray.Direction.X + ray.Direction.Y*ray.Direction.Y + ray.Direction.Z*ray.Direction.Z
+ B := 2 * geom.Dot(ray.Direction, H)
+ HLenghtSqr := H.X*H.X + H.Y*H.Y + H.Z*H.Z
+ C := HLenghtSqr - s.R*s.R
+
+ disc := B*B - 4*A*C
+ if disc <= 0 {
+ return false
+ } else {
+ return true
+ }
+}
+
+func NewSphere(origin geom.Vector, r float64) Sphere {
+ return Sphere{
+ Origin: origin,
+ R: r,
+ }
+}
+
+type Triangle struct {
+ A, B, C geom.Vector
+}
+
+func NewTriangle(a, b, c geom.Vector) Triangle {
+ return Triangle{
+ A: a,
+ B: b,
+ C: c,
+ }
+}
+func det(a, b, c geom.Vector) float64 {
+ d := geom.Cross(a, b)
+ return geom.Dot(d, c)
+}
+
+func (t Triangle) Intersect(ray geom.Ray) bool {
+ AB := geom.Sub(t.B, t.A)
+ AC := geom.Sub(t.C, t.A)
+ Nil := geom.NewVector(0, 0, 0)
+ D := geom.Sub(Nil, ray.Direction)
+
+ DiscrC := det(AB, AC, D)
+
+ if DiscrC == 0 {
+ return false
+ }
+
+ revDiscr := 1 / DiscrC
+
+ H := geom.Sub(ray.Origin, t.A)
+
+ Gamma := det(AB, AC, H) * revDiscr
+ if Gamma == 0 {
+ return false
+ }
+
+ lambdaTwo := det(H, AC, D) * revDiscr
+ if lambdaTwo < 0 || lambdaTwo > 1 {
+ return false
+ }
+ lambdaThree := det(AB, H, D) * revDiscr
+
+ if lambdaThree < 0 || lambdaThree > 1 {
+ return false
+ }
+
+ lambdaOne := 1 - lambdaTwo - lambdaThree
+ if lambdaOne < 0 {
+ return false
+ }
+
+ return true
+
+}
+
+type Quad struct {
+ A, B, C, D geom.Vector
+}
+
+func NewQuad(a, b, c, d geom.Vector) Quad {
+ return Quad{
+ A: a,
+ B: b,
+ C: c,
+ D: d,
+ }
+}
+
+func (q Quad) Intersect(ray geom.Ray) bool {
+
+ trOne := NewTriangle(q.A, q.B, q.D)
+ trTwo := NewTriangle(q.B, q.C, q.D)
+ firstBoolean := trOne.Intersect(ray)
+ secondBoolean := trTwo.Intersect(ray)
+ if firstBoolean && secondBoolean {
+ return true
+ }
+ return false
+}
+
+func main() {
+ fmt.Println("Hello, playground")
+ a, b, c := geom.NewVector(-1, -1, 0), geom.NewVector(1, -1, 0), geom.NewVector(0, 1, 0)
+ tr := NewTriangle(a, b, c)
+
+ ray := geom.NewRay(geom.NewVector(0, 0, -1), geom.NewVector(0, 0, 1))
+
+ if tr.Intersect(ray) {
+ fmt.Println("ray intersects tr")
+ }
+
+}