-
-
Notifications
You must be signed in to change notification settings - Fork 110
Expand file tree
/
Copy pathComponent.ts
More file actions
339 lines (283 loc) · 10.9 KB
/
Component.ts
File metadata and controls
339 lines (283 loc) · 10.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
import { entityExists, EntityId, getEntityComponents, Prefab } from './Entity'
import { queryAddEntity, queryCheckEntity, queryRemoveEntity } from './Query'
import { Query } from './Query'
import {
IsA,
Pair,
Wildcard,
getRelationTargets,
$relationData,
$isPairComponent,
$pairTarget,
$relation
} from './Relation'
import { createObservable, Observable } from './utils/Observer'
import { $internal, InternalWorld, World, WorldContext } from './World'
export const $default = Symbol.for('bitecs-default')
const $defaultParams = Symbol.for('bitecs-default-params')
/**
* Represents a reference to a component.
* @typedef {any} ComponentRef
*/
export type ComponentRef = any
/**
* Represents the data associated with a component.
* @interface ComponentData
* @property {number} id - The unique identifier for the component.
* @property {number} generationId - The generation ID of the component.
* @property {number} bitflag - The bitflag used for component masking.
* @property {ComponentRef} ref - Reference to the component.
* @property {Set<Query>} queries - Set of queries associated with the component.
* @property {Observable} setObservable - Observable for component changes.
*/
export interface ComponentData {
id: number
generationId: number
bitflag: number
ref: ComponentRef
queries: Set<Query>
setObservable: Observable
getObservable: Observable
}
/**
* Registers a component with the world.
* @param {World} world - The world object.
* @param {ComponentRef} component - The component to register.
* @returns {ComponentData} The registered component data.
* @throws {Error} If the component is null or undefined.
*/
export const registerComponent = (world: World, component: ComponentRef) => {
if (!component) {
throw new Error(`bitECS - Cannot register null or undefined component`)
}
const ctx = (world as InternalWorld)[$internal]
const queries = new Set<Query>()
const data: ComponentData = {
id: ctx.componentCount++,
generationId: ctx.entityMasks.length - 1,
bitflag: ctx.bitflag,
ref: component,
queries,
setObservable: createObservable(),
getObservable: createObservable(),
}
ctx.componentMap.set(component, data)
ctx.bitflag *= 2
if (ctx.bitflag >= 2 ** 31) {
ctx.bitflag = 1
ctx.entityMasks.push([])
}
return data
}
/**
* Registers multiple components with the world.
* @param {World} world - The world object.
* @param {ComponentRef[]} components - Array of components to register.
*/
export const registerComponents = (world: World, components: ComponentRef[]) => {
components.forEach((component) => registerComponent(world, component))
}
/**
* Checks if an entity has a specific component.
* @param {World} world - The world object.
* @param {number} eid - The entity ID.
* @param {ComponentRef} component - The component to check for.
* @returns {boolean} True if the entity has the component, false otherwise.
*/
export const hasComponent = (world: World, eid: EntityId, component: ComponentRef): boolean => {
const ctx = (world as InternalWorld)[$internal]
const registeredComponent = ctx.componentMap.get(component)
if (!registeredComponent) return false
const { generationId, bitflag } = registeredComponent
const mask = ctx.entityMasks[generationId][eid]
return (mask & bitflag) === bitflag
}
/**
* Retrieves the data associated with a component for a specific entity.
* @param {World} world - The world object.
* @param {EntityId} eid - The entity ID.
* @param {ComponentRef} component - The component to retrieve data for.
* @returns {any} The component data, or undefined if the component is not found or the entity doesn't have the component.
*/
export const getComponentData = (world: World, eid: EntityId, component: ComponentRef): any => {
const ctx = (world as InternalWorld)[$internal]
const componentData = ctx.componentMap.get(component)
if (!componentData) {
return undefined
}
if (!hasComponent(world, eid, component)) {
return undefined
}
// Notify observers that this component is being accessed
return componentData.getObservable.notify(eid)
}
/**
* Helper function to set component data.
* @param {ComponentRef} component - The component to set.
* @param {any} data - The data to set for the component.
* @returns {{ component: ComponentRef, data: any }} An object containing the component and its data.
*/
export const set = <T extends ComponentRef>(component: T, data: any): { component: T, data: any } => ({
component,
data
})
/**
* Recursvely inherits components from one entity to another.
* @param {World} world - The world object.
* @param {number} baseEid - The ID of the entity inheriting components.
* @param {number} inheritedEid - The ID of the entity being inherited from.
* @param {boolean} isFirstSuper - Whether this is the first super in the inheritance chain.
*/
const recursivelyInherit = (ctx: WorldContext, world: World, baseEid: EntityId, inheritedEid: EntityId, visited = new Set<EntityId>()): void => {
// Guard against circular inheritance
if (visited.has(inheritedEid)) return
visited.add(inheritedEid)
// Add IsA relation first
addComponent(world, baseEid, IsA(inheritedEid))
// Copy components and their data from this level
// This needs to happen before recursing to ancestors so closer ancestors take precedence
for (const component of getEntityComponents(world, inheritedEid)) {
// TODO: inherit reference vs copy
if (component === Prefab) continue
// Only add component if entity doesn't already have it
// This ensures closer ancestors take precedence
if (!hasComponent(world, baseEid, component)) {
addComponent(world, baseEid, component)
const componentData = ctx.componentMap.get(component)
if (componentData?.setObservable) {
const data = getComponentData(world, inheritedEid, component)
componentData.setObservable.notify(baseEid, data)
}
}
}
// Then recursively inherit from ancestors
// This ensures more distant ancestors don't override closer ones
for (const parentEid of getRelationTargets(world, inheritedEid, IsA)) {
recursivelyInherit(ctx, world, baseEid, parentEid, visited)
}
}
/**
* Represents a component with data to be set on an entity.
*/
type ComponentSetter<T = any> = { component: ComponentRef; data: T }
/**
* Adds one or more components to an entity.
* @param {World} world - The world object.
* @param {EntityId} eid - The entity ID.
* @param {...(ComponentRef | ComponentSetter)} components - Components to add or set.
* @throws {Error} If the entity does not exist in the world.
*/
export const addComponent = (world: World, eid: EntityId, ...components: (ComponentRef | ComponentSetter)[]): void => {
if (!entityExists(world, eid)) {
throw new Error(`Cannot add component - entity ${eid} does not exist in the world.`)
}
const ctx = (world as InternalWorld)[$internal]
components.forEach(componentOrSet => {
const component = 'component' in componentOrSet ? componentOrSet.component : componentOrSet
const data = 'data' in componentOrSet ? componentOrSet.data : undefined
if (!ctx.componentMap.has(component)) registerComponent(world, component)
setDefault(world, eid, component, componentOrSet[$defaultParams])
const componentData = ctx.componentMap.get(component)!
if (data !== undefined) {
componentData.setObservable.notify(eid, data)
}
if (hasComponent(world, eid, component)) return
const { generationId, bitflag, queries } = componentData
ctx.entityMasks[generationId][eid] |= bitflag
if (!hasComponent(world, eid, Prefab)) {
queries.forEach((queryData: Query) => {
queryData.toRemove.remove(eid)
const match = queryCheckEntity(world, queryData, eid)
if (match) queryAddEntity(queryData, eid)
else queryRemoveEntity(world, queryData, eid)
})
}
ctx.entityComponents.get(eid)!.add(component)
if (component[$isPairComponent]) {
const relation = component[$relation]
const target = component[$pairTarget]
// Add both Wildcard pairs for relation and target
addComponent(world, eid, Pair(relation, Wildcard))
addComponent(world, eid, Pair(Wildcard, target))
// For non-Wildcard targets, add Wildcard pair to track relation targets
if (typeof target === 'number') {
// Add Wildcard pair for target being a relation target
addComponent(world, target, Pair(Wildcard, relation))
// add target to a set to make autoRemoveSubject checks faster
ctx.entitiesWithRelations.add(target)
}
// add target to a set to make autoRemoveSubject checks faster
ctx.entitiesWithRelations.add(target)
const relationData = relation[$relationData]
if (relationData.exclusiveRelation === true && target !== Wildcard) {
const oldTarget = getRelationTargets(world, eid, relation)[0]
if (oldTarget !== undefined && oldTarget !== null && oldTarget !== target) {
removeComponent(world, eid, relation(oldTarget))
}
}
if (relation === IsA) {
const inheritedTargets = getRelationTargets(world, eid, IsA)
for (const inherited of inheritedTargets) {
recursivelyInherit(ctx, world, eid, inherited)
}
}
}
})
}
/**
* Alias for addComponent.
*/
export const addComponents = addComponent
/**
* Removes one or more components from an entity.
* @param {World} world - The world object.
* @param {number} eid - The entity ID.
* @param {...ComponentRef} components - Components to remove.
* @throws {Error} If the entity does not exist in the world.
*/
export const removeComponent = (world: World, eid: EntityId, ...components: ComponentRef[]) => {
const ctx = (world as InternalWorld)[$internal]
if (!entityExists(world, eid)) {
throw new Error(`Cannot remove component - entity ${eid} does not exist in the world.`)
}
components.forEach(component => {
if (!hasComponent(world, eid, component)) return
const componentNode = ctx.componentMap.get(component)!
const { generationId, bitflag, queries } = componentNode
ctx.entityMasks[generationId][eid] &= ~bitflag
queries.forEach((queryData: Query) => {
queryData.toRemove.remove(eid)
const match = queryCheckEntity(world, queryData, eid)
if (match) queryAddEntity(queryData, eid)
else queryRemoveEntity(world, queryData, eid)
})
ctx.entityComponents.get(eid)!.delete(component)
if (component[$isPairComponent]) {
const target = component[$pairTarget]
removeComponent(world, eid, Pair(Wildcard, target))
const relation = component[$relation]
const otherTargets = getRelationTargets(world, eid, relation)
if (otherTargets.length === 0) {
removeComponent(world, eid, Pair(relation, Wildcard))
}
}
})
}
/**
* Alias for removeComponent.
*/
export const removeComponents = removeComponent
export function Default(component: ComponentRef, params: any) {
return {
component,
[$defaultParams]: params
}
}
function setDefault(world: World, eid: EntityId, component: ComponentRef, params: any) {
if (component[$default] !== undefined) {
if (typeof component[$default] !== 'function') {
throw new Error(`${$default.toString()} must be a function. Got "${typeof component[$default]}".`)
}
component[$default](eid, params)
}
}