/
PopmotionPlugin.ts
240 lines (211 loc) · 8.48 KB
/
PopmotionPlugin.ts
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
import type {Driver} from 'popmotion/lib/animations/types'
import {now} from 'ts-browser-helpers'
import {animate, type AnimationOptions} from 'popmotion'
import {AViewerPluginSync, ThreeViewer} from '../../viewer'
import type {FrameFadePlugin} from '../pipeline/FrameFadePlugin'
import type {ProgressivePlugin} from '../pipeline/ProgressivePlugin'
import {generateUUID} from '../../three'
import {animateCameraToViewLinear, animateCameraToViewSpherical, EasingFunctions, makeSetterFor} from '../../utils'
import {ICamera, ICameraView} from '../../core'
export interface AnimationResult{
id: string
promise: Promise<string>
options: AnimationOptions<any>
stop: () => void
// eslint-disable-next-line @typescript-eslint/naming-convention
_stop?: () => void
targetRef?: {target: any, key: string}
}
/**
* Popmotion plugin
*
* Provides animation capabilities to the viewer using the popmotion library: https://popmotion.io/
*
* Overrides the driver in popmotion to sync with the viewer and provide ways to keep track and stop animations.
*
* @category Plugin
*/
export class PopmotionPlugin extends AViewerPluginSync<''> {
public static readonly PluginType = 'PopmotionPlugin'
enabled = true
toJSON: any = undefined // disable serialization
fromJSON: any = undefined // disable serialization
constructor(enabled = true) {
super()
this.enabled = enabled
this._postFrame = this._postFrame.bind(this)
}
// private _animating = false
private _lastFrameTime = 0 // for post frame
private _updaters: {u: ((timestamp: number) => void), time: number}[] = []
dependencies = []
private _fadeDisabled = false
/**
* Disable the frame fade plugin while animation is running
*/
disableFrameFade = true
// Same code used in CameraViewPlugin
private _postFrame = ()=>{
if (!this._viewer) return
if (this.isDisabled() || Object.keys(this.animations).length < 1) {
this._lastFrameTime = 0
// console.log('not anim')
if (this._fadeDisabled) {
this._viewer.getPlugin<FrameFadePlugin>('FrameFade')?.enable(this)
this._fadeDisabled = false
}
return
}
const time = now() / 1000.0
if (this._lastFrameTime < 1) this._lastFrameTime = time - 1.0 / 60.0
let delta = time - this._lastFrameTime
this._lastFrameTime = time
// todo: scrolling
// delta = delta * (this.animateOnScroll ? this._scrollAnimationState : 1)
const d = this._viewer.getPlugin<ProgressivePlugin>('Progressive')?.postFrameConvergedRecordingDelta()
if (d && d > 0) delta = d
if (d === 0) return // not converged yet.
// if d < 0: not recording, do nothing
delta *= 1000
// delta = 16.666 // testing
if (delta <= 0.001) return
this._updaters.forEach(u=>{
let dt = delta
if (u.time + dt < 0) dt = -u.time
u.time += dt
if (Math.abs(dt) > 0.001)
u.u(dt)
})
if (!this._fadeDisabled && this.disableFrameFade) {
const ff = this._viewer.getPlugin<FrameFadePlugin>('FrameFade')
if (ff) {
ff.disable(this)
this._fadeDisabled = true
}
}
// todo: scrolling
// if (this._scrollAnimationState < 0.001) this._scrollAnimationState = 0
// else this._scrollAnimationState *= 1.0 - this.scrollAnimationDamping
}
readonly defaultDriver: Driver = (update)=>{
return {
start: ()=>this._updaters.push({u:update, time:0}),
stop: ()=> this._updaters.splice(this._updaters.findIndex(u=>u.u === update), 1),
}
}
onAdded(viewer: ThreeViewer): void {
super.onAdded(viewer)
viewer.addEventListener('postFrame', this._postFrame)
}
onRemove(viewer: ThreeViewer): void {
viewer.removeEventListener('postFrame', this._postFrame)
super.onRemove(viewer)
}
readonly animations: Record<string, AnimationResult> = {}
animateTarget<T>(target: T, key: keyof T, options: AnimationOptions<T[keyof T]>): AnimationResult {
return this.animate({...options, target, key: key as string})
}
animate<V>(options1: AnimationOptions<V> & {target?: any, key?: string}): AnimationResult {
let targetRef = undefined
const options = {...options1} as ((typeof options1) & {lastOnUpdate?: (a:V)=>void})
if (options.target !== undefined) {
if (options.key === undefined) throw new Error('key must be defined')
if (!(options.key in options.target)) {
console.warn('key not present in target, creating', options.key, options.target)
options.target[options.key] = options.from || 0
}
const setter = makeSetterFor(options.target, options.key)
const fromVal = options.target[options.key]
options.lastOnUpdate = options.onUpdate
options.onUpdate = (val: V)=>{
setter(val)
options.lastOnUpdate && options.lastOnUpdate(val)
}
targetRef = {target: options.target, key: options.key}
if (options.from === undefined) options.from = fromVal
delete options.target
delete options.key
}
const uuid = generateUUID()
const a: AnimationResult = {
id: uuid,
options,
stop: ()=>{
if (!this.animations[uuid]?._stop) console.warn('Animation not started')
else this.animations[uuid]?._stop?.()
},
promise: undefined as any,
targetRef,
}
this.animations[uuid] = a
a.promise = new Promise<void>((resolve, reject) => {
const end2 = ()=>{
try {
options.onEnd && options.onEnd()
} catch (e: any) {
reject(e)
return false
}
return true
}
const opts: AnimationOptions<V> = {
driver: this.defaultDriver,
...options,
onComplete: ()=>{
try {
options.onComplete && options.onComplete()
} catch (e: any) {
if (!end2()) return
reject(e)
return
}
if (!end2()) return
resolve()
},
onStop: ()=>{
try {
options.onStop && options.onStop()
} catch (e: any) {
if (!end2()) return
reject(e)
return
}
resolve()
},
}
// todo: support boolean using timeout.
const anim = animate(opts)
this.animations[uuid]._stop = anim.stop
this.animations[uuid].options = opts
}).then(()=>{
delete this.animations[uuid]
return uuid
})
return this.animations[uuid]
}
async animateAsync<V>(options: AnimationOptions<V>& {target?: any, key?: string}, animations?: AnimationResult[]): Promise<string> {
const anim = this.animate(options)
if (animations) animations.push(anim)
return anim.promise
}
async animateTargetAsync<T>(target: T, key: keyof T, options: AnimationOptions<T[keyof T]>, animations?: AnimationResult[]): Promise<string> {
const anim = this.animate({...options, target, key: key as string})
if (animations) animations.push(anim)
return anim.promise
}
animateCamera(camera: ICamera, view: ICameraView, spherical = true, options?: Partial<AnimationOptions<any>>) {
const anim = spherical ?
animateCameraToViewSpherical(camera, view) :
animateCameraToViewLinear(camera, view)
return this.animate({
ease: EasingFunctions.linear,
duration: 1000,
...anim, ...options,
})
}
async animateCameraAsync(camera: ICamera, view: ICameraView, spherical = true, options?: Partial<AnimationOptions<any>>, animations?: AnimationResult[]) {
const anim = this.animateCamera(camera, view, spherical, options)
if (animations) animations.push(anim)
return anim.promise
}
}