all repos — mgba @ 327c3e78c6f3b4efb60a79c77e36c376754d2085

mGBA Game Boy Advance Emulator

src/core/timing.c (view raw)

 1/* Copyright (c) 2013-2016 Jeffrey Pfau
 2 *
 3 * This Source Code Form is subject to the terms of the Mozilla Public
 4 * License, v. 2.0. If a copy of the MPL was not distributed with this
 5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 6#include "timing.h"
 7
 8void mTimingInit(struct mTiming* timing, int32_t* relativeCycles, int32_t* nextEvent) {
 9	timing->root = NULL;
10	timing->masterCycles = 0;
11	timing->relativeCycles = relativeCycles;
12	timing->nextEvent = nextEvent;
13}
14
15void mTimingDeinit(struct mTiming* timing) {
16}
17
18void mTimingClear(struct mTiming* timing) {
19	timing->root = NULL;
20	timing->masterCycles = 0;
21}
22
23void mTimingSchedule(struct mTiming* timing, struct mTimingEvent* event, int32_t when) {
24	int32_t nextEvent = when + *timing->relativeCycles;
25	event->when = nextEvent + timing->masterCycles;
26	if (nextEvent < *timing->nextEvent) {
27		*timing->nextEvent = nextEvent;
28	}
29	struct mTimingEvent** previous = &timing->root;
30	struct mTimingEvent* next = timing->root;
31	while (next) {
32		int32_t nextWhen = next->when - timing->masterCycles;
33		if (nextWhen > when) {
34			break;
35		}
36		previous = &next->next;
37		next = next->next;
38	}
39	event->next = next;
40	*previous = event;
41}
42
43void mTimingDeschedule(struct mTiming* timing, struct mTimingEvent* event) {
44	struct mTimingEvent** previous = &timing->root;
45	struct mTimingEvent* next = timing->root;
46	while (next) {
47		if (next == event) {
48			*previous = next->next;
49			return;
50		}
51		previous = &next->next;
52		next = next->next;
53	}
54}
55
56int32_t mTimingTick(struct mTiming* timing, int32_t cycles) {
57	timing->masterCycles += cycles;
58	uint32_t masterCycles = timing->masterCycles;
59	while (timing->root) {
60		struct mTimingEvent* next = timing->root;
61		int32_t nextWhen = next->when - masterCycles;
62		if (nextWhen > 0) {
63			return nextWhen;
64		}
65		timing->root = next->next;
66		next->callback(timing, next->context, -nextWhen);
67	}
68	return *timing->nextEvent;
69}
70
71int32_t mTimingCurrentTime(struct mTiming* timing) {
72	return timing->masterCycles + *timing->relativeCycles;
73}
74
75int32_t mTimingNextEvent(struct mTiming* timing) {
76	struct mTimingEvent* next = timing->root;
77	if (!next) {
78		return INT_MAX;
79	}
80	return next->when - timing->masterCycles;
81}