Skip to content

Instantly share code, notes, and snippets.

@jarikomppa
Created November 25, 2023 15:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jarikomppa/d4b1895833e0780cf69ef5909276a85b to your computer and use it in GitHub Desktop.
Save jarikomppa/d4b1895833e0780cf69ef5909276a85b to your computer and use it in GitHub Desktop.
#ifdef __EMSCRIPTEN__
#include <emscripten/emscripten.h>
#endif
#include "SDL3/SDL.h"
#include "SDL3/SDL_main.h"
int* fb;
SDL_Window* window;
SDL_Renderer* renderer;
SDL_Texture* tex;
static int done;
const int WINDOW_WIDTH = 1920/2;
const int WINDOW_HEIGHT = 1080/2;
bool update()
{
SDL_Event e;
if (SDL_PollEvent(&e)) {
if (e.type == SDL_EVENT_QUIT)
{
return false;
}
if (e.type == SDL_EVENT_KEY_UP && e.key.keysym.sym == SDLK_ESCAPE)
{
return false;
}
}
char* pix;
int pitch;
SDL_LockTexture(tex, NULL, (void**)&pix, &pitch);
for (int i = 0, sp = 0, dp = 0; i < WINDOW_HEIGHT; i++, dp += WINDOW_WIDTH, sp += pitch)
memcpy(pix + sp, fb + dp, WINDOW_WIDTH * 4);
SDL_UnlockTexture(tex);
SDL_RenderTexture(renderer, tex, NULL, NULL);
SDL_RenderPresent(renderer);
return true;
}
void render(Uint64 ticks)
{
for (int i = 0, c = 0; i < WINDOW_HEIGHT; i++)
for (int j = 0; j < WINDOW_WIDTH; j++, c++)
fb[c] = (int)(i * i + j * j + ticks);
}
void loop()
{
if (!update())
{
done = 1;
#ifdef __EMSCRIPTEN__
emscripten_cancel_main_loop();
#endif
}
else
{
render(SDL_GetTicks());
}
}
int main(int argc, char** argv)
{
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS) < 0)
{
return -1;
}
fb = new int[WINDOW_WIDTH * WINDOW_HEIGHT];
window = SDL_CreateWindow("SDL3 window", WINDOW_WIDTH, WINDOW_HEIGHT, SDL_WINDOW_OPENGL);
renderer = SDL_CreateRenderer(window, NULL, SDL_RENDERER_ACCELERATED);
tex = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_ABGR8888, SDL_TEXTUREACCESS_STREAMING, WINDOW_WIDTH, WINDOW_HEIGHT);
if (!fb || !window || !renderer || !tex)
return -1;
done = 0;
#ifdef __EMSCRIPTEN__
emscripten_set_main_loop(loop, 0, 1);
#else
while (!done) {
loop();
}
#endif
SDL_DestroyTexture(tex);
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment