File size: 1,532 Bytes
0b12ad4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import {
  Clock
} from 'https://unpkg.com/[email protected]/build/three.module.js';
import {
  createCamera
} from '../components/camera.js';

const clock = new Clock();

class Loop {
  constructor(camera, scene, renderer, faceTracker) {
    this.camera = camera;
    this.cameraPosition = [0, 0, 0.5];
    this.fov = 43.6;
    this.aspectRatio = 1;
    this.scene = scene;
    this.lastUpdate = 0;
    this.renderer = renderer;
    this.faceTracker = faceTracker;
    this.canvas = document.createElement('canvas')
    this.updatables = [];
  }

  async init() {
    await this.faceTracker.init();
  }

  async updateCameraParameters() {
    const timestamp = Date.now();
    if (timestamp - this.lastUpdate > 30) {
      const result = await this.faceTracker.getCameraParameters();
      if (result !== null) {
        const [cameraPosition, fov] = result;
        this.cameraPosition = cameraPosition;
        this.fov = fov;
        this.lastUpdate = Date.now();
      }
    }
  }

  setAspectRatio(ar) {
    this.aspectRatio = ar;
  }

  start() {
    this.renderer.setAnimationLoop(() => {
      this.updateCameraParameters().then(() => {
        this.camera = createCamera(this.cameraPosition, this.fov, this.aspectRatio);
        this.tick();
        this.renderer.render(this.scene, this.camera);
      });
    });
  }

  stop() {
    this.renderer.setAnimationLoop(null);
  }

  tick() {
    const delta = clock.getDelta();
    for (const object of this.updatables) {
      object.tick(delta);
    }
  }
}

export {
  Loop
};