• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

visgl / luma.gl / 17267018539

27 Aug 2025 12:42PM UTC coverage: 76.317% (-0.006%) from 76.323%
17267018539

push

github

web-flow
Document redraw detection and expose needsRedraw on AnimationLoop (#2443)

2270 of 2958 branches covered (76.74%)

Branch coverage included in aggregate %.

7 of 11 new or added lines in 1 file covered. (63.64%)

28553 of 37430 relevant lines covered (76.28%)

68.17 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

79.74
/modules/engine/src/animation-loop/animation-loop.ts
1
// luma.gl
1✔
2
// SPDX-License-Identifier: MIT
1✔
3
// Copyright (c) vis.gl contributors
1✔
4

1✔
5
import {luma, Device} from '@luma.gl/core';
1✔
6
import {
1✔
7
  requestAnimationFramePolyfill,
1✔
8
  cancelAnimationFramePolyfill
1✔
9
} from './request-animation-frame';
1✔
10
import {Timeline} from '../animation/timeline';
1✔
11
import {AnimationProps} from './animation-props';
1✔
12
import {Stats, Stat} from '@probe.gl/stats';
1✔
13

1✔
14
let statIdCounter = 0;
1✔
15

1✔
16
/** AnimationLoop properties */
1✔
17
export type AnimationLoopProps = {
1✔
18
  device: Device | Promise<Device>;
1✔
19

1✔
20
  onAddHTML?: (div: HTMLDivElement) => string; // innerHTML
1✔
21
  onInitialize?: (animationProps: AnimationProps) => Promise<unknown>;
1✔
22
  onRender?: (animationProps: AnimationProps) => unknown;
1✔
23
  onFinalize?: (animationProps: AnimationProps) => void;
1✔
24
  onError?: (reason: Error) => void;
1✔
25

1✔
26
  stats?: Stats;
1✔
27

1✔
28
  // view parameters - TODO move to CanvasContext?
1✔
29
  autoResizeViewport?: boolean;
1✔
30
};
1✔
31

1✔
32
export type MutableAnimationLoopProps = {
1✔
33
  // view parameters
1✔
34
  autoResizeViewport?: boolean;
1✔
35
};
1✔
36

1✔
37
/** Convenient animation loop */
1✔
38
export class AnimationLoop {
1✔
39
  static defaultAnimationLoopProps = {
1✔
40
    device: null!,
1✔
41

1✔
42
    onAddHTML: () => '',
1✔
43
    onInitialize: async () => null,
1✔
44
    onRender: () => {},
1✔
45
    onFinalize: () => {},
1✔
46
    onError: error => console.error(error), // eslint-disable-line no-console
1✔
47

1✔
48
    stats: luma.stats.get(`animation-loop-${statIdCounter++}`),
1✔
49

1✔
50
    // view parameters
1✔
51
    autoResizeViewport: false
1✔
52
  } as const satisfies Readonly<Required<AnimationLoopProps>>;
1✔
53

1✔
54
  device: Device | null = null;
1✔
55
  canvas: HTMLCanvasElement | OffscreenCanvas | null = null;
1✔
56

1✔
57
  props: Required<AnimationLoopProps>;
1✔
58
  animationProps: AnimationProps | null = null;
1✔
59
  timeline: Timeline | null = null;
1✔
60
  stats: Stats;
1✔
61
  cpuTime: Stat;
1✔
62
  gpuTime: Stat;
1✔
63
  frameRate: Stat;
1✔
64

1✔
65
  display: any;
1✔
66

1✔
67
  private _needsRedraw: string | false = 'initialized';
1✔
68

1✔
69
  _initialized: boolean = false;
1✔
70
  _running: boolean = false;
1✔
71
  _animationFrameId: any = null;
1✔
72
  _nextFramePromise: Promise<AnimationLoop> | null = null;
1✔
73
  _resolveNextFrame: ((animationLoop: AnimationLoop) => void) | null = null;
1✔
74
  _cpuStartTime: number = 0;
1✔
75
  _error: Error | null = null;
1✔
76

1✔
77
  // _gpuTimeQuery: Query | null = null;
1✔
78

1✔
79
  /*
1✔
80
   * @param {HTMLCanvasElement} canvas - if provided, width and height will be passed to context
1✔
81
   */
1✔
82
  constructor(props: AnimationLoopProps) {
1✔
83
    this.props = {...AnimationLoop.defaultAnimationLoopProps, ...props};
6✔
84
    props = this.props;
6✔
85

6✔
86
    if (!props.device) {
6!
87
      throw new Error('No device provided');
×
88
    }
×
89

6✔
90
    // state
6✔
91
    this.stats = props.stats || new Stats({id: 'animation-loop-stats'});
6!
92
    this.cpuTime = this.stats.get('CPU Time');
6✔
93
    this.gpuTime = this.stats.get('GPU Time');
6✔
94
    this.frameRate = this.stats.get('Frame Rate');
6✔
95

6✔
96
    this.setProps({autoResizeViewport: props.autoResizeViewport});
6✔
97

6✔
98
    // Bind methods
6✔
99
    this.start = this.start.bind(this);
6✔
100
    this.stop = this.stop.bind(this);
6✔
101

6✔
102
    this._onMousemove = this._onMousemove.bind(this);
6✔
103
    this._onMouseleave = this._onMouseleave.bind(this);
6✔
104
  }
6✔
105

1✔
106
  destroy(): void {
1✔
107
    this.stop();
×
108
    this._setDisplay(null);
×
109
  }
×
110

1✔
111
  /** @deprecated Use .destroy() */
1✔
112
  delete(): void {
1✔
113
    this.destroy();
×
114
  }
×
115

1✔
116
  reportError(error: Error): void {
1✔
117
    this.props.onError(error);
×
118
    this._error = error;
×
119
  }
×
120

1✔
121
  /** Flags this animation loop as needing redraw */
1✔
122
  setNeedsRedraw(reason: string): this {
1✔
123
    this._needsRedraw = this._needsRedraw || reason;
4✔
124
    return this;
4✔
125
  }
4✔
126

1✔
127
  /** Query redraw status. Clears the flag. */
1✔
128
  needsRedraw(): false | string {
1✔
NEW
129
    const reason = this._needsRedraw;
×
NEW
130
    this._needsRedraw = false;
×
NEW
131
    return reason;
×
NEW
132
  }
×
133

1✔
134
  setProps(props: MutableAnimationLoopProps): this {
1✔
135
    if ('autoResizeViewport' in props) {
6✔
136
      this.props.autoResizeViewport = props.autoResizeViewport || false;
6✔
137
    }
6✔
138
    return this;
6✔
139
  }
6✔
140

1✔
141
  /** Starts a render loop if not already running */
1✔
142
  async start() {
1✔
143
    if (this._running) {
8✔
144
      return this;
2✔
145
    }
2✔
146
    this._running = true;
6✔
147

6✔
148
    try {
6✔
149
      let appContext;
6✔
150
      if (!this._initialized) {
8✔
151
        this._initialized = true;
5✔
152
        // Create the WebGL context
5✔
153
        await this._initDevice();
5✔
154
        this._initialize();
5✔
155

5✔
156
        // Note: onIntialize can return a promise (e.g. in case app needs to load resources)
5✔
157
        await this.props.onInitialize(this._getAnimationProps());
5✔
158
      }
5✔
159

6✔
160
      // check that we haven't been stopped
6✔
161
      if (!this._running) {
8✔
162
        return null;
1✔
163
      }
1✔
164

5✔
165
      // Start the loop
5✔
166
      if (appContext !== false) {
5✔
167
        // cancel any pending renders to ensure only one loop can ever run
5✔
168
        this._cancelAnimationFrame();
5✔
169
        this._requestAnimationFrame();
5✔
170
      }
5✔
171

5✔
172
      return this;
5✔
173
    } catch (err: unknown) {
8!
174
      const error = err instanceof Error ? err : new Error('Unknown error');
×
175
      this.props.onError(error);
×
176
      // this._running = false; // TODO
×
177
      throw error;
×
178
    }
×
179
  }
8✔
180

1✔
181
  /** Stops a render loop if already running, finalizing */
1✔
182
  stop() {
1✔
183
    // console.debug(`Stopping ${this.constructor.name}`);
6✔
184
    if (this._running) {
6✔
185
      // call callback
6✔
186
      // If stop is called immediately, we can end up in a state where props haven't been initialized...
6✔
187
      if (this.animationProps && !this._error) {
6✔
188
        this.props.onFinalize(this.animationProps);
6✔
189
      }
6✔
190

6✔
191
      this._cancelAnimationFrame();
6✔
192
      this._nextFramePromise = null;
6✔
193
      this._resolveNextFrame = null;
6✔
194
      this._running = false;
6✔
195
    }
6✔
196
    return this;
6✔
197
  }
6✔
198

1✔
199
  /** Explicitly draw a frame */
1✔
200
  redraw(): this {
1✔
201
    if (this.device?.isLost || this._error) {
9!
202
      return this;
×
203
    }
×
204

9✔
205
    this._beginFrameTimers();
9✔
206

9✔
207
    this._setupFrame();
9✔
208
    this._updateAnimationProps();
9✔
209

9✔
210
    this._renderFrame(this._getAnimationProps());
9✔
211

9✔
212
    // clear needsRedraw flag
9✔
213
    this._clearNeedsRedraw();
9✔
214

9✔
215
    if (this._resolveNextFrame) {
9✔
216
      this._resolveNextFrame(this);
4✔
217
      this._nextFramePromise = null;
4✔
218
      this._resolveNextFrame = null;
4✔
219
    }
4✔
220

9✔
221
    this._endFrameTimers();
9✔
222

9✔
223
    return this;
9✔
224
  }
9✔
225

1✔
226
  /** Add a timeline, it will be automatically updated by the animation loop. */
1✔
227
  attachTimeline(timeline: Timeline): Timeline {
1✔
228
    this.timeline = timeline;
×
229
    return this.timeline;
×
230
  }
×
231

1✔
232
  /** Remove a timeline */
1✔
233
  detachTimeline(): void {
1✔
234
    this.timeline = null;
×
235
  }
×
236

1✔
237
  /** Wait until a render completes */
1✔
238
  waitForRender(): Promise<AnimationLoop> {
1✔
239
    this.setNeedsRedraw('waitForRender');
4✔
240

4✔
241
    if (!this._nextFramePromise) {
4✔
242
      this._nextFramePromise = new Promise(resolve => {
4✔
243
        this._resolveNextFrame = resolve;
4✔
244
      });
4✔
245
    }
4✔
246
    return this._nextFramePromise;
4✔
247
  }
4✔
248

1✔
249
  /** TODO - should use device.deviceContext */
1✔
250
  async toDataURL(): Promise<string> {
1✔
251
    this.setNeedsRedraw('toDataURL');
×
252
    await this.waitForRender();
×
253
    if (this.canvas instanceof HTMLCanvasElement) {
×
254
      return this.canvas.toDataURL();
×
255
    }
×
256
    throw new Error('OffscreenCanvas');
×
257
  }
×
258

1✔
259
  // PRIVATE METHODS
1✔
260

1✔
261
  _initialize(): void {
1✔
262
    this._startEventHandling();
5✔
263

5✔
264
    // Initialize the callback data
5✔
265
    this._initializeAnimationProps();
5✔
266
    this._updateAnimationProps();
5✔
267

5✔
268
    // Default viewport setup, in case onInitialize wants to render
5✔
269
    this._resizeViewport();
5✔
270

5✔
271
    // this._gpuTimeQuery = Query.isSupported(this.gl, ['timers']) ? new Query(this.gl) : null;
5✔
272
  }
5✔
273

1✔
274
  _setDisplay(display: any): void {
1✔
275
    if (this.display) {
×
276
      this.display.destroy();
×
277
      this.display.animationLoop = null;
×
278
    }
×
279

×
280
    // store animation loop on the display
×
281
    if (display) {
×
282
      display.animationLoop = this;
×
283
    }
×
284

×
285
    this.display = display;
×
286
  }
×
287

1✔
288
  _requestAnimationFrame(): void {
1✔
289
    if (!this._running) {
13✔
290
      return;
1✔
291
    }
1✔
292

12✔
293
    // VR display has a separate animation frame to sync with headset
12✔
294
    // TODO WebVR API discontinued, replaced by WebXR: https://immersive-web.github.io/webxr/
12✔
295
    // See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/requestAnimationFrame
12✔
296
    // if (this.display && this.display.requestAnimationFrame) {
12✔
297
    //   this._animationFrameId = this.display.requestAnimationFrame(this._animationFrame.bind(this));
12✔
298
    // }
12✔
299
    this._animationFrameId = requestAnimationFramePolyfill(this._animationFrame.bind(this));
12✔
300
  }
13✔
301

1✔
302
  _cancelAnimationFrame(): void {
1✔
303
    if (this._animationFrameId === null) {
11✔
304
      return;
6✔
305
    }
6✔
306

5✔
307
    // VR display has a separate animation frame to sync with headset
5✔
308
    // TODO WebVR API discontinued, replaced by WebXR: https://immersive-web.github.io/webxr/
5✔
309
    // See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/requestAnimationFrame
5✔
310
    // if (this.display && this.display.cancelAnimationFramePolyfill) {
5✔
311
    //   this.display.cancelAnimationFrame(this._animationFrameId);
5✔
312
    // }
5✔
313
    cancelAnimationFramePolyfill(this._animationFrameId);
5✔
314
    this._animationFrameId = null;
5✔
315
  }
11✔
316

1✔
317
  _animationFrame(): void {
1✔
318
    if (!this._running) {
8!
319
      return;
×
320
    }
×
321
    this.redraw();
8✔
322
    this._requestAnimationFrame();
8✔
323
  }
8✔
324

1✔
325
  // Called on each frame, can be overridden to call onRender multiple times
1✔
326
  // to support e.g. stereoscopic rendering
1✔
327
  _renderFrame(animationProps: AnimationProps): void {
1✔
328
    // Allow e.g. VR display to render multiple frames.
9✔
329
    if (this.display) {
9!
330
      this.display._renderFrame(animationProps);
×
331
      return;
×
332
    }
×
333

9✔
334
    // call callback
9✔
335
    this.props.onRender(this._getAnimationProps());
9✔
336
    // end callback
9✔
337

9✔
338
    // Submit commands (necessary on WebGPU)
9✔
339
    this.device?.submit();
9✔
340
  }
9✔
341

1✔
342
  _clearNeedsRedraw(): void {
1✔
343
    this._needsRedraw = false;
9✔
344
  }
9✔
345

1✔
346
  _setupFrame(): void {
1✔
347
    this._resizeViewport();
9✔
348
  }
9✔
349

1✔
350
  // Initialize the  object that will be passed to app callbacks
1✔
351
  _initializeAnimationProps(): void {
1✔
352
    const canvasContext = this.device?.getDefaultCanvasContext();
5✔
353
    if (!this.device || !canvasContext) {
5!
354
      throw new Error('loop');
×
355
    }
×
356

5✔
357
    const canvas = canvasContext?.canvas;
5✔
358
    const useDevicePixels = canvasContext.props.useDevicePixels;
5✔
359

5✔
360
    this.animationProps = {
5✔
361
      animationLoop: this,
5✔
362

5✔
363
      device: this.device,
5✔
364
      canvasContext,
5✔
365
      canvas,
5✔
366
      // @ts-expect-error Deprecated
5✔
367
      useDevicePixels,
5✔
368

5✔
369
      timeline: this.timeline,
5✔
370

5✔
371
      needsRedraw: false,
5✔
372

5✔
373
      // Placeholders
5✔
374
      width: 1,
5✔
375
      height: 1,
5✔
376
      aspect: 1,
5✔
377

5✔
378
      // Animation props
5✔
379
      time: 0,
5✔
380
      startTime: Date.now(),
5✔
381
      engineTime: 0,
5✔
382
      tick: 0,
5✔
383
      tock: 0,
5✔
384

5✔
385
      // Experimental
5✔
386
      _mousePosition: null // Event props
5✔
387
    };
5✔
388
  }
5✔
389

1✔
390
  _getAnimationProps(): AnimationProps {
1✔
391
    if (!this.animationProps) {
23!
392
      throw new Error('animationProps');
×
393
    }
×
394
    return this.animationProps;
23✔
395
  }
23✔
396

1✔
397
  // Update the context object that will be passed to app callbacks
1✔
398
  _updateAnimationProps(): void {
1✔
399
    if (!this.animationProps) {
14!
400
      return;
×
401
    }
×
402

14✔
403
    // Can this be replaced with canvas context?
14✔
404
    const {width, height, aspect} = this._getSizeAndAspect();
14✔
405
    if (width !== this.animationProps.width || height !== this.animationProps.height) {
14!
406
      this.setNeedsRedraw('drawing buffer resized');
×
407
    }
×
408
    if (aspect !== this.animationProps.aspect) {
14!
409
      this.setNeedsRedraw('drawing buffer aspect changed');
×
410
    }
×
411

14✔
412
    this.animationProps.width = width;
14✔
413
    this.animationProps.height = height;
14✔
414
    this.animationProps.aspect = aspect;
14✔
415

14✔
416
    this.animationProps.needsRedraw = this._needsRedraw;
14✔
417

14✔
418
    // Update time properties
14✔
419
    this.animationProps.engineTime = Date.now() - this.animationProps.startTime;
14✔
420

14✔
421
    if (this.timeline) {
14!
422
      this.timeline.update(this.animationProps.engineTime);
×
423
    }
×
424

14✔
425
    this.animationProps.tick = Math.floor((this.animationProps.time / 1000) * 60);
14✔
426
    this.animationProps.tock++;
14✔
427

14✔
428
    // For back compatibility
14✔
429
    this.animationProps.time = this.timeline
14!
430
      ? this.timeline.getTime()
×
431
      : this.animationProps.engineTime;
14✔
432
  }
14✔
433

1✔
434
  /** Wait for supplied device */
1✔
435
  async _initDevice() {
1✔
436
    this.device = await this.props.device;
5✔
437
    if (!this.device) {
5!
438
      throw new Error('No device provided');
×
439
    }
×
440
    this.canvas = this.device.getDefaultCanvasContext().canvas || null;
5!
441
    // this._createInfoDiv();
5✔
442
  }
5✔
443

1✔
444
  _createInfoDiv(): void {
1✔
445
    if (this.canvas && this.props.onAddHTML) {
×
446
      const wrapperDiv = document.createElement('div');
×
447
      document.body.appendChild(wrapperDiv);
×
448
      wrapperDiv.style.position = 'relative';
×
449
      const div = document.createElement('div');
×
450
      div.style.position = 'absolute';
×
451
      div.style.left = '10px';
×
452
      div.style.bottom = '10px';
×
453
      div.style.width = '300px';
×
454
      div.style.background = 'white';
×
455
      if (this.canvas instanceof HTMLCanvasElement) {
×
456
        wrapperDiv.appendChild(this.canvas);
×
457
      }
×
458
      wrapperDiv.appendChild(div);
×
459
      const html = this.props.onAddHTML(div);
×
460
      if (html) {
×
461
        div.innerHTML = html;
×
462
      }
×
463
    }
×
464
  }
×
465

1✔
466
  _getSizeAndAspect(): {width: number; height: number; aspect: number} {
1✔
467
    if (!this.device) {
14!
468
      return {width: 1, height: 1, aspect: 1};
×
469
    }
×
470
    // https://webglfundamentals.org/webgl/lessons/webgl-resizing-the-canvas.html
14✔
471
    const [width, height] = this.device?.getDefaultCanvasContext().getDevicePixelSize() || [1, 1];
14!
472

14✔
473
    // https://webglfundamentals.org/webgl/lessons/webgl-anti-patterns.html
14✔
474
    let aspect = 1;
14✔
475
    const canvas = this.device?.getDefaultCanvasContext().canvas;
14✔
476

14✔
477
    // @ts-expect-error
14✔
478
    if (canvas && canvas.clientHeight) {
14✔
479
      // @ts-expect-error
14✔
480
      aspect = canvas.clientWidth / canvas.clientHeight;
14✔
481
    } else if (width > 0 && height > 0) {
14!
482
      aspect = width / height;
×
483
    }
×
484

14✔
485
    return {width, height, aspect};
14✔
486
  }
14✔
487

1✔
488
  /** @deprecated Default viewport setup */
1✔
489
  _resizeViewport(): void {
1✔
490
    // TODO can we use canvas context to code this in a portable way?
14✔
491
    // @ts-expect-error Expose on canvasContext
14✔
492
    if (this.props.autoResizeViewport && this.device.gl) {
14!
493
      // @ts-expect-error Expose canvasContext
×
494
      this.device.gl.viewport(
×
495
        0,
×
496
        0,
×
497
        // @ts-expect-error Expose canvasContext
×
498
        this.device.gl.drawingBufferWidth,
×
499
        // @ts-expect-error Expose canvasContext
×
500
        this.device.gl.drawingBufferHeight
×
501
      );
×
502
    }
×
503
  }
14✔
504

1✔
505
  _beginFrameTimers() {
1✔
506
    this.frameRate.timeEnd();
9✔
507
    this.frameRate.timeStart();
9✔
508

9✔
509
    // Check if timer for last frame has completed.
9✔
510
    // GPU timer results are never available in the same
9✔
511
    // frame they are captured.
9✔
512
    // if (
9✔
513
    //   this._gpuTimeQuery &&
9✔
514
    //   this._gpuTimeQuery.isResultAvailable() &&
9✔
515
    //   !this._gpuTimeQuery.isTimerDisjoint()
9✔
516
    // ) {
9✔
517
    //   this.stats.get('GPU Time').addTime(this._gpuTimeQuery.getTimerMilliseconds());
9✔
518
    // }
9✔
519

9✔
520
    // if (this._gpuTimeQuery) {
9✔
521
    //   // GPU time query start
9✔
522
    //   this._gpuTimeQuery.beginTimeElapsedQuery();
9✔
523
    // }
9✔
524

9✔
525
    this.cpuTime.timeStart();
9✔
526
  }
9✔
527

1✔
528
  _endFrameTimers() {
1✔
529
    this.cpuTime.timeEnd();
9✔
530

9✔
531
    // if (this._gpuTimeQuery) {
9✔
532
    //   // GPU time query end. Results will be available on next frame.
9✔
533
    //   this._gpuTimeQuery.end();
9✔
534
    // }
9✔
535
  }
9✔
536

1✔
537
  // Event handling
1✔
538

1✔
539
  _startEventHandling() {
1✔
540
    if (this.canvas) {
5✔
541
      this.canvas.addEventListener('mousemove', this._onMousemove.bind(this));
5✔
542
      this.canvas.addEventListener('mouseleave', this._onMouseleave.bind(this));
5✔
543
    }
5✔
544
  }
5✔
545

1✔
546
  _onMousemove(event: Event) {
1✔
547
    if (event instanceof MouseEvent) {
×
548
      this._getAnimationProps()._mousePosition = [event.offsetX, event.offsetY];
×
549
    }
×
550
  }
×
551

1✔
552
  _onMouseleave(event: Event) {
1✔
553
    this._getAnimationProps()._mousePosition = null;
×
554
  }
×
555
}
1✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc