1#include <SDL2/SDL.h>
2
3#include "util.h"
4#include "platform/platform.h"
5
6void platform_get_drawable_size(MGContext* ctx, i32* width, i32* height)
7{
8#ifdef MG_RENDERER_SMALL3DLIB
9 SDL_GetWindowSize(ctx->win, width, height);
10#else
11 SDL_GL_GetDrawableSize(ctx->win, width, height);
12#endif
13}
14
15void platform_init(MGContext* ctx)
16{
17 (void)ctx;
18 if (SDL_Init(SDL_INIT_VIDEO) != 0)
19 mg_die(MG_ERR_SDL_INIT, "SDL_Init failed: %s", SDL_GetError());
20
21#ifdef MG_RENDERER_SOKOL
22 /* TODO: OpenGL specifis */
23 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
24 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
25 SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
26 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
27 SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
28#endif
29}
30
31/* TODO: platform independant design MGEvent, MGPoll */
32i32 platform_poll(MGContext* ctx)
33{
34 SDL_Event ev;
35 while (SDL_PollEvent(&ev)) {
36 switch (ev.type) {
37 case SDL_QUIT:
38 return 0;
39
40 case SDL_WINDOWEVENT:
41 if (ev.window.event == SDL_WINDOWEVENT_SIZE_CHANGED) { /* resize */
42 ctx->width = ev.window.data1;
43 ctx->height = ev.window.data2;
44 }
45 }
46 }
47
48 return 1;
49}
50
51void platform_present(MGContext* ctx)
52{
53#ifdef MG_RENDERER_SMALL3DLIB
54 SDL_RenderPresent(ctx->vbe.renderer);
55#else
56 SDL_GL_SwapWindow(ctx->win);
57#endif
58}
59
60void platform_shutdown(MGContext* ctx)
61{
62 if (!ctx)
63 return;
64
65#ifdef MG_RENDERER_SMALL3DLIB
66 if (ctx->vbe.renderer) {
67 SDL_DestroyRenderer(ctx->vbe.renderer);
68 ctx->vbe.renderer = NULL;
69 }
70#endif
71
72#ifdef MG_RENDERER_SOKOL
73 if (ctx->vbe.gl) {
74 SDL_GL_DeleteContext(ctx->vbe.gl);
75 ctx->vbe.gl = NULL;
76 }
77#endif
78
79 if (ctx->win) {
80 SDL_DestroyWindow(ctx->win);
81 ctx->win = NULL;
82 }
83
84 SDL_Quit();
85}
86
87void platform_window_create(MGContext* ctx)
88{
89 u32 flags = SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI;
90#ifdef MG_RENDERER_SOKOL
91 flags |= SDL_WINDOW_OPENGL;
92#endif
93
94 ctx->win = SDL_CreateWindow(ctx->title, ctx->x, ctx->y, ctx->width, ctx->height, flags);
95
96 if (!ctx->win)
97 mg_die(MG_ERR_SDL_CREATE_WIN, "Failed to create window: %s", SDL_GetError());
98
99#ifdef MG_RENDERER_SMALL3DLIB
100 ctx->vbe.renderer = SDL_CreateRenderer(ctx->win, -1, SDL_RENDERER_ACCELERATED);
101 if (!ctx->vbe.renderer)
102 ctx->vbe.renderer = SDL_CreateRenderer(ctx->win, -1, SDL_RENDERER_SOFTWARE);
103 if (!ctx->vbe.renderer)
104 mg_die(MG_ERR_REN_CREATE, "Failed to create SDL renderer: %s", SDL_GetError());
105#endif
106
107#ifdef MG_RENDERER_SOKOL
108 ctx->vbe.gl = SDL_GL_CreateContext(ctx->win);
109 if (!ctx->vbe.gl)
110 mg_die(MG_ERR_GL_CTX_CREATE, "Failed to initialise GL Context");
111
112 if (SDL_GL_MakeCurrent(ctx->win, ctx->vbe.gl) != 0)
113 mg_die(MG_ERR_GL_CTX_ACTIVATE, "Failed to activate GL Context: %s", SDL_GetError());
114
115 SDL_GL_SetSwapInterval(1);
116#endif
117}