]> git.r.bdr.sh - rbdr/serpentity/blob - lib/serpentity/node_collection.js
e6150201afb82ced47171ae8af76daf1709f3b8f
[rbdr/serpentity] / lib / serpentity / node_collection.js
1 import Events from 'events';
2
3 /*
4 * Node Collections contain nodes, in order to keep the lists of nodes
5 * that belong to each type.
6 *
7 * It has a type which is the class name of the node, and an array of
8 * instances of that class.
9 */
10
11 export class NodeCollection extends Events {
12
13 constructor(config) {
14
15 super();
16
17 this.nodes = [];
18 this.type = null;
19
20 Object.assign(this, config);
21 }
22
23 /*
24 * Creates a node for an entity if it matches, and adds it to the
25 * node list.
26 *
27 * Returns true if added, false otherwise.
28 */
29 add(entity) {
30
31 if (this.type.matches(entity) && !this._entityExists(entity)) {
32
33 const node = new this.type({});
34 const types = this.type.types;
35 const typeNames = Object.keys(types);
36
37 node.entity = entity;
38
39 for (const typeName of typeNames) {
40 node[typeName] = entity.getComponent(types[typeName]);
41 }
42
43 this.nodes.push(node);
44 this.emit('nodeAdded', { node });
45
46 return true;
47 }
48
49 return false;
50 }
51
52 /*
53 * Removes an entity by removing its related node from the list of nodes
54 *
55 * returns true if it was removed, false otherwise.
56 */
57 remove(entity) {
58
59 let foundIndex = -1;
60 let foundNode = null;
61
62 const found = this.nodes.some((node, i) => {
63
64 if (node.entity === entity) {
65 foundIndex = i;
66 foundNode = node;
67 return true;
68 }
69 });
70
71 if (found) {
72 this.nodes.splice(foundIndex, 1);
73 this.emit('nodeRemoved', { node: foundNode });
74 }
75
76 return found;
77 }
78
79 /*
80 * Checks whether we already have nodes for this entity.
81 */
82 _entityExists(entity) {
83
84 let found = false;
85
86 for (const node of this.nodes) {
87 if (node.entity === entity) {
88 found = true;
89 }
90 }
91
92 return found;
93 }
94 }
95
96
97 /*
98 * Make the node collection iterable without returning the array directly
99 */
100 NodeCollection.prototype[Symbol.iterator] = function * () {
101
102 yield* this.nodes;
103 };