summaryrefslogtreecommitdiff
path: root/src/platform_sdl.c
blob: f6bc08e868b199a41672ea5d57bb4691b02e6e31 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
#include "platform_sdl.h"

#include "game.h"

#include <stdbool.h>
#include <stdio.h>
#include <time.h>

#ifndef MAP_ANONYMOUS
#define MAP_ANONYMOUS MAP_ANON
#endif

extern bool PAUSED;

static struct SDLOffscreenBuffer global_back_buffer;


struct SDLWindowDimension sdl_get_window_dimension(SDL_Window *window)
{
    struct SDLWindowDimension result;
    SDL_GetWindowSize(window, &result.width, &result.height);
    return(result);
}


void sdl_resize_texture(struct SDLOffscreenBuffer *buffer, SDL_Renderer *renderer, int width, int height)
{
    if (buffer->memory)
    {
        free(buffer->memory);
    }

    if (buffer->texture)
    {
        SDL_DestroyTexture(buffer->texture);
    }

    buffer->texture = SDL_CreateTexture(
            renderer,
            SDL_PIXELFORMAT_ARGB8888,
            SDL_TEXTUREACCESS_STREAMING,
            width, height);

    buffer->width = width;
    buffer->height = height;
    buffer->pitch = width * BYTES_PER_PIXEL;

    buffer->memory = malloc(width * height * BYTES_PER_PIXEL);
}


void sdl_update_window(SDL_Renderer *renderer, struct SDLOffscreenBuffer *buffer)
{
    if (SDL_UpdateTexture(buffer->texture, 0, buffer->memory, buffer->pitch))
    {
        // TODO(amin): Handle this error
    }

    SDL_RenderCopy(renderer, buffer->texture, 0, 0);
    SDL_RenderPresent(renderer);
}


void clear_screen(struct SDLOffscreenBuffer *buffer, uint32_t pixel_value)
{
    // NOTE(amin): Memset is faster than nested for loops, but can only set
    // pixels to single byte values
    memset(buffer->memory, pixel_value, buffer->height * buffer->width * BYTES_PER_PIXEL);
}


// TODO: make the deadzone circular
float sdl_process_controller_axis_value(int16_t value, int16_t deadzone_threshold)
{
    float result = 0.0;
    if (value < -deadzone_threshold)
    {
        result = (float)(value + deadzone_threshold) / (32768.0f - deadzone_threshold);
    }
    else if (value > deadzone_threshold)
    {
        result = (float)(value - deadzone_threshold) / (32767.0f - deadzone_threshold);
    }
    return result;
}


bool sdl_handle_event(SDL_Event *event, struct GameControllerInput *controller_input)
{
    if (!event || !controller_input)
    {
        return true;
    }

    bool should_quit = false;

    switch(event->type)
    {
        case SDL_QUIT:
        {
            printf("SDL_QUIT\n");
            should_quit = true;
        } break;

        case SDL_KEYDOWN:
        case SDL_KEYUP:
        {
            SDL_Keycode key_code = event->key.keysym.sym;
            bool is_down = (event->key.state == SDL_PRESSED);
            if (is_down)
            {
                if (key_code == SDLK_p)
                {
                    PAUSED = !PAUSED;
                }
            }
        } break;

        case SDL_CONTROLLERAXISMOTION:
        {
            // down and right are positive
            float normalized_axis_value = sdl_process_controller_axis_value(event->caxis.value, DEADZONE_THRESHOLD);

            //printf("SDL_CONTROLLERAXISMOTION (%d, %s, %d, %f)\n",
            //        event->caxis.which,
            //        SDL_GameControllerGetStringForAxis(event->caxis.axis),
            //        event->caxis.value,
            //        normalized_axis_value);

            switch(event->caxis.axis)
            {
                case SDL_CONTROLLER_AXIS_LEFTX:
                {
                    controller_input->left_stick_x = normalized_axis_value;
                } break;
                case SDL_CONTROLLER_AXIS_LEFTY:
                {
                    controller_input->left_stick_y = normalized_axis_value;
                } break;
                case SDL_CONTROLLER_AXIS_RIGHTX:
                {
                    controller_input->right_stick_x = normalized_axis_value;
                } break;
                case SDL_CONTROLLER_AXIS_RIGHTY:
                {
                    controller_input->right_stick_y = normalized_axis_value;
                } break;
                default:
                {
                    printf("Unhandled axis input\n");
                }
            }
        } break;

        case SDL_WINDOWEVENT:
        {
            switch(event->window.event)
            {
                case SDL_WINDOWEVENT_SIZE_CHANGED:
                {
                    SDL_Window *window = SDL_GetWindowFromID(event->window.windowID);
                    SDL_Renderer *renderer = SDL_GetRenderer(window);
                    printf("SDL_WINDOWEVENT_SIZE_CHANGED (%d, %d)\n", event->window.data1, event->window.data2);
                    sdl_resize_texture(&global_back_buffer, renderer, event->window.data1, event->window.data2);
                } break;

                case SDL_WINDOWEVENT_FOCUS_GAINED:
                {
                    printf("SDL_WINDOWEVENT_FOCUS_GAINED\n");
                } break;

                case SDL_WINDOWEVENT_EXPOSED:
                {
                    SDL_Window *window = SDL_GetWindowFromID(event->window.windowID);
                    SDL_Renderer *renderer = SDL_GetRenderer(window);
                    sdl_update_window(renderer, &global_back_buffer);
                } break;
            }
        } break;
    }
    return(should_quit);
}


int main(int argc, char *argv[])
{
    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_GAMECONTROLLER))
    {
        // TODO(amin): log SDL_Init error
    }

    SDL_Window *window = SDL_CreateWindow(
            TITLE,
            SDL_WINDOWPOS_UNDEFINED,
            SDL_WINDOWPOS_UNDEFINED,
            SCREEN_WIDTH,
            SCREEN_HEIGHT,
            SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI);

#ifdef FULLSCREEN
    SDL_SetWindowFullscreen(window, SDL_WINDOW_FULLSCREEN_DESKTOP);
#endif

    if (window)
    {
        SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, 0);

        if (renderer)
        {
            struct SDLWindowDimension dimension = sdl_get_window_dimension(window);
            sdl_resize_texture(&global_back_buffer, renderer, dimension.width, dimension.height);

            bool running = true;

#ifdef USE_TEST_SEED
            srand((uint32_t)0);
#else
            srand((uint32_t)time(NULL));
#endif

            int num_joysticks = SDL_NumJoysticks();
            SDL_GameController *controller_handles[MAX_CONTROLLERS];
            for (int controller_index = 0; controller_index < num_joysticks; ++controller_index)
            {
                if (!SDL_IsGameController(controller_index))
                {
                    continue;
                }

                if (controller_index >= MAX_CONTROLLERS)
                {
                    break;
                }

                controller_handles[controller_index] = SDL_GameControllerOpen(controller_index);
            }

            uint64_t lag = 0;
            uint64_t previous_ms = (SDL_GetPerformanceCounter() * SECOND) / SDL_GetPerformanceFrequency();

            struct GameState game_state;
            game_init(&game_state, dimension.width, dimension.height);

            struct GameControllerInput controller_input;
            controller_input.controller_index = 0;
            controller_input.left_stick_x = 0;
            controller_input.right_stick_y = 0;
            controller_input.left_stick_x = 0;
            controller_input.right_stick_y = 0;

            while (running)
            {
                uint64_t current_ms = (SDL_GetPerformanceCounter() * SECOND) / SDL_GetPerformanceFrequency();
                uint64_t elapsed_ms = current_ms - previous_ms;
                previous_ms = current_ms;
                lag += elapsed_ms;
                //printf("%" PRIu64 ", %" PRIu64 ", %f\n", elapsed_ms, lag, MS_PER_UPDATE);

                SDL_Event event;
                while (SDL_PollEvent(&event))
                {
                    running = !sdl_handle_event(&event, &controller_input);
                }
                SDL_PumpEvents();

                dimension = sdl_get_window_dimension(window);

                struct OffscreenBuffer buffer;
                // WARNING: these pointers are aliased until the end of the
                // loop
                buffer.memory = global_back_buffer.memory;
                buffer.width = global_back_buffer.width;
                buffer.height = global_back_buffer.height;
                buffer.pitch = global_back_buffer.pitch;

                if (PAUSED)
                {
                    lag = 0;
                }
                else
                {
                    while (lag >= MS_PER_UPDATE)
                    {
                        game_update(&game_state, controller_input, buffer.width, buffer.height);
                        //printf("\t%" PRIu64 ", %f\n", lag, MS_PER_UPDATE);
                        lag -= MS_PER_UPDATE;
                    }
                }

                clear_screen(&global_back_buffer, COLOR_BACKGROUND);
                game_render(&buffer, lag/SECOND, &game_state);
                sdl_update_window(renderer, &global_back_buffer);
                if (elapsed_ms <= MS_PER_FRAME)
                {
                    SDL_Delay(MS_PER_FRAME - elapsed_ms);
                }
            }

            game_cleanup(&game_state);

            for (int controller_index = 0; controller_index < num_joysticks; ++controller_index)
            {
                if (!SDL_IsGameController(controller_index))
                {
                    continue;
                }

                if (controller_index >= MAX_CONTROLLERS)
                {
                    break;
                }

                SDL_GameControllerClose(controller_handles[controller_index]);
            }
        }
        else
        {
            // TODO(amin): log SDL_Renderer error
        }
    }
    else
    {
        // TODO(amin): log SDL_Window error
    }

    SDL_Quit();
    return(0);
}