matrix.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // Copyright 2016 The G3N Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Package collision implements collision related algorithms and data structures.
  5. package collision
  6. // Matrix is a triangular collision matrix indicating which pairs of bodies are colliding.
  7. type Matrix struct {
  8. col [][]bool
  9. }
  10. // NewMatrix creates and returns a pointer to a new collision Matrix.
  11. func NewMatrix() *Matrix {
  12. m := new(Matrix)
  13. m.col = make([][]bool, 0)
  14. return m
  15. }
  16. // Set sets whether i and j are colliding.
  17. func (m *Matrix) Set(i, j int, val bool) {
  18. var s, l int
  19. if i < j {
  20. s = i
  21. l = j
  22. } else {
  23. s = j
  24. l = i
  25. }
  26. diff := s + 1 - len(m.col)
  27. if diff > 0 {
  28. for i := 0; i < diff; i++ {
  29. m.col = append(m.col, make([]bool,0))
  30. }
  31. }
  32. for idx := range m.col {
  33. diff = l + 1 - len(m.col[idx]) - idx
  34. if diff > 0 {
  35. for i := 0; i < diff; i++ {
  36. m.col[idx] = append(m.col[idx], false)
  37. }
  38. }
  39. }
  40. m.col[s][l-s] = val
  41. }
  42. // Get returns whether i and j are colliding.
  43. func (m *Matrix) Get(i, j int) bool {
  44. var s, l int
  45. if i < j {
  46. s = i
  47. l = j
  48. } else {
  49. s = j
  50. l = i
  51. }
  52. return m.col[s][l-s]
  53. }