| 1 | export class EcsWorld |
| 2 | { |
| 3 | constructor () |
| 4 | { |
| 5 | this.nextId = 1; |
| 6 | this.alive = new Set(); |
| 7 | this.stores = new Map(); |
| 8 | } |
| 9 | |
| 10 | entity () |
| 11 | { |
| 12 | const id = this.nextId++; |
| 13 | this.alive.add(id); |
| 14 | return id; |
| 15 | } |
| 16 | |
| 17 | destroy (id) |
| 18 | { |
| 19 | this.alive.delete(id); |
| 20 | for (const store of this.stores.values()) |
| 21 | { store.delete(id); } |
| 22 | } |
| 23 | |
| 24 | add (id, name, data) |
| 25 | { |
| 26 | let store = this.stores.get(name); |
| 27 | if (!store) |
| 28 | { |
| 29 | store = new Map(); |
| 30 | this.stores.set(name, store); |
| 31 | } |
| 32 | store.set(id, data); |
| 33 | return data; |
| 34 | } |
| 35 | |
| 36 | get (id, name) |
| 37 | { |
| 38 | return this.stores.get(name)?.get(id); |
| 39 | } |
| 40 | |
| 41 | has (id, name) |
| 42 | { |
| 43 | return this.stores.get(name)?.has(id) ?? false; |
| 44 | } |
| 45 | |
| 46 | remove (id, name) |
| 47 | { |
| 48 | this.stores.get(name)?.delete(id); |
| 49 | } |
| 50 | |
| 51 | query (...names) |
| 52 | { |
| 53 | const primary = this.stores.get(names[0]); |
| 54 | if (!primary) |
| 55 | { return []; } |
| 56 | |
| 57 | const results = []; |
| 58 | for (const [id, first] of primary) |
| 59 | { |
| 60 | if (!this.alive.has(id)) |
| 61 | { continue; } |
| 62 | |
| 63 | const record = { id, [names[0]]: first }; |
| 64 | let matched = true; |
| 65 | for (let i = 1; i < names.length; i++) |
| 66 | { |
| 67 | const component = this.get(id, names[i]); |
| 68 | if (!component) |
| 69 | { |
| 70 | matched = false; |
| 71 | break; |
| 72 | } |
| 73 | record[names[i]] = component; |
| 74 | } |
| 75 | if (matched) |
| 76 | { results.push(record); } |
| 77 | } |
| 78 | return results; |
| 79 | } |
| 80 | } |