Skip to content

Commit

Permalink
Validate componentIds used in prefab
Browse files Browse the repository at this point in the history
  • Loading branch information
sondresj committed Oct 9, 2021
1 parent 4f4f869 commit b06397f
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
11 changes: 11 additions & 0 deletions packages/piecs/src/Errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,14 @@ export class WorldNotInitializedError extends Error {
super('World not initialized')
}
}

export class PrefabricationError extends Error {
constructor(componentIds: number[], nextComponentId: number) {
super(`
Cannot prefabricate using componentIds that would conflict with existing componentIds.
Make sure you either prefabricate before generating componentIds with world.getNextComponentId(),
or prefabricate using componentIds generated by world.getNextComponentId().
Conflicting componentIds: [${componentIds.filter(id => id < nextComponentId).join(', ')}]
`)
}
}
11 changes: 9 additions & 2 deletions packages/piecs/src/World.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type { System, InsideWorld, OutsideWorld } from './types'
import type { InternalQuery, Query } from './Query'
import { createArchetype, InternalArchetype, transformArchetype, traverseArchetypeGraph, Archetype } from './Archetype'
import { createBitSet } from './collections/BitSet'
import { EntityDeletedError, EntityNotExistError, EntityUndefinedError, WorldNotInitializedError } from './Errors'
import { EntityDeletedError, EntityNotExistError, EntityUndefinedError, PrefabricationError, WorldNotInitializedError } from './Errors'

export class World implements OutsideWorld, InsideWorld {
private rootArchetype: InternalArchetype = createArchetype('root', createBitSet(255), null)
Expand Down Expand Up @@ -98,7 +98,14 @@ export class World implements OutsideWorld, InsideWorld {
}

prefabricate(componentIds: number[]): Archetype {
this.nextComponentId = Math.max(this.nextComponentId - 1, ...componentIds) + 1 >>> 0
const max = Math.max(...componentIds)
if (max >= this.nextComponentId) {
if (Math.min(...componentIds) < this.nextComponentId) {
throw new PrefabricationError(componentIds, this.nextComponentId)
}

this.nextComponentId = (max + 1) >>> 0
}
let archetype = this.rootArchetype

for (let i = 0, l = componentIds.length; i < l; i++) {
Expand Down

0 comments on commit b06397f

Please sign in to comment.