Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 24 additions & 2 deletions packages/app/src/app.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/** @import { SystemConfig, SystemGroupConfig, ScheduleConfig } from '@wimaengine/schedule' */
/** @import { CrossWorldScheduleConfig, CrossWorldSystemConfig, ScheduleConfig, SystemConfig, SystemGroupConfig } from '@wimaengine/schedule' */
/** @import { Constructor,TypeId } from '@wimaengine/type'*/

import { World, ComponentHooks } from '@wimaengine/ecs'
Expand All @@ -7,7 +7,7 @@ import { Scheduler, SchedulerBuilder } from '@wimaengine/schedule'
import { typeid } from '@wimaengine/type'
import { Worlds } from './worlds'

const registererror = 'Schedules, system groups, systems, plugins, worlds, resource aliases or resources should be registered or set before `App().run()`'
const registererror = 'Schedules, crossworld schedules, system groups, systems, crossworld systems, plugins, worlds, resource aliases or resources should be registered or set before `App().run()`'

export class PluginRegistry {

Expand Down Expand Up @@ -166,6 +166,17 @@ export class App {
return this
}

/**
* @param {CrossWorldScheduleConfig} config
*/
registerCrossWorldSchedule(config) {
assertTrue(!this.initialized, registererror)

SchedulerBuilder.Instance.addCrossWorldSchedule(config)

return this
}

/**
* @param {import('@wimaengine/schedule').Runner} runner
*/
Expand Down Expand Up @@ -232,6 +243,17 @@ export class App {
return this
}

/**
* @param {CrossWorldSystemConfig} config
*/
registerCrossworldSystem(config) {
assertTrue(!this.initialized, registererror)

SchedulerBuilder.Instance.addCrossworldSystem(config)

return this
}

/**
* @param {SystemGroupConfig} config
*/
Expand Down
42 changes: 39 additions & 3 deletions packages/core/src/core/runner.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,21 @@ import { typeid } from '@wimaengine/type'
*/
export function defaultRunner(scheduler, worlds) {

/** @type {Map<string, { active: boolean, nextRunAt: number }>} */
const crossWorldState = new Map()

/** @type {Map<string, { active: boolean, nextRunAt: number }>} */
const state = new Map()

const now = performance.now()

for (const executable of scheduler.crossWorldValues()) {
crossWorldState.set(executable.typeId, {
active: true,
nextRunAt: now + executable.delay
})
}

for (const executable of scheduler.values()) {
state.set(executable.typeId, {
active: true,
Expand All @@ -20,16 +30,42 @@ export function defaultRunner(scheduler, worlds) {
}

const update = (/** @type {number} */ time) => {
for (const executable of scheduler.crossWorldValues()) {
const execState = crossWorldState.get(executable.typeId)

if (!execState || !execState.active) continue

if (time >= execState.nextRunAt) {
const targetTypeId = typeid(executable.world)
const targetWorld = worlds.get(targetTypeId)

assert(targetWorld, `The world \`${targetTypeId}\` does not exist.`)

const sourceTypeId = typeid(executable.sourceWorld)
const sourceWorld = worlds.get(sourceTypeId)

assert(sourceWorld, `The source world \`${sourceTypeId}\` does not exist.`)

executable.schedule.run(targetWorld, sourceWorld, executable.errorHandler)

if (executable.repeat) {
execState.nextRunAt = time + executable.delay
} else {
execState.active = false
}
}
}

for (const executable of scheduler.values()) {
const execState = state.get(executable.typeId)

if (!execState || !execState.active) continue

if (time >= execState.nextRunAt) {
const typeId = typeid(executable.world)
const world = worlds.get(typeId)
const targetTypeId = typeid(executable.world)
const world = worlds.get(targetTypeId)

assert(world, `The world \`${typeId}\` does not exist.`)
assert(world, `The world \`${targetTypeId}\` does not exist.`)

executable.schedule.run(world, executable.errorHandler)

Expand Down
85 changes: 85 additions & 0 deletions packages/core/tests/defaultRunner.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import { strictEqual, deepStrictEqual } from 'node:assert'
import { afterEach, describe, test, vi } from 'vitest'
import { World } from '@wimaengine/ecs'
import { typeid } from '@wimaengine/type'
import { CrossWorldSchedule, Executable, Scheduler } from '@wimaengine/schedule'
import { defaultRunner } from '../src/core/runner.js'

class TargetWorld { }
class SourceWorld { }
class NormalSchedule { }
class CrossWorldScheduleLabel { }

describe('Testing `defaultRunner`', () => {
afterEach(() => {
vi.unstubAllGlobals()
vi.restoreAllMocks()
})

test('runs crossworld schedules before normal schedules', () => {
const scheduler = new Scheduler()
const targetWorld = new World()
const sourceWorld = new World()
const worlds = new Map([
[typeid(TargetWorld), targetWorld],
[typeid(SourceWorld), sourceWorld]
])
/** @type {string[]} */
const order = []
/** @type {((time: number) => void)[]} */
const frames = []

scheduler.set(new Executable({
label: NormalSchedule,
repeat: false,
world: TargetWorld
}))
scheduler.setCrossWorld(new Executable({
label: CrossWorldScheduleLabel,
repeat: false,
schedule: new CrossWorldSchedule(),
world: TargetWorld,
sourceWorld: SourceWorld
}))

const normalSchedule = scheduler.get(NormalSchedule)
if (!normalSchedule) {
throw new Error('The normal schedule was not created.')
}

normalSchedule.add(() => {
order.push('normal')
})

const crossWorldSchedule = scheduler.getCrossWorld(CrossWorldScheduleLabel)
if (!crossWorldSchedule) {
throw new Error('The crossworld schedule was not created.')
}

crossWorldSchedule.add((target, source) => {
strictEqual(target, targetWorld)
strictEqual(source, sourceWorld)
order.push('crossworld')
})

vi.stubGlobal('performance', {
now: () => 0
})
vi.stubGlobal('requestAnimationFrame', (callback) => {
frames.push(callback)
return 0
})

defaultRunner(scheduler, worlds)

const frame = frames.shift()

if (!frame) {
throw new Error('The animation frame callback was not scheduled.')
}

frame(0)

deepStrictEqual(order, ['crossworld', 'normal'])
})
})
71 changes: 71 additions & 0 deletions packages/schedule/src/core/crossworldschedule.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
/** @import { CrossWorldSystemFunc } from './crossworldsystem' */
/** @import { SystemId } from '@wimaengine/ecs' */
/** @import { World } from '@wimaengine/ecs' */

import { Bitset } from '@wimaengine/datastructures'
import { World as EcsWorld } from '@wimaengine/ecs'

/**
* Stores a collection of crossworld systems which are in order.
*
* Crossworld systems receive both the target world and the source world.
*/
export class CrossWorldSchedule {

/**
* @private
* @type {CrossWorldSystemFunc[]}
*/
systems = []

/**
* @private
* @type {Bitset}
*/
condition = new Bitset()

/**
* @param {CrossWorldSystemFunc} system
* @returns {SystemId}
*/
add(system) {
const { length } = this.systems

this.systems.push(system)
this.condition.resize(length + 1)
this.condition.set(length)

return length
}

/**
* @param {World} targetWorld
* @param {World} sourceWorld
* @param {(error: Error, world: EcsWorld) => void} [errorHandler]
*/
run(targetWorld, sourceWorld, errorHandler) {
const handler = errorHandler ?? defaultErrorHandler

for (let i = 0; i < this.systems.length; i++) {
try {
if (this.condition.get(i)) this.systems[i](targetWorld, sourceWorld)
} catch(error) {
if (error instanceof Error) {
handler(error, targetWorld)
} else if (typeof error === 'string') {
handler(new Error(error), targetWorld)
} else {
handler(new Error(String(error)), targetWorld)
}
}
}
}
}

/**
* @param {Error} error
* @throws {Error}
*/
function defaultErrorHandler(error) {
throw error
}
9 changes: 9 additions & 0 deletions packages/schedule/src/core/crossworldsystem.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/** @import { World } from '@wimaengine/ecs' */

/**
* @callback CrossWorldSystemFunc
* @param {World} targetWorld
* @param {World} sourceWorld
* @returns {void}
*/
export {}
27 changes: 22 additions & 5 deletions packages/schedule/src/core/executable.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,21 @@ import { typeid } from '@wimaengine/type'
import { Schedule } from './schedule'

/**
* @template ScheduleType
* @template {import('@wimaengine/type').Constructor | undefined} SourceWorldType
* @typedef {{
* label: import('@wimaengine/type').Constructor,
* repeat?: boolean,
* delay?: number,
* errorHandler?: (error: Error, world: World) => void,
* defaultSystemGroup?: import('@wimaengine/type').Constructor,
* world: import('@wimaengine/type').Constructor
* world: import('@wimaengine/type').Constructor,
* sourceWorld: SourceWorldType,
* schedule: ScheduleType
* }} ExecutableConfig
*
*/

/**
* @typedef {{
* label: import('@wimaengine/type').Constructor,
* repeat?: boolean,
Expand All @@ -26,6 +32,9 @@ import { Schedule } from './schedule'
* This is the binding between a labeled {@link Schedule schedule}
* and its runtime configuration.
*
* @template ScheduleType
* @template {import('@wimaengine/type').Constructor | undefined} SourceWorldType
*
* @example
* ```ts
* function helloWorld(){
Expand Down Expand Up @@ -57,9 +66,9 @@ export class Executable {

/**
* @readonly
* @type {Schedule}
* @type {ScheduleType}
*/
schedule = new Schedule()
schedule

/**
* @readonly
Expand All @@ -85,14 +94,20 @@ export class Executable {
*/
world

/**
* @readonly
* @type {SourceWorldType}
*/
sourceWorld

/**
* @readonly
* @type {((error: Error, world: World) => void) | undefined}
*/
errorHandler

/**
* @param {ExecutableConfig} config
* @param {ExecutableConfig<ScheduleType, SourceWorldType>} config
*/
constructor(config) {
this.label = config.label
Expand All @@ -101,6 +116,8 @@ export class Executable {
this.errorHandler = config.errorHandler
this.defaultSystemGroup = config.defaultSystemGroup
this.world = config.world
this.sourceWorld = config.sourceWorld
this.schedule = /** @type {ScheduleType} */ (config.schedule ?? new Schedule())
}

/**
Expand Down
2 changes: 2 additions & 0 deletions packages/schedule/src/core/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
export * from './schedule'
export * from './crossworldsystem'
export * from './crossworldschedule'
export * from './scheduler'
export * from './executable'
export * from './schedulerbuilder'
Expand Down
Loading