f32.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. // Copyright 2014 The Go 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. //go:generate go run gen.go -output table.go
  5. // Package f32 implements some linear algebra and GL helpers for float32s.
  6. //
  7. // Types defined in this package have methods implementing common
  8. // mathematical operations. The common form for these functions is
  9. //
  10. // func (dst *T) Op(lhs, rhs *T)
  11. //
  12. // which reads in traditional mathematical notation as
  13. //
  14. // dst = lhs op rhs.
  15. //
  16. // It is safe to use the destination address as the left-hand side,
  17. // that is, dst *= rhs is dst.Mul(dst, rhs).
  18. //
  19. // # WARNING
  20. //
  21. // The interface to this package is not stable. It will change considerably.
  22. // Only use functions that provide package documentation. Semantics are
  23. // non-obvious. Be prepared for the package name to change.
  24. package f32 // import "golang.org/x/mobile/exp/f32"
  25. import (
  26. "encoding/binary"
  27. "fmt"
  28. "math"
  29. )
  30. type Radian float32
  31. func Cos(x float32) float32 {
  32. const n = sinTableLen
  33. i := uint32(int32(x * (n / math.Pi)))
  34. i += n / 2
  35. i &= 2*n - 1
  36. if i >= n {
  37. return -sinTable[i&(n-1)]
  38. }
  39. return sinTable[i&(n-1)]
  40. }
  41. func Sin(x float32) float32 {
  42. const n = sinTableLen
  43. i := uint32(int32(x * (n / math.Pi)))
  44. i &= 2*n - 1
  45. if i >= n {
  46. return -sinTable[i&(n-1)]
  47. }
  48. return sinTable[i&(n-1)]
  49. }
  50. func Sqrt(x float32) float32 {
  51. return float32(math.Sqrt(float64(x))) // TODO(crawshaw): implement
  52. }
  53. func Tan(x float32) float32 {
  54. return float32(math.Tan(float64(x))) // TODO(crawshaw): fast version
  55. }
  56. // Bytes returns the byte representation of float32 values in the given byte
  57. // order. byteOrder must be either binary.BigEndian or binary.LittleEndian.
  58. func Bytes(byteOrder binary.ByteOrder, values ...float32) []byte {
  59. le := false
  60. switch byteOrder {
  61. case binary.BigEndian:
  62. case binary.LittleEndian:
  63. le = true
  64. default:
  65. panic(fmt.Sprintf("invalid byte order %v", byteOrder))
  66. }
  67. b := make([]byte, 4*len(values))
  68. for i, v := range values {
  69. u := math.Float32bits(v)
  70. if le {
  71. b[4*i+0] = byte(u >> 0)
  72. b[4*i+1] = byte(u >> 8)
  73. b[4*i+2] = byte(u >> 16)
  74. b[4*i+3] = byte(u >> 24)
  75. } else {
  76. b[4*i+0] = byte(u >> 24)
  77. b[4*i+1] = byte(u >> 16)
  78. b[4*i+2] = byte(u >> 8)
  79. b[4*i+3] = byte(u >> 0)
  80. }
  81. }
  82. return b
  83. }