Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
emscripten draw pixels and scale by SDL_RenderCopy
emcc test_pixel2.c ^
-O2 ^
-Wall -Wextra -pedantic ^
-s USE_SDL=2 ^
-s USE_SDL_IMAGE=2 -s SDL2_IMAGE_FORMATS="[""png""]" ^
-s USE_SDL_TTF=2 ^
--preload-file assets ^
-o test_pixel2.html
#include <stdbool.h>
#include <stdint.h>
#include <SDL2/SDL.h>
#ifdef __EMSCRIPTEN__
#include <emscripten.h>
#endif
typedef struct {
SDL_Window *window;
SDL_Renderer *renderer;
} Context;
void Cleanup(Context *ctx) {
if (ctx) {
if (ctx->renderer)
SDL_DestroyRenderer(ctx->renderer);
if (ctx->window)
SDL_DestroyWindow(ctx->window);
}
}
uint32_t Init(Context *ctx) {
if (SDL_Init(SDL_INIT_VIDEO) != 0) {
fprintf(stderr, "Error: %s", SDL_GetError());
return -1;
}
ctx->window = SDL_CreateWindow("sandbox2",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
640,480,
SDL_WINDOW_SHOWN);
if (ctx->window == NULL) {
fprintf(stderr, "Error: %s", SDL_GetError());
return -1;
}
ctx->renderer = SDL_CreateRenderer(ctx->window,
-1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
if (ctx->renderer == NULL) {
fprintf(stderr, "Error: %s", SDL_GetError());
return -1;
}
SDL_SetRenderDrawColor(ctx->renderer, 255 ,200 ,200, 255);
/*
* Init Display
*/
return 0;
}
SDL_Surface *screen;
void Loop(void *arg) {
Context *ctx = (Context *)arg;
//
// Manipulate
//
// if arg2 is NULL, draw all surface.
SDL_FillRect(screen, NULL, SDL_MapRGBA(screen->format, 0xcc, 0xcc, 0xcc, 0xff));
SDL_LockSurface(screen);
// ARGB
*((int*)screen->pixels + 0) = 0xFFFF0000;
*((int*)screen->pixels + 1) = 0xFF00FF00;
*((int*)screen->pixels + 2) = 0xFF0000FF;
*((int*)screen->pixels + 3) = 0xFFFFFFFF;
*((int*)screen->pixels + 4) = 0x00000000;
*((int*)screen->pixels + 95)= 0xFF000000;
SDL_UnlockSurface(screen);
//
// Draw
//
SDL_Texture *tex = SDL_CreateTextureFromSurface(ctx->renderer, screen);
SDL_RenderClear(ctx->renderer);
SDL_RenderCopy(ctx->renderer, tex, NULL, &(SDL_Rect){0, 0, 640*2, 480*2});
SDL_RenderPresent(ctx->renderer);
SDL_DestroyTexture(tex);
}
int main() {
Context ctx = {0,0};
Init(&ctx);
screen = SDL_CreateRGBSurface(0, 64, 32, 32, 0, 0, 0, 0);
printf("screen format:%d\n", screen->format->format);
Loop(&ctx);
emscripten_set_main_loop_arg(Loop, &ctx,-1, 1/*block*/);
printf("don't run this message by block.");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.