animation.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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 collada
  5. import (
  6. "fmt"
  7. "github.com/g3n/engine/core"
  8. "github.com/g3n/engine/math32"
  9. "strings"
  10. )
  11. // AnimationTarget contains all animation channels for an specific target node
  12. type AnimationTarget struct {
  13. target core.INode
  14. matrix math32.Matrix4 // original node transformation matrix
  15. start float32 // initial input offset value
  16. last float32 // last input value
  17. minInput float32 // minimum input value for all channels
  18. maxInput float32 // maximum input value for all channels
  19. loop bool // animation loop flag
  20. rot math32.Vector3 // rotation in XYZ Euler angles
  21. channels []*ChannelInstance
  22. }
  23. // A ChannelInstance associates an animation parameter channel to an interpolation sampler
  24. type ChannelInstance struct {
  25. sampler *SamplerInstance
  26. action ActionFunc
  27. }
  28. // SamplerInstance specifies the input key frames, output values for these key frames
  29. // and interpolation information. It can be shared by more than one animation
  30. type SamplerInstance struct {
  31. Input []float32 // Input keys (usually time)
  32. Output []float32 // Outputs values for the keys
  33. Interp []string // Names of interpolation functions for each key frame
  34. InTangent []float32 // Origin tangents for Bezier interpolation
  35. OutTangent []float32 // End tangents for Bezier interpolation
  36. }
  37. // ActionFunc is the type for all functions that execute an specific parameter animation
  38. type ActionFunc func(at *AnimationTarget, v float32)
  39. // Reset resets the animation from the beginning
  40. func (at *AnimationTarget) Reset() {
  41. at.last = at.start
  42. at.target.GetNode().SetMatrix(&at.matrix)
  43. }
  44. // SetLoop sets the state of the animation loop flag
  45. func (at *AnimationTarget) SetLoop(loop bool) {
  46. at.loop = loop
  47. }
  48. func (at *AnimationTarget) SetStart(v float32) {
  49. at.start = v
  50. }
  51. // Update interpolates the specified input value for each animation target channel
  52. // and executes its corresponding action function. Returns true if the input value
  53. // is inside the key frames ranges or false otherwise.
  54. func (at *AnimationTarget) Update(delta float32) bool {
  55. // Checks if input is less than minimum
  56. at.last = at.last + delta
  57. if at.last < at.minInput {
  58. return false
  59. }
  60. // Checks if input is greater than maximum
  61. if at.last > at.maxInput {
  62. if at.loop {
  63. at.Reset()
  64. } else {
  65. return false
  66. }
  67. }
  68. for i := 0; i < len(at.channels); i++ {
  69. ch := at.channels[i]
  70. // Get interpolated value
  71. v, ok := ch.sampler.Interpolate(at.last)
  72. if !ok {
  73. return false
  74. }
  75. // Call action func
  76. ch.action(at, v)
  77. // Sets final rotation
  78. at.target.GetNode().SetRotation(at.rot.X, at.rot.Y, at.rot.Z)
  79. }
  80. return true
  81. }
  82. // NewAnimationTargets creates and returns a map of all animation targets
  83. // contained in the decoded Collada document and for the previously decoded scene.
  84. // The map is indexed by the node loaderID.
  85. func (d *Decoder) NewAnimationTargets(scene core.INode) (map[string]*AnimationTarget, error) {
  86. if d.dom.LibraryAnimations == nil {
  87. return nil, fmt.Errorf("No animations found")
  88. }
  89. // Maps target node to its animation target instance
  90. targetsMap := make(map[string]*AnimationTarget)
  91. // For each Collada animation element
  92. for _, ca := range d.dom.LibraryAnimations.Animation {
  93. // For each Collada channel for this animation
  94. for _, cc := range ca.Channel {
  95. // Separates the channel target in target id and target action
  96. parts := strings.Split(cc.Target, "/")
  97. if len(parts) < 2 {
  98. return nil, fmt.Errorf("Channel target invalid")
  99. }
  100. targetID := parts[0]
  101. targetAction := parts[1]
  102. // Get the target node object referenced by the target id from the specified scene.
  103. target := scene.GetNode().FindLoaderID(targetID)
  104. if target == nil {
  105. return nil, fmt.Errorf("Target node id:%s not found", targetID)
  106. }
  107. // Get reference to the AnimationTarget for this target in the local map
  108. // If not found creates the animation target and inserts in the map
  109. at := targetsMap[targetID]
  110. if at == nil {
  111. at = new(AnimationTarget)
  112. at.target = target
  113. at.matrix = target.GetNode().Matrix()
  114. targetsMap[targetID] = at
  115. }
  116. // Creates the sampler instance specified from the channel source
  117. si, err := NewSamplerInstance(ca, cc.Source)
  118. if err != nil {
  119. return nil, err
  120. }
  121. // Sets the action function from the target action
  122. var af ActionFunc
  123. switch targetAction {
  124. case "location.X":
  125. af = actionPositionX
  126. case "location.Y":
  127. af = actionPositionY
  128. case "location.Z":
  129. af = actionPositionZ
  130. case "rotationX.ANGLE":
  131. af = actionRotationX
  132. case "rotationY.ANGLE":
  133. af = actionRotationY
  134. case "rotationZ.ANGLE":
  135. af = actionRotationZ
  136. case "scale.X":
  137. af = actionScaleX
  138. case "scale.Y":
  139. af = actionScaleY
  140. case "scale.Z":
  141. af = actionScaleZ
  142. default:
  143. return nil, fmt.Errorf("Unsupported channel target action:%s", targetAction)
  144. }
  145. // Creates the channel instance for this sampler and target action and adds it
  146. // to the current AnimationTarget
  147. ci := &ChannelInstance{si, af}
  148. at.channels = append(at.channels, ci)
  149. }
  150. }
  151. // Set minimum and maximum input values for each animation target
  152. for _, at := range targetsMap {
  153. at.minInput = math32.Infinity
  154. at.maxInput = -math32.Infinity
  155. for _, ch := range at.channels {
  156. // First key frame input
  157. inp := ch.sampler.Input[0]
  158. if inp < at.minInput {
  159. at.minInput = inp
  160. }
  161. // Last key frame input
  162. inp = ch.sampler.Input[len(ch.sampler.Input)-1]
  163. if inp > at.maxInput {
  164. at.maxInput = inp
  165. }
  166. }
  167. }
  168. return targetsMap, nil
  169. }
  170. func actionPositionX(at *AnimationTarget, v float32) {
  171. at.target.GetNode().SetPositionX(v)
  172. }
  173. func actionPositionY(at *AnimationTarget, v float32) {
  174. at.target.GetNode().SetPositionY(v)
  175. }
  176. func actionPositionZ(at *AnimationTarget, v float32) {
  177. at.target.GetNode().SetPositionZ(v)
  178. }
  179. func actionRotationX(at *AnimationTarget, v float32) {
  180. at.rot.X = math32.DegToRad(v)
  181. }
  182. func actionRotationY(at *AnimationTarget, v float32) {
  183. at.rot.Y = math32.DegToRad(v)
  184. }
  185. func actionRotationZ(at *AnimationTarget, v float32) {
  186. at.rot.Z = math32.DegToRad(v)
  187. }
  188. func actionScaleX(at *AnimationTarget, v float32) {
  189. at.target.GetNode().SetScaleX(v)
  190. }
  191. func actionScaleY(at *AnimationTarget, v float32) {
  192. at.target.GetNode().SetScaleY(v)
  193. }
  194. func actionScaleZ(at *AnimationTarget, v float32) {
  195. at.target.GetNode().SetScaleZ(v)
  196. }
  197. // NewSampler creates and returns a pointer to a new SamplerInstance built
  198. // with data from the specified Collada animation and URI
  199. func NewSamplerInstance(ca *Animation, uri string) (*SamplerInstance, error) {
  200. id := strings.TrimPrefix(uri, "#")
  201. var cs *Sampler
  202. for _, current := range ca.Sampler {
  203. if current.Id == id {
  204. cs = current
  205. break
  206. }
  207. }
  208. if cs == nil {
  209. return nil, fmt.Errorf("Sampler:%s not found", id)
  210. }
  211. // Get sampler inputs
  212. si := new(SamplerInstance)
  213. for _, inp := range cs.Input {
  214. if inp.Semantic == "INPUT" {
  215. data, err := findSourceFloatArray(ca, inp.Source)
  216. if err != nil {
  217. return nil, err
  218. }
  219. si.Input = data
  220. continue
  221. }
  222. if inp.Semantic == "OUTPUT" {
  223. data, err := findSourceFloatArray(ca, inp.Source)
  224. if err != nil {
  225. return nil, err
  226. }
  227. si.Output = data
  228. continue
  229. }
  230. if inp.Semantic == "INTERPOLATION" {
  231. data, err := findSourceNameArray(ca, inp.Source)
  232. if err != nil {
  233. return nil, err
  234. }
  235. si.Interp = data
  236. continue
  237. }
  238. if inp.Semantic == "IN_TANGENT" {
  239. data, err := findSourceFloatArray(ca, inp.Source)
  240. if err != nil {
  241. return nil, err
  242. }
  243. si.InTangent = data
  244. continue
  245. }
  246. if inp.Semantic == "OUT_TANGENT" {
  247. data, err := findSourceFloatArray(ca, inp.Source)
  248. if err != nil {
  249. return nil, err
  250. }
  251. si.OutTangent = data
  252. continue
  253. }
  254. }
  255. return si, nil
  256. }
  257. // Interpolate returns the interpolated output and its validity
  258. // for this sampler for the specified input.
  259. func (si *SamplerInstance) Interpolate(inp float32) (float32, bool) {
  260. // Test limits
  261. if len(si.Input) < 2 {
  262. return 0, false
  263. }
  264. if inp < si.Input[0] {
  265. return 0, false
  266. }
  267. if inp > si.Input[len(si.Input)-1] {
  268. return 0, false
  269. }
  270. // Find key frame interval
  271. var idx int
  272. for idx = 0; idx < len(si.Input)-1; idx++ {
  273. if inp >= si.Input[idx] && inp < si.Input[idx+1] {
  274. break
  275. }
  276. }
  277. // Checks if interval was found
  278. if idx >= len(si.Input)-1 {
  279. return 0, false
  280. }
  281. switch si.Interp[idx] {
  282. case "STEP":
  283. return si.linearInterp(inp, idx), true
  284. case "LINEAR":
  285. return si.linearInterp(inp, idx), true
  286. case "BEZIER":
  287. return si.bezierInterp(inp, idx), true
  288. case "HERMITE":
  289. return si.linearInterp(inp, idx), true
  290. case "CARDINAL":
  291. return si.linearInterp(inp, idx), true
  292. case "BSPLINE":
  293. return si.linearInterp(inp, idx), true
  294. default:
  295. return 0, false
  296. }
  297. return 0, false
  298. }
  299. func (si *SamplerInstance) linearInterp(inp float32, idx int) float32 {
  300. k1 := si.Input[idx]
  301. k2 := si.Input[idx+1]
  302. v1 := si.Output[idx]
  303. v2 := si.Output[idx+1]
  304. return v1 + (v2-v1)*(inp-k1)/(k2-k1)
  305. }
  306. func (si *SamplerInstance) bezierInterp(inp float32, idx int) float32 {
  307. p0 := si.Output[idx]
  308. p1 := si.Output[idx+1]
  309. c0 := si.OutTangent[2*idx+1]
  310. c1 := si.InTangent[2*(idx+1)+1]
  311. k1 := si.Input[idx]
  312. k2 := si.Input[idx+1]
  313. s := (inp - k1) / (k2 - k1)
  314. out := p0*math32.Pow(1-s, 3) + 3*c0*s*math32.Pow(1-s, 2) + 3*c1*s*s*(1-s) + p1*math32.Pow(s, 3)
  315. return out
  316. }
  317. func findSourceNameArray(ca *Animation, uri string) ([]string, error) {
  318. src := findSource(ca, uri)
  319. if src == nil {
  320. return nil, fmt.Errorf("Source:%s not found", uri)
  321. }
  322. na, ok := src.ArrayElement.(*NameArray)
  323. if !ok {
  324. return nil, fmt.Errorf("Source:%s is not NameArray", uri)
  325. }
  326. return na.Data, nil
  327. }
  328. func findSourceFloatArray(ca *Animation, uri string) ([]float32, error) {
  329. src := findSource(ca, uri)
  330. if src == nil {
  331. return nil, fmt.Errorf("Source:%s not found", uri)
  332. }
  333. fa, ok := src.ArrayElement.(*FloatArray)
  334. if !ok {
  335. return nil, fmt.Errorf("Source:%s is not FloatArray", uri)
  336. }
  337. return fa.Data, nil
  338. }
  339. func findSource(ca *Animation, uri string) *Source {
  340. id := strings.TrimPrefix(uri, "#")
  341. for _, src := range ca.Source {
  342. if src.Id == id {
  343. return src
  344. }
  345. }
  346. return nil
  347. }