Matrix transformation using go-gl

Look! there's a flower!·2024년 8월 28일

Transform matrix

We can use mgl32 or mgl64 of go-gl/mathgl to calculate matrix transformation.
(refer to https://github.com/go-gl/mathgl)

  1. install library mgl32 or mgl64
    $ go get github.com/go-gl/mathgl/mgl32 #float
    $ go get github.com/go-gl/mathgl/mgl64 #double

  2. sample code

import (
    "fmt"
    "github.com/go-gl/mathgl/mgl32"
)

func main() {
    matrix := mgl32.Ident4()

    matrix = matrix.Mul4( mgl32.Translate3D(1, 2, 3))
    matrix = matrix.Mul4( mgl32.HomogRotate3D( mgl32.DegToRad(45), mgl32.Vec3{0,1,0}))
    matrix = matrix.Mul4( mgl32.Scale3D(2,2,2))

    point := mgl32.Vec4{1,1,1,1}
    pt := matrix.Mul4x1(point)

    fmt.Printf("Transformed: %v\n", pt)

    point3 := mgl32.Vec4{1,1,1,0}
    pt3 := matrix.Mul4x1(point3)
    //point3 := mgl32.Vec3{1,1,1}
    // pt3 := matrix.Mul4x1( point3.Vec4(1.0)).Vec3()
    fmt.Printf("Transformed2: %v\n", pt3)
}
  1. Point and directional vector transformation
    Vec4's 4th element represent point or directional vector.
    For example at the above code, Vec4{1,1,1,1} is directional vector and Vec4{1,1,1,0} is point.
    All operations in the transformation matrix but translations are applied to directional vector while all operations in the matrix are applied to point.

  2. Vector cross product and dot product also are supported.

v1 := mgl32.Vec3{1, 0, 0}
v2 := mgl32.Vec3{0, 1, 0}
cross := v1.Cross(v2)
dot := v1.Dot(v2)

Operations

Vec3 := mgl32.Vec3{0,1,0}
point3 := Vec4 := mgl32.Vec4{1,1,1,0}
matrix := Mat4 := mgl32.Ident4()
Mat4 := mgl32.Translate3D(1, 2, 3)
Mat4 := mgl32.Scale3D(1,2,3)
Mat4 := mgl32.DegToRad(45)
Mat4 := mgl32.HomogRotate3D(Degree, mgl32.Vec3)
Mat4 := matrix.Mul4( mgl32.Translate3D())
Mat4 := matrix.Mul4( mgl32.HomogRotate3D())
Mat4 := matrix.Mul4( mgl32.Scale3D())
Vec4 := matrix.Mul4x1(point3)
Vec4 := point3.Vec4(1)
Vec3 := Vec4.Vec3()

vec3 := Vec3.Sub( Vec3 )
vec3 := Vec3.Normalize()
vec3 := Vec3.Add( Vec3 )
vec3 := Vec3.Mul( Vec3 )

vec3 := Vec3.Cross(Vec3)
double := Vec3.Dot(Vec3)

Inverse Transform

inverseMatrix, ok := matrix.Inv()
point3D := mgl32.Vec3{x,y,z}
rePoint := inverseMatrix.Mul4x1( point3D.Vec4(1)).Vec3()

Finding a point on a plane perpendicular from a given vector

given: Points O, P, N, Q where O and P are on the same plane. ON is a normal vector to the plane.
goal: finding point M on the plane which has O and P such that MQ is perpendicular to the plane.

import (
    "fmt"
    "github.com/go-gl/mathgl/mgl32"
)

func findPointM(O, P, N, Q mgl32.Vec3) mgl32.Vec3 {
    // Calculate the normal vector (already given as ON)
    n := N.Sub(O).Normalize()

    // Calculate OQ
    OQ := Q.Sub(O)

    // Project OQ onto n
    proj := n.Mul(OQ.Dot(n))

    // Calculate OM
    OM := OQ.Sub(proj)

    // Calculate M
    M := O.Add(OM)

    return M
}
profile
Why don't you take a look around for a moment?

0개의 댓글