]> git.r.bdr.sh - rbdr/sumo/blob - lib/systems/render.js
8bfa4bf0a2d5c11c7e4be39cc17514417e2b083f
[rbdr/sumo] / lib / systems / render.js
1 import { System } from '@serpentity/serpentity';
2
3 import RenderableNode from '../nodes/renderable';
4
5 const internals = {
6 kNoPixiError: 'No pixi application passed to render system. Make sure you set the `application` key in the config object when initializing.'
7 };
8
9 /**
10 * Renders renderable objects using pixi
11 *
12 * @extends {external:Serpentity.System}
13 * @class RenderSystem
14 * @param {object} config a configuration object to extend.
15 */
16 export default class RenderSystem extends System {
17
18 constructor(config = {}) {
19
20 super();
21
22 /**
23 * The node collection of renderable entities
24 *
25 * @property {external:Serpentity.NodeCollection} renderables
26 * @instance
27 * @memberof RenderSystem
28 */
29 this.renderables = null;
30
31 /**
32 * The pixi engine we will use to render
33 *
34 * @property {external:PixiJs.Application} application
35 * @instance
36 * @memberof RenderSystem
37 */
38 this.application = config.application;
39
40 if (!this.application) {
41 throw new Error(internals.kNoPixiError);
42 }
43 }
44
45 /**
46 * Initializes system when added. Requests renderable nodes and
47 * attaches to event listeners to add / remove them to pixi stage
48 *
49 * @function added
50 * @memberof RenderSystem
51 * @instance
52 * @param {external:Serpentity.Engine} engine the serpentity engine to
53 * which we are getting added
54 */
55 added(engine) {
56
57 this.renderables = engine.getNodes(RenderableNode);
58 this.renderables.on('nodeAdded', (event) => {
59
60 this.application.stage.addChild(event.node.container.container);
61 });
62 this.renderables.on('nodeRemoved', (event) => {
63
64 this.application.stage.removeChild(event.node.container.container);
65 });
66 }
67
68 /**
69 * Clears system resources when removed.
70 *
71 * @function removed
72 * @instance
73 * @memberof RenderSystem
74 */
75 removed() {
76
77 this.renderables.removeAllListeners('nodeAdded');
78 this.renderables.removeAllListeners('nodeRemoved');
79 this.renderables = null;
80 }
81
82 /**
83 * Runs on every update of the loop. Does nothing.
84 *
85 * @function update
86 * @instance
87 * @param {Number} currentFrameDuration the duration of the current
88 * frame
89 * @memberof RenderSystem
90 */
91 update(currentFrameDuration) {
92
93 this.application.render();
94 }
95 }