-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathcomponent_animation.go
More file actions
598 lines (508 loc) · 16.3 KB
/
Copy pathcomponent_animation.go
File metadata and controls
598 lines (508 loc) · 16.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
/*
* Copyright (c) 2021 The XGo Authors (xgo.dev). All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package spx
import (
"maps"
"math"
"github.com/goplus/spbase/mathf"
"github.com/goplus/spx/v2/internal/base/defaults"
coreproject "github.com/goplus/spx/v2/internal/core/project"
"github.com/goplus/spx/v2/internal/engine"
spxlog "github.com/goplus/spx/v2/internal/log"
"github.com/goplus/spx/v2/internal/time"
"github.com/goplus/spx/v2/internal/tools"
)
// ============================================================================
// Animation Component
// ============================================================================
// This component manages sprite frame playback and tween-driven motion state.
// sharedAnimationData stores read-only animation data shared across cloned sprites.
type sharedAnimationData struct {
animations map[SpriteAnimationName]*coreproject.AniConfig
animBindings map[string]string
defaultAnimation SpriteAnimationName
animationWrappers map[SpriteAnimationName]*animationWrapper
}
type animationComponent struct {
componentBase
// Shared animation configuration (read-only, shared across clones)
shared *sharedAnimationData
// Animation state (per-instance)
curAnimState *animState
curTweenState *animState
activeTweenStates []*animState
defaultAnimActive bool
// Animation tracking (per-instance)
donedAnimations []string
}
// ============================================================================
// Lifecycle
// ============================================================================
// initialize initializes the animation component from configuration.
func (a *animationComponent) initialize(sprite *SpriteImpl, spriteCfg *coreproject.SpriteConfig) {
a.componentBase.initialize(sprite, spriteCfg)
a.initFromConfig(spriteCfg)
a.donedAnimations = make([]string, 0)
}
// initFromConfig initializes animations from sprite configuration.
func (a *animationComponent) initFromConfig(spriteCfg *coreproject.SpriteConfig) {
a.shared = &sharedAnimationData{
defaultAnimation: spriteCfg.DefaultAnimation,
animations: make(map[SpriteAnimationName]*coreproject.AniConfig),
animBindings: make(map[string]string),
animationWrappers: make(map[SpriteAnimationName]*animationWrapper),
}
anims := spriteCfg.FAnimations
for key, val := range anims {
var ani = val
_, ok := a.shared.animations[key]
if ok {
spxlog.Panicf("Animation key [%s] already exists", key)
}
defaults.SetDefaultIfZero(&ani.FrameFps, 25)
defaults.SetDefaultIfZero(&ani.TurnToDuration, 1.0)
defaults.SetDefaultIfZero(&ani.StepDuration, 0.01)
ani.IFrameFrom, ani.IFrameTo = a.frameRange(ani.FrameFrom, ani.FrameTo)
ani.Speed = 1
ani.Duration = (math.Abs(float64(ani.IFrameFrom-ani.IFrameTo)) + 1) / float64(ani.FrameFps)
a.shared.animations[key] = ani
}
maps.Copy(a.shared.animBindings, spriteCfg.AnimBindings)
for animName, ani := range a.shared.animations {
a.shared.animationWrappers[animName] = &animationWrapper{
spriteName: a.sprite.name,
ani: ani,
costumes: a.sprite.costumes,
isCostumeSet: a.sprite.runtimeState.IsCostumeSet,
engineMgr: a.engine(),
}
}
}
// cloneFrom creates a new animation component by cloning from source.
func (a *animationComponent) cloneFrom(src component, newSprite *SpriteImpl) component {
srcAnim := src.(*animationComponent)
newAnim := &animationComponent{
componentBase: componentBase{sprite: newSprite},
shared: srcAnim.shared,
activeTweenStates: make([]*animState, 0),
donedAnimations: make([]string, 0),
}
return newAnim
}
// onDestroy cleans up when the component is destroyed.
func (a *animationComponent) onDestroy() {
a.stopAnimState(a.curAnimState)
for _, state := range a.activeTweenStates {
a.stopAnimState(state)
}
a.curTweenState = nil
a.activeTweenStates = nil
a.unRegisterOnAnimationLooped()
a.unRegisterOnAnimationFinished()
}
func (a *animationComponent) syncSprite() *engine.Sprite {
if a.sprite == nil {
return nil
}
return a.sprite.runtimeState.SyncSprite
}
func (a *animationComponent) syncSpriteForPlayback() *engine.Sprite {
if a.sprite == nil || a.sprite.isDestroyed() {
return nil
}
return a.sprite.runtimeState.SyncSprite
}
// ============================================================================
// Playback
// ============================================================================
func (a *animationComponent) registerOnAnimationLooped(f func()) {
if syncSprite := a.syncSprite(); syncSprite != nil {
syncSprite.RegisterOnAnimationLooped(f)
}
}
func (a *animationComponent) unRegisterOnAnimationLooped() {
if syncSprite := a.syncSprite(); syncSprite != nil {
syncSprite.UnRegisterOnAnimationLooped()
}
}
func (a *animationComponent) registerOnAnimationFinished(f func()) {
if syncSprite := a.syncSprite(); syncSprite != nil {
syncSprite.RegisterOnAnimationFinished(f)
}
}
func (a *animationComponent) unRegisterOnAnimationFinished() {
if syncSprite := a.syncSprite(); syncSprite != nil {
syncSprite.UnRegisterOnAnimationFinished()
}
}
func (a *animationComponent) Animate(name SpriteAnimationName, loop bool) {
a.playAnimation(name, loop, false, "Animation: %s")
}
func (a *animationComponent) AnimateAndWait(name SpriteAnimationName) {
a.playAnimation(name, false, true, "AnimateAndWait: %s")
}
func (a *animationComponent) StopAnimation(name SpriteAnimationName) {
if name == "" || !a.hasAnim(name) {
return
}
state := a.curAnimState
if state == nil || state.Name != name {
return
}
syncSprite := a.syncSpriteForPlayback()
if syncSprite == nil {
return
}
if !a.stopCurrentAnimState(state) {
return
}
syncSprite.PauseAnim()
a.playDefaultAnim()
}
func (a *animationComponent) playAnimation(name SpriteAnimationName, loop, blocking bool, debugMsg string) {
if isDebugInstrEnabled() {
spxlog.Debug(debugMsg, name)
}
ani, ok := a.shared.animations[name]
if !ok {
spxlog.Warn("Animation not found: %s", name)
return
}
a.doAnimation(name, ani, loop, 1, blocking, true)
}
func (a *animationComponent) doAnimation(animName SpriteAnimationName, ani *coreproject.AniConfig, loop bool, speed float64, isBlocking bool, playAudio bool) *animState {
syncSprite := a.syncSpriteForPlayback()
if syncSprite == nil {
return nil
}
a.stopAnimState(a.curAnimState)
a.defaultAnimActive = false
a.curAnimState = &animState{
AniType: coreproject.AniTypeFrame,
Name: animName,
Speed: speed,
}
info := a.curAnimState
if playAudio {
a.playAnimationAudio(ani, info)
}
a.sprite.baseObj.applyCostumeUpdate()
a.prepareAnimationPlayback(animName, ani)
a.engine().SpriteMgr.PlayAnim(syncSprite.GetId(), animName, speed, loop, false)
if isBlocking {
a.sprite.runtimeState.IsAnimating = true
for a.engine().SpriteMgr.IsPlayingAnim(syncSprite.GetId()) {
if info.IsCanceled {
break
}
engine.WaitNextFrame()
}
a.sprite.runtimeState.IsAnimating = false
a.stopAnimState(info)
}
return info
}
// ============================================================================
// Animation State
// ============================================================================
func (a *animationComponent) playDefaultAnim() {
animName := ""
syncSprite := a.syncSpriteForPlayback()
if syncSprite == nil {
return
}
if !a.sprite.spriteState.IsVisible || a.sprite.spriteState.IsDying {
return
}
speed := 1.0
if a.curTweenState == nil {
animName = a.shared.defaultAnimation
} else {
switch a.curTweenState.AniType {
case coreproject.AniTypeMove:
animName = a.sprite.getStateAnimName(StateStep)
case coreproject.AniTypeTurn:
animName = a.sprite.getStateAnimName(StateTurn)
case coreproject.AniTypeGlide:
animName = a.sprite.getStateAnimName(StateGlide)
}
speed = a.curTweenState.Speed
}
if animName == "" {
animName = a.shared.defaultAnimation
}
if ani, ok := a.shared.animations[animName]; ok {
a.prepareAnimationPlayback(animName, ani)
a.engine().SpriteMgr.PlayAnim(syncSprite.GetId(), animName, speed, true, false)
a.defaultAnimActive = true
} else {
a.defaultAnimActive = false
a.sprite.goSetCostume(a.sprite.spriteState.DefaultCostumeIndex)
}
}
func (a *animationComponent) playDefaultAnimIfIdle() {
if a.hasActiveAnimationPlayback() {
return
}
a.playDefaultAnim()
}
func (a *animationComponent) hasActiveAnimationPlayback() bool {
if a.defaultAnimActive {
return true
}
return a.curAnimState != nil && !a.curAnimState.IsCanceled
}
func (a *animationComponent) adaptAnimBitmapResolution(ani *coreproject.AniConfig) {
syncSprite := a.syncSprite()
if syncSprite == nil {
return
}
renderScale := a.sprite.getAnimRenderScale(ani.AdaptAnimBitmapResolution)
syncSprite.SetRenderScale(engine.UniformVec2(renderScale))
}
func (a *animationComponent) prepareAnimationPlayback(animName SpriteAnimationName, ani *coreproject.AniConfig) {
a.shared.animationWrappers[animName].ensureRegistered(animName, ani)
a.adaptAnimBitmapResolution(ani)
}
func (a *animationComponent) onAnimationDone(animName string) {
if a.syncSpriteForPlayback() == nil {
return
}
if state := a.curAnimState; state != nil && state.Name == animName {
if !a.stopCurrentAnimState(state) {
return
}
a.playDefaultAnim()
}
}
func (a *animationComponent) stopCurrentAnimState(state *animState) bool {
a.stopAnimState(state)
if a.curAnimState != state {
return false
}
a.curAnimState = nil
return true
}
func (a *animationComponent) stopAnimState(state *animState) {
if state == nil {
return
}
engine.Lock()
state.IsCanceled = true
engine.Unlock()
a.stopAnimationAudio(state)
}
func (a *animationComponent) costumeIndex(nameOrIndex any) int {
switch v := nameOrIndex.(type) {
case SpriteCostumeName:
idx := a.sprite.findCostume(v)
if idx < 0 {
spxlog.Panicf("FindCostume failed for %s", v)
}
return idx
default:
val, _ := tools.GetFloat(nameOrIndex)
return int(val)
}
}
func (a *animationComponent) frameRange(from, to any) (int, int) {
return a.costumeIndex(from), a.costumeIndex(to)
}
func (a *animationComponent) hasAnim(animName string) bool {
_, ok := a.shared.animations[animName]
return ok
}
func (a *animationComponent) getAnimation(animName SpriteAnimationName) (*coreproject.AniConfig, bool) {
ani, ok := a.shared.animations[animName]
return ani, ok
}
func (a *animationComponent) getStateAnimName(stateName string) string {
if bindingName, ok := a.shared.animBindings[stateName]; ok {
return bindingName
}
return stateName
}
func (a *animationComponent) addDonedAnimation(animName string) {
a.donedAnimations = append(a.donedAnimations, animName)
}
func (a *animationComponent) takeDonedAnimations(buffer []string) []string {
buffer = append(buffer, a.donedAnimations...)
a.donedAnimations = a.donedAnimations[:0]
return buffer
}
func (a *animationComponent) getCurAnimState() *animState {
return a.curAnimState
}
func (a *animationComponent) getCurTweenState() *animState {
return a.curTweenState
}
func (a *animationComponent) registerTweenState(state *animState) {
a.activeTweenStates = append(a.activeTweenStates, state)
a.curTweenState = state
}
func (a *animationComponent) unregisterTweenState(state *animState) bool {
idx := -1
for i := len(a.activeTweenStates) - 1; i >= 0; i-- {
if a.activeTweenStates[i] == state {
idx = i
break
}
}
if idx < 0 {
return false
}
a.activeTweenStates = append(a.activeTweenStates[:idx], a.activeTweenStates[idx+1:]...)
if len(a.activeTweenStates) == 0 {
a.curTweenState = nil
} else {
a.curTweenState = a.activeTweenStates[len(a.activeTweenStates)-1]
}
return true
}
// tweenParams holds pre-calculated parameters for tween animations.
type tweenParams struct {
moveFrom mathf.Vec2
moveTo mathf.Vec2
moveVelocity mathf.Vec2
turnFrom float64
turnTo float64
}
// ============================================================================
// Tween Execution
// ============================================================================
func (a *animationComponent) doTween(name SpriteAnimationName, ani *coreproject.AniConfig) {
info, ownedPlayback := a.initTweenState(name, ani)
if info == nil {
return
}
params, ok := a.prepareTweenParams(ani)
if !ok {
return
}
a.executeTweenLoop(info, ani, params)
a.cleanupTween(info, ownedPlayback, name, ani)
}
func (a *animationComponent) initTweenState(name SpriteAnimationName, ani *coreproject.AniConfig) (*animState, *animState) {
if ani.Duration <= 0 {
spxlog.Warn("Invalid animation duration: %v", ani.Duration)
return nil, nil
}
info := &animState{
AniType: ani.AniType,
Name: name,
Speed: ani.Speed,
}
a.registerTweenState(info)
var ownedPlayback *animState
if a.hasAnim(name) {
ownedPlayback = a.doAnimation(name, ani, ani.IsLoop, ani.Speed, false, false)
a.playAnimationAudio(ani, info)
}
return info, ownedPlayback
}
func (a *animationComponent) prepareTweenParams(ani *coreproject.AniConfig) (*tweenParams, bool) {
params := &tweenParams{}
duration := ani.Duration
switch ani.AniType {
case coreproject.AniTypeMove, coreproject.AniTypeGlide:
src, srcOk := tools.GetVec2(ani.From)
dst, dstOk := tools.GetVec2(ani.To)
if !srcOk || !dstOk {
spxlog.Warn("Invalid 'From' or 'To' for move/glide animation: not a *mathf.Vec2")
return nil, false
}
params.moveFrom = src
params.moveTo = dst
if ani.AniType == coreproject.AniTypeMove {
params.moveVelocity = dst.Sub(src).Mulf(1 / duration)
}
case coreproject.AniTypeTurn:
src, srcOk := tools.GetFloat(ani.From)
dst, dstOk := tools.GetFloat(ani.To)
if !srcOk || !dstOk {
spxlog.Warn("Invalid 'From' or 'To' for turn animation: not a float")
return nil, false
}
params.turnFrom = src
params.turnTo = dst
}
return params, true
}
func (a *animationComponent) executeTweenLoop(info *animState, ani *coreproject.AniConfig, params *tweenParams) {
timer := 0.0
duration := ani.Duration
for timer < duration {
if info.IsCanceled {
return
}
timer += time.DeltaTime()
percent := mathf.Clamp01f(timer / duration)
a.applyTweenStep(ani.AniType, percent, params)
engine.WaitNextFrame()
}
}
func (a *animationComponent) applyTweenStep(aniType coreproject.AniType, percent float64, params *tweenParams) {
switch aniType {
case coreproject.AniTypeMove:
physicsMode := a.sprite.PhysicsMode()
if isPhysicsEnabled() && physicsMode != NoPhysics && physicsMode != StaticPhysics {
a.sprite.SetVelocity(params.moveVelocity.X, params.moveVelocity.Y)
} else {
a.applyTweenPosition(percent, params)
}
case coreproject.AniTypeGlide:
a.applyTweenPosition(percent, params)
case coreproject.AniTypeTurn:
a.applyTweenHeading(percent, params)
}
}
func (a *animationComponent) applyTweenPosition(percent float64, params *tweenParams) {
pos := params.moveFrom.Lerp(params.moveTo, percent)
a.sprite.SetXYpos(pos.X, pos.Y)
}
func (a *animationComponent) applyTweenHeading(percent float64, params *tweenParams) {
a.sprite.SetHeading(mathf.Lerpf(params.turnFrom, params.turnTo, percent))
}
func (a *animationComponent) cleanupTween(info, ownedPlayback *animState, name SpriteAnimationName, ani *coreproject.AniConfig) {
a.stopMoveTweenVelocity(ani)
a.stopAnimState(info)
stoppedOwnedPlayback := a.stopOwnedTweenPlaybackIfCurrent(ownedPlayback)
if !a.unregisterTweenState(info) {
if stoppedOwnedPlayback {
a.playDefaultAnimIfIdle()
}
return
}
if name != a.shared.defaultAnimation && !ani.IsKeepOnStop {
a.playDefaultAnimIfIdle()
}
}
func (a *animationComponent) stopMoveTweenVelocity(ani *coreproject.AniConfig) {
if ani.AniType != coreproject.AniTypeMove {
return
}
physicsMode := a.sprite.PhysicsMode()
if isPhysicsEnabled() && physicsMode != NoPhysics && physicsMode != StaticPhysics {
a.sprite.SetVelocity(0, 0)
}
}
func (a *animationComponent) stopOwnedTweenPlaybackIfCurrent(ownedPlayback *animState) bool {
if ownedPlayback == nil || a.curAnimState != ownedPlayback {
return false
}
a.stopCurrentAnimState(ownedPlayback)
return true
}