import {expect, test} from 'vitest'; import Ecs from './ecs.js'; import {wrapComponents} from './test-helper.js'; import Query from './query.js'; const Components = wrapComponents([ ['A', {a: {type: 'int32', defaultValue: 64}}], ['B', {b: {type: 'int32', defaultValue: 32}}], ['C', {c: {type: 'int32'}}], ]); const ecsTest = test.extend({ ecs: async ({}, use) => { const ecs = new Ecs({Components}); await ecs.createManySpecific([ [1, {B: {}}], [2, {A: {}, B: {}, C: {}}], [3, {A: {}}], [4, {C: {}}], ]); await use(ecs); }, }); async function testQuery(ecs, parameters, expected) { const query = new Query(parameters, ecs); query.reindex([1, 2, 3]); expect(query.count) .to.equal(expected.length); for (const _ of query.select()) { expect(expected.includes(_.id)) .to.equal(true); } } ecsTest('can query all', async ({ecs}) => { await testQuery(ecs, [], [1, 2, 3]); }); ecsTest('can query some', async ({ecs}) => { await testQuery(ecs, ['A'], [2, 3]); await testQuery(ecs, ['A', 'B'], [2]); }); ecsTest('can query excluding', async ({ecs}) => { await testQuery(ecs, ['!A'], [1]); await testQuery(ecs, ['A', '!B'], [3]); }); ecsTest('can deindex', async ({ecs}) => { const query = new Query(['A'], ecs); query.reindex([1, 2, 3]); expect(query.count) .to.equal(2); query.deindex([2]); expect(query.count) .to.equal(1); }); ecsTest('can reindex', async ({ecs}) => { const query = new Query(['B'], ecs); query.reindex([1, 2]); expect(query.count) .to.equal(2); ecs.destroyMany(new Set([2])); query.reindex([1, 2]); expect(query.count) .to.equal(1); }); ecsTest('can select', async ({ecs}) => { const query = new Query(['A'], ecs); query.reindex([1, 2, 3]); const it = query.select(); const {value: {A}} = it.next(); expect(A.a) .to.equal(64); });