优化ArchetypeSystem的AND指令

This commit is contained in:
YHH
2025-09-30 15:08:33 +08:00
parent a07108a431
commit 0969d09da1

View File

@@ -1,6 +1,6 @@
import {Entity} from '../Entity'; import {Entity} from '../Entity';
import {ComponentType} from './ComponentStorage'; import {ComponentType} from './ComponentStorage';
import {BitMask64Data, ComponentTypeManager} from "../Utils"; import {BitMask64Data, BitMask64Utils, ComponentTypeManager} from "../Utils";
/** /**
* 原型标识符 * 原型标识符
@@ -128,6 +128,10 @@ export class ArchetypeSystem {
/** /**
* 查询包含指定组件组合的原型 * 查询包含指定组件组合的原型
*
* @param componentTypes 要查询的组件类型列表
* @param operation 查询操作类型:'AND'(包含所有)或 'OR'(包含任意)
* @returns 匹配的原型列表及实体总数
*/ */
public queryArchetypes(componentTypes: ComponentType[], operation: 'AND' | 'OR' = 'AND'): ArchetypeQueryResult { public queryArchetypes(componentTypes: ComponentType[], operation: 'AND' | 'OR' = 'AND'): ArchetypeQueryResult {
@@ -135,8 +139,12 @@ export class ArchetypeSystem {
let totalEntities = 0; let totalEntities = 0;
if (operation === 'AND') { if (operation === 'AND') {
// 生成查询的 BitMask
const queryMask = this.generateArchetypeId(componentTypes);
// 使用 BitMask 位运算快速判断原型是否包含所有指定组件
for (const archetype of this._allArchetypes) { for (const archetype of this._allArchetypes) {
if (this.archetypeContainsAllComponents(archetype, componentTypes)) { if (BitMask64Utils.hasAll(archetype.id, queryMask)) {
matchingArchetypes.push(archetype); matchingArchetypes.push(archetype);
totalEntities += archetype.entities.size; totalEntities += archetype.entities.size;
} }
@@ -254,18 +262,6 @@ export class ArchetypeSystem {
return archetype; return archetype;
} }
/**
* 检查原型是否包含所有指定组件
*/
private archetypeContainsAllComponents(archetype: Archetype, componentTypes: ComponentType[]): boolean {
for (const componentType of componentTypes) {
if (!archetype.componentTypes.includes(componentType)) {
return false;
}
}
return true;
}
/** /**
* 更新组件索引 * 更新组件索引
*/ */