Skip to content

Commit 4bb508f

Browse files
authored
Merge pull request #382 from Jameskmonger/rs2-tasks
feat: create tick-based task system
2 parents 54bebc2 + 169bcfa commit 4bb508f

17 files changed

+1313
-5
lines changed

src/engine/task/README.md

Lines changed: 139 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,139 @@
1+
# Task system
2+
3+
The task system allows you to write content which will be executed on the tick cycles of the server.
4+
5+
You can configure a task to execute every `n` ticks (minimum of `1` for every tick), and you can also choose a number of other behaviours, such as whether the task should execute immediately or after a delay, as well as set to repeat indefinitely.
6+
7+
## Scheduling a task
8+
9+
You can schedule a task by registering it with a `TaskScheduler`.
10+
11+
The task in the example of below runs with an interval of `2`, i.e. it will be executed every 2 ticks.
12+
13+
```ts
14+
class MyTask extends Task {
15+
public constructor() {
16+
super({ interval: 2 });
17+
}
18+
19+
public execute(): void {
20+
console.log('2 ticks');
21+
}
22+
}
23+
24+
const scheduler = new TaskScheduler();
25+
26+
scheduler.addTask(new MyTask());
27+
28+
scheduler.tick();
29+
scheduler.tick(); // '2 ticks'
30+
```
31+
32+
Every two times that `scheduler.tick()` is called, it will run the `execute` function of your task.
33+
34+
## Task configuration
35+
36+
You can pass a `TaskConfig` object to the `Task` constructor in order to configure various aspects of your task.
37+
38+
### Timing
39+
40+
The most simple configuration option for a `Task` is the `interval` option. Your task will be executed every `interval` amount of ticks.
41+
42+
```ts
43+
/**
44+
* The number of ticks between each execution of the task.
45+
*/
46+
interval: number;
47+
```
48+
49+
For example, with an interval of `1`, your task will run every tick. The default value is `1`.
50+
51+
### Immediate execution
52+
53+
You can configure your task to execute immediately with the `immediate` option.
54+
55+
```ts
56+
/**
57+
* Should the task be executed on the first tick after it is added?
58+
*/
59+
immediate: boolean;
60+
```
61+
62+
For example, if `immediate` is `true` and `interval` is `5`, your task will run on the 1st and 6th ticks (and so on).
63+
64+
### Repeating
65+
66+
You can use the `repeat` option to tell your task to run forever.
67+
68+
```ts
69+
/**
70+
* Should the task be repeated indefinitely?
71+
*/
72+
repeat: boolean;
73+
```
74+
75+
You can use `this.stop()` inside the task to stop it from repeating further.
76+
77+
### Stacking
78+
79+
The `stackType` and `stackGroup` properties allow you to control how your task interacts with other, similar tasks.
80+
81+
```ts
82+
/**
83+
* How the task should be stacked with other tasks of the same stack group.
84+
*/
85+
stackType: TaskStackType;
86+
87+
/**
88+
* The stack group for this task.
89+
*/
90+
stackGroup: string;
91+
```
92+
93+
When `stackType` is set to `TaskStackType.NEVER`, other tasks with the same `stackGroup` will be stopped when your task is enqueued. A `stackType` of `TaskStackType.STACK` will allow your task to run with others of the same group.
94+
95+
The default type is `TaskStackType.STACK` and the group is `TaskStackGroup.ACTION` (`'action'`)
96+
97+
## Task Subtypes
98+
99+
Rather than extending `Task`, there are a number of subclasses you can extend which will give you some syntactic sugar around common functionality.
100+
101+
- `ActorTask`
102+
103+
This is the base task to be performed by an `Actor`. It will automatically listen to the actor's walking queue, and stop the task if it has a `breakType` of `ON_MOVE`.
104+
105+
- `ActorWalkToTask`
106+
107+
This task will make an actor walk to a `Position` or `LandscapeObject` and will expose the `atDestination` property for your extended task to query. You can then begin executing your task logic.
108+
109+
- `ActorLandscapeObjectInteractionTask`
110+
111+
This task extends `ActorWalkToTask` and will make an actor walk to a given `LandscapeObject`, before exposing the `landscapeObject` property for your task to use.
112+
113+
- `ActorWorldItemInteractionTask`
114+
115+
This task extends `ActorWalkToTask` and will make an actor walk to a given `WorldItem`, before exposing the `worldItem` property for your task to use.
116+
117+
# Future improvements
118+
119+
- Stalling executions for certain tasks when interface is open
120+
- should we create a `PlayerTask` to contain this behaviour? The `breakType` behaviour could be moved to this base, rather than `ActorTask`
121+
122+
- Consider refactoring this system to use functional programming patterns. Composition should be favoured over inheritance generally, and there are some examples of future tasks which may be easier if we could compose tasks from building blocks. Consider the implementation of some task which requires both a `LandscapeObject` and a `WorldItem` - we currently would need to create some custom task which borrowed behaviour from the `ActorLandscapeObjectInteractionTask` and `ActorWorldItemInteractionTask`. TypeScript mixins could be useful here.
123+
124+
# Content requiring conversion to task system
125+
126+
Highest priority is to convert pieces of content which make use of the old `task` system. These are:
127+
128+
- Magic attack
129+
- Magic teleports
130+
- Prayer
131+
- Combat
132+
- Forging (smithing)
133+
- Woodcutting
134+
135+
The following areas will make interesting use of the task system and would serve as a good demonstration:
136+
137+
- Health regen
138+
- NPC movement
139+
- Firemaking
Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
import { LandscapeObject } from '@runejs/filestore';
2+
import { activeWorld, Position } from '@engine/world';
3+
import { Actor } from '@engine/world/actor';
4+
import { ActorWalkToTask } from './actor-walk-to-task';
5+
6+
/**
7+
* A task for an actor to interact with a {@link LandscapeObject}.
8+
*
9+
* This task extends {@link ActorWalkToTask} and will walk the actor to the object.
10+
* Once the actor is within range of the object, the task will expose the {@link landscapeObject} property
11+
*
12+
* @author jameskmonger
13+
*/
14+
export abstract class ActorLandscapeObjectInteractionTask<TActor extends Actor = Actor> extends ActorWalkToTask<TActor, LandscapeObject> {
15+
private _landscapeObject: LandscapeObject;
16+
private _objectPosition: Position;
17+
18+
/**
19+
* Gets the {@link LandscapeObject} that this task is interacting with.
20+
*
21+
* @returns If the object is still present, and the actor is at the destination, the object.
22+
* Otherwise, `null`.
23+
*
24+
* TODO (jameskmonger) unit test this
25+
*/
26+
protected get landscapeObject(): LandscapeObject | null {
27+
// TODO (jameskmonger) consider if we want to do these checks rather than delegating to the child task
28+
// as currently the subclass has to store it in a subclass property if it wants to use it
29+
// without these checks
30+
if (!this.atDestination) {
31+
return null;
32+
}
33+
34+
if (!this._landscapeObject) {
35+
return null;
36+
}
37+
38+
return this._landscapeObject;
39+
}
40+
41+
/**
42+
* Get the position of this task's landscape object
43+
*
44+
* @returns The position of this task's landscape object, or null if the landscape object is not present
45+
*/
46+
protected get landscapeObjectPosition(): Position {
47+
if (!this._landscapeObject) {
48+
return null;
49+
}
50+
51+
return this._objectPosition;
52+
}
53+
54+
/**
55+
* @param actor The actor executing this task.
56+
* @param landscapeObject The landscape object to interact with.
57+
* @param sizeX The size of the LandscapeObject in the X direction.
58+
* @param sizeY The size of the LandscapeObject in the Y direction.
59+
*/
60+
constructor (
61+
actor: TActor,
62+
landscapeObject: LandscapeObject,
63+
sizeX: number = 1,
64+
sizeY: number = 1
65+
) {
66+
super(
67+
actor,
68+
landscapeObject,
69+
Math.max(sizeX, sizeY)
70+
);
71+
72+
if (!landscapeObject) {
73+
this.stop();
74+
return;
75+
}
76+
77+
// create the Position here to prevent instantiating a new Position every tick
78+
this._objectPosition = new Position(landscapeObject.x, landscapeObject.y, landscapeObject.level);
79+
this._landscapeObject = landscapeObject;
80+
}
81+
82+
/**
83+
* Checks for the continued presence of the {@link LandscapeObject} and stops the task if it is no longer present.
84+
*
85+
* TODO (jameskmonger) unit test this
86+
*/
87+
public execute() {
88+
super.execute();
89+
90+
if (!this.isActive || !this.atDestination) {
91+
return;
92+
}
93+
94+
if (!this._landscapeObject) {
95+
this.stop();
96+
return;
97+
}
98+
99+
const { object: worldObject } = activeWorld.findObjectAtLocation(this.actor, this._landscapeObject.objectId, this._objectPosition);
100+
101+
if (!worldObject) {
102+
this.stop();
103+
return;
104+
}
105+
}
106+
}

src/engine/task/impl/actor-task.ts

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
import { Subscription } from 'rxjs';
2+
import { Actor } from '@engine/world/actor';
3+
import { TaskBreakType, TaskConfig } from '../types';
4+
import { Task } from '../task';
5+
6+
/**
7+
* A task that is executed by an actor.
8+
*
9+
* If the task has a break type of ON_MOVE, the ActorTask will subscribe to the actor's
10+
* movement events and will stop executing when the actor moves.
11+
*
12+
* @author jameskmonger
13+
*/
14+
export abstract class ActorTask<TActor extends Actor = Actor> extends Task {
15+
/**
16+
* A function that is called when a movement event is queued on the actor.
17+
*
18+
* This will be `null` if the task does not break on movement.
19+
*/
20+
private walkingQueueSubscription: Subscription | null = null;
21+
22+
/**
23+
* @param actor The actor executing this task.
24+
* @param config The task configuration.
25+
*/
26+
constructor(
27+
protected readonly actor: TActor,
28+
config?: TaskConfig
29+
) {
30+
super(config);
31+
32+
this.listenForMovement();
33+
}
34+
35+
/**
36+
* Called when the task is stopped and unsubscribes from the actor's walking queue if necessary.
37+
*
38+
* TODO (jameskmonger) unit test this
39+
*/
40+
public onStop(): void {
41+
if (this.walkingQueueSubscription) {
42+
this.walkingQueueSubscription.unsubscribe();
43+
}
44+
}
45+
46+
/**
47+
* If required, listen to the actor's walking queue to stop the task
48+
*
49+
* This function uses `setImmediate` to ensure that the subscription to the
50+
* walking queue is not created
51+
*
52+
* TODO (jameskmonger) unit test this
53+
*/
54+
private listenForMovement(): void {
55+
if (!this.breaksOn(TaskBreakType.ON_MOVE)) {
56+
return;
57+
}
58+
59+
setImmediate(() => {
60+
this.walkingQueueSubscription = this.actor.walkingQueue.movementQueued$.subscribe(() => {
61+
this.stop();
62+
});
63+
});
64+
}
65+
}

0 commit comments

Comments
 (0)