]> git.r.bdr.sh - rbdr/lissajous/blob - lib/main.js
60189578f817e292f9d1745c9a8e7ecb60d15607
[rbdr/lissajous] / lib / main.js
1 import Serpentity from '@serpentity/serpentity';
2 import { canvasId, settingsId, fps } from './config';
3
4 // Systems
5 import CameraRotator from './systems/camera_rotator';
6 import WebGLRenderer from './systems/webgl_renderer';
7 import LissajousPositionUpdater from './systems/lissajous_position_updater';
8 import CameraAdjuster from './systems/camera_adjuster';
9 import FrequencyAdjuster from './systems/frequency_adjuster';
10 import AmplitudeAdjuster from './systems/amplitude_adjuster';
11 import GlobalAdjuster from './systems/global_adjuster';
12
13 // Factories
14 import { lissajousCurve } from './factories/curves';
15 import { camera, configuration } from './factories/global';
16
17 const internals = {
18
19 // State variables
20
21 started: false,
22 currentTime: 0,
23 engine: null,
24
25 load() {
26 // Create entities
27 const engine = new Serpentity();
28
29 // Add Entities
30 engine.addEntity(camera());
31 engine.addEntity(lissajousCurve());
32 engine.addEntity(configuration());
33
34 // Select elements
35 const canvas = document.getElementById(canvasId);
36 const settings = document.getElementById(settingsId);
37
38 // Add Systems
39 engine.addSystem(new CameraRotator());
40 engine.addSystem(new LissajousPositionUpdater());
41 engine.addSystem(new WebGLRenderer(canvas));
42
43 // IMPROVEMENT NOTE: I believe adjusters can be generalized further.
44 // We could potentially have a factory for this.
45 engine.addSystem(new GlobalAdjuster(settings));
46 engine.addSystem(new CameraAdjuster(settings));
47 engine.addSystem(new FrequencyAdjuster(settings));
48 engine.addSystem(new AmplitudeAdjuster(settings));
49
50 internals.engine = engine;
51 },
52
53 unload() {
54 internals.engine = null;
55 },
56
57 run(time) {
58
59 const delta = time - internals.currentTime;
60 const interval = 1000 / fps;
61
62 if (delta >= interval) {
63 internals.engine.update(delta);
64 internals.currentTime = time;
65 }
66
67 internals.started && window.requestAnimationFrame(internals.run);
68 },
69
70 start() {
71 if (!internals.started) {
72 internals.started = true;
73 internals.load();
74 window.requestAnimationFrame(internals.run);
75 }
76 },
77
78 stop() {
79 if (internals.started) {
80 internals.started = false;
81 internals.unload();
82 }
83 }
84 };
85
86 internals.start();