tofu

Making something with OpenGL in Go
Log | Files | Refs

math.go (805B)


      1 package tofu
      2 
      3 import "math"
      4 
      5 type Vec3 [3]float32
      6 
      7 // column major
      8 type Mat4 [16]float32
      9 
     10 // Mul multiplies m by n and returns newly allocated result.
     11 func (m Mat4) Mul(n Mat4) Mat4 {
     12 	var dst Mat4
     13 	for i := 0; i < 4; i++ {
     14 		for j := 0; j < 4; j++ {
     15 			for k := 0; k < 4; k++ {
     16 				dst[i+4*j] += m[i+4*k] * n[k+4*j]
     17 			}
     18 		}
     19 	}
     20 	return dst
     21 }
     22 
     23 func Translate(v Vec3) Mat4 {
     24 	var n Mat4
     25 	n[0] = 1
     26 	n[5] = 1
     27 	n[10] = 1
     28 	n[12] = v[0]
     29 	n[13] = v[1]
     30 	n[14] = v[2]
     31 	n[15] = 1
     32 	return n
     33 }
     34 
     35 func Rotate(rad float32, axis Vec3) Mat4 {
     36 	x, y, z := axis[0], axis[1], axis[2]
     37 	c := float32(math.Cos(float64(rad)))
     38 	d := 1 - c
     39 	s := float32(math.Sin(float64(rad)))
     40 	return Mat4{c + x*x*d, y*x*d + z*s, z*x*d - y*s, 0,
     41 		x*y*d - z*s, c + y*y*d, z*y*d + x*s, 0,
     42 		x*z*d + y*s, y*z*d - x*s, c + z*z*d, 0,
     43 		0, 0, 0, 1}
     44 }