animation-loop.ts 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /**
  2. * Copyright (c) 2020-2022 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author David Sehnal <david.sehnal@gmail.com>
  5. * @author Alexander Rose <alexander.rose@weirdbyte.de>
  6. */
  7. import { PluginContext } from './context';
  8. import { now } from '../mol-util/now';
  9. import { PluginAnimationManager } from '../mol-plugin-state/manager/animation';
  10. import { isTimingMode } from '../mol-util/debug';
  11. import { printTimerResults } from '../mol-gl/webgl/timer';
  12. export class PluginAnimationLoop {
  13. private currentFrame: any = void 0;
  14. private _isAnimating = false;
  15. get isAnimating() {
  16. return this._isAnimating;
  17. }
  18. async tick(t: number, options?: { isSynchronous?: boolean, manualDraw?: boolean, animation?: PluginAnimationManager.AnimationInfo }) {
  19. await this.plugin.managers.animation.tick(t, options?.isSynchronous, options?.animation);
  20. this.plugin.canvas3d?.tick(t as now.Timestamp, options);
  21. if (isTimingMode) {
  22. const timerResults = this.plugin.canvas3d?.webgl.timer.resolve();
  23. if (timerResults) {
  24. for (const result of timerResults) {
  25. printTimerResults([result]);
  26. }
  27. }
  28. }
  29. }
  30. private frame = () => {
  31. this.tick(now());
  32. if (this._isAnimating) {
  33. this.currentFrame = requestAnimationFrame(this.frame);
  34. }
  35. };
  36. resetTime(t: number = now()) {
  37. this.plugin.canvas3d?.resetTime(t);
  38. }
  39. start(options?: { immediate?: boolean }) {
  40. this.plugin.canvas3d?.resume();
  41. this._isAnimating = true;
  42. this.resetTime();
  43. // TODO: should immediate be the default mode?
  44. if (options?.immediate) this.frame();
  45. else this.currentFrame = requestAnimationFrame(this.frame);
  46. }
  47. stop(options?: { noDraw?: boolean }) {
  48. this._isAnimating = false;
  49. if (this.currentFrame !== void 0) {
  50. cancelAnimationFrame(this.currentFrame);
  51. this.currentFrame = void 0;
  52. }
  53. if (options?.noDraw) {
  54. this.plugin.canvas3d?.pause(options?.noDraw);
  55. }
  56. }
  57. constructor(private plugin: PluginContext) {
  58. }
  59. }