shrooms-vb-native/game.c

89 lines
2.2 KiB
C
Raw Normal View History

2024-10-22 00:52:51 +00:00
#include <audio.h>
#include <assets.h>
2024-10-20 04:08:37 +00:00
#include <controller.h>
2024-10-15 04:24:13 +00:00
#include <game.h>
#include <SDL2/SDL.h>
2024-10-19 22:04:15 +00:00
#include <stdbool.h>
2024-10-15 04:24:13 +00:00
#include <time.h>
int sleepNanos(long int ns) {
struct timespec time;
2024-10-20 01:05:56 +00:00
if (ns < 0) return 0;
2024-10-15 04:24:13 +00:00
time.tv_sec = ns / 1000000000;
time.tv_nsec = ns % 1000000000;
return nanosleep(&time, NULL);
}
2024-10-20 01:05:56 +00:00
long int tickNs() {
struct timespec time;
clock_gettime(CLOCK_MONOTONIC, &time);
return (time.tv_sec * 1000000000) + time.tv_nsec;
}
2024-10-15 04:24:13 +00:00
2024-10-19 22:04:15 +00:00
typedef struct {
GraphicsContext *gfx;
2024-10-22 00:52:51 +00:00
AudioContext aud;
int16_t audioBuffer[834 * 2];
2024-10-19 22:04:15 +00:00
} GameState;
int onFrame(VB *sim) {
static uint8_t leftEye[384*224];
static uint8_t rightEye[384*224];
GameState *state;
2024-10-22 00:52:51 +00:00
void *samples;
uint32_t samplePairs;
2024-10-19 22:04:15 +00:00
state = vbGetUserData(sim);
vbGetPixels(sim, leftEye, 1, 384, rightEye, 1, 384);
2024-10-22 00:52:51 +00:00
gfxUpdateLeftEye(state->gfx, leftEye);
gfxUpdateRightEye(state->gfx, rightEye);
samples = vbGetSamples(sim, NULL, &samplePairs);
audioUpdate(&state->aud, samples, samplePairs * 4);
vbSetSamples(sim, samples, 834);
gfxRender(state->gfx);
2024-10-19 22:04:15 +00:00
return 1;
}
#define MAX_STEP_CLOCKS 20000000
2024-10-15 04:24:13 +00:00
int runGame(VB *sim, GraphicsContext *gfx) {
2024-10-15 04:24:13 +00:00
uint32_t clocks;
SDL_Event event;
2024-10-19 22:04:15 +00:00
GameState state;
2024-10-20 04:08:37 +00:00
ControllerState ctrl;
2024-10-19 22:04:15 +00:00
uint64_t ticks, prevTicks;
state.gfx = gfx;
2024-10-22 00:52:51 +00:00
audioInit(&state.aud);
vbSetSamples(sim, &state.audioBuffer, 834);
2024-10-19 22:04:15 +00:00
vbSetUserData(sim, &state);
vbSetFrameCallback(sim, &onFrame);
2024-10-15 04:24:13 +00:00
2024-10-20 04:08:37 +00:00
ctrlInit(&ctrl);
gfxUpdateLeftEye(gfx, LEFT_EYE_DEFAULT);
gfxUpdateRightEye(gfx, RIGHT_EYE_DEFAULT);
2024-10-15 04:24:13 +00:00
while (1) {
clocks = MAX_STEP_CLOCKS;
2024-10-20 01:05:56 +00:00
prevTicks = tickNs();
2024-10-15 04:24:13 +00:00
vbEmulate(sim, &clocks);
2024-10-20 01:05:56 +00:00
ticks = tickNs();
2024-10-20 04:08:37 +00:00
sleepNanos(((MAX_STEP_CLOCKS - clocks) * 50) - (ticks - prevTicks));
2024-10-15 04:24:13 +00:00
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) {
return 0;
}
2024-10-20 04:08:37 +00:00
if (event.type == SDL_KEYDOWN) {
ctrlKeyDown(&ctrl, event.key.keysym.sym);
}
if (event.type == SDL_KEYUP) {
ctrlKeyUp(&ctrl, event.key.keysym.sym);
}
2024-10-15 04:24:13 +00:00
}
2024-10-20 04:08:37 +00:00
vbSetKeys(sim, ctrlKeys(&ctrl));
2024-10-15 04:24:13 +00:00
}
}