Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: fast loop using update #513

Merged
merged 1 commit into from
Nov 15, 2024
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
44 changes: 44 additions & 0 deletions examples/fastLoop.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// @ts-check

kaplay();

loadBean();

const interval = 0.001;
const delay = 1;

loop(interval, () => {
const bean = add([
sprite("bean"),
pos(rand(vec2(0), vec2(width(), height()))),
]);
wait(delay, () => {
destroy(bean);
});
}, -1, true);

const counter = add([
pos(10, 10),
text(""),
z(9999),
]);
add([
pos(counter.pos),
rect(counter.width, counter.height),
color(BLACK),
z(counter.z - 1),
{
update() {
this.width = counter.width;
this.height = counter.height;
}
}
])

var beanCount = 0;
onAdd(() => beanCount++);
onDestroy(() => beanCount--);
loop(0.1, () => {
const error = 100 * Math.abs((delay / interval) - beanCount) / (delay / interval);
counter.text = `${beanCount.toFixed().padStart(5)} beans\nerror: ${error.toFixed(2).padStart(5)}%`;
});
77 changes: 34 additions & 43 deletions src/components/misc/timer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,24 +8,32 @@ import type {
TimerController,
TweenController,
} from "../../types";
import type { KEventController } from "../../utils";
import { KEvent } from "../../utils";

/**
* The {@link timer `timer()`} component.
*
* @group Component Types
*/
export interface TimerComp extends Comp {
/**
* The maximum number of loops per frame allowed,
* to keep loops with sub-frame intervals from freezing the game.
*/
maxLoopsPerFrame: number
/**
* Run the callback after n seconds.
*/
wait(time: number, action?: () => void): TimerController;
/**
* Run the callback every n seconds.
*
* If waitFirst is false (the default), the function will
* be called once on the very next frame, and then loop like normal.
*
* @since v3000.0
*/
loop(time: number, action: () => void): KEventController;
loop(time: number, action: () => void, maxLoops?: number, waitFirst?: boolean): TimerController;
/**
* Tweeeeen! Note that this doesn't specifically mean tweening on this object's property, this just registers the timer on this object, so the tween will cancel with the object gets destroyed, or paused when obj.paused is true.
*
Expand All @@ -40,59 +48,42 @@ export interface TimerComp extends Comp {
): TweenController;
}

export function timer(): TimerComp {
export function timer(maxLoopsPerFrame: number = 1000): TimerComp {
return {
id: "timer",
wait(
this: GameObj<TimerComp>,
time: number,
action?: () => void,
): TimerController {
const actions: Function[] = [];

if (action) actions.push(action);
let t = 0;
maxLoopsPerFrame,
loop(this: GameObj<TimerComp>, time: number, action: () => void, count: number = -1, waitFirst: boolean = false): TimerController {
let t: number = waitFirst ? 0 : time;
let onEndEvents = new KEvent;
const ev = this.onUpdate(() => {
t += _k.app.state.dt;
if (t >= time) {
actions.forEach((f) => f());
ev.cancel();
for (let i = 0; t >= time && i < this.maxLoopsPerFrame; i++) {
if (count != -1) {
count--;
if (count < 0) {
ev.cancel();
onEndEvents.trigger();
return;
}
}
action();
t -= time;
}
});
})
return {
get paused() {
return ev.paused;
return ev.paused
},
set paused(p) {
ev.paused = p;
ev.paused = p
},
cancel: ev.cancel,
onEnd(action) {
actions.push(action);
},
then(action) {
this.onEnd(action);
return this;
},
};
onEnd: onEndEvents.add,
then(f) { onEndEvents.add(f); return this; }
}
},
loop(t: number, action: () => void): KEventController {
let curTimer: null | TimerController = null;
const newAction = () => {
// TODO: should f be execute right away as loop() is called?
curTimer = this.wait(t, newAction);
action();
};
curTimer = this.wait(0, newAction);
return {
get paused() {
return curTimer?.paused ?? false;
},
set paused(p) {
if (curTimer) curTimer.paused = p;
},
cancel: () => curTimer?.cancel(),
};
wait(this: GameObj<TimerComp>, time: number, action?: () => void): TimerController {
return this.loop(time, action ?? (() => { }), 1, true);
},
tween<V extends LerpValue>(
this: GameObj<TimerComp>,
Expand Down
4 changes: 2 additions & 2 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -953,7 +953,7 @@ export interface KAPLAYCtx<
*
* @group Components
*/
timer(): TimerComp;
timer(maxLoopsPerFrame?: number): TimerComp;
/**
* Make object unaffected by camera or parent object transforms, and render at last.
*
Expand Down Expand Up @@ -2758,7 +2758,7 @@ export interface KAPLAYCtx<
* ```
* @group Timer
*/
loop(t: number, action: () => void): KEventController;
loop(t: number, action: () => void, maxLoops?: number, waitFirst?: boolean): TimerController;
/**
* Play a piece of audio.
*
Expand Down