skeleton.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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 graphic
  5. import (
  6. "github.com/g3n/engine/core"
  7. "github.com/g3n/engine/math32"
  8. )
  9. // Skeleton contains armature information.
  10. type Skeleton struct {
  11. inverseBindMatrices []math32.Matrix4
  12. boneMatrices []math32.Matrix4
  13. bones []*core.Node
  14. }
  15. // NewSkeleton creates and returns a pointer to a new Skeleton.
  16. func NewSkeleton() *Skeleton {
  17. sk := new(Skeleton)
  18. sk.boneMatrices = make([]math32.Matrix4, 0)
  19. sk.bones = make([]*core.Node, 0)
  20. return sk
  21. }
  22. // AddBone adds a bone to the skeleton along with an optional inverseBindMatrix.
  23. func (sk *Skeleton) AddBone(node *core.Node, inverseBindMatrix *math32.Matrix4) {
  24. // Useful for debugging:
  25. //node.Add(NewAxisHelper(0.2))
  26. sk.bones = append(sk.bones, node)
  27. sk.boneMatrices = append(sk.boneMatrices, *math32.NewMatrix4())
  28. if inverseBindMatrix == nil {
  29. inverseBindMatrix = math32.NewMatrix4() // Identity matrix
  30. }
  31. sk.inverseBindMatrices = append(sk.inverseBindMatrices, *inverseBindMatrix)
  32. }
  33. // Bones returns the list of bones in the skeleton.
  34. func (sk *Skeleton) Bones() []*core.Node {
  35. return sk.bones
  36. }
  37. // BoneMatrices calculates and returns the bone world matrices to be sent to the shader.
  38. func (sk *Skeleton) BoneMatrices(invMat *math32.Matrix4) []math32.Matrix4 {
  39. // Update bone matrices based on inverseBindMatrices and the provided invMat
  40. for i := range sk.bones {
  41. bMat := sk.bones[i].MatrixWorld()
  42. bMat.MultiplyMatrices(&bMat, &sk.inverseBindMatrices[i])
  43. sk.boneMatrices[i].MultiplyMatrices(invMat, &bMat)
  44. }
  45. return sk.boneMatrices
  46. }