Tuesday, February 12, 2019

Emscripten and SDL2 Tutorial --- WebAssembly C++

I believe that most C/C++ programmers are very interested with WebAssembly. Emscripten provides a number of ways to solve the first problem of making files on the server accessible to C/C++ programs.

SDL (Simple DirectMedia Layer) is a cross-platform development library designed to provide low level access to audio, keyboard, mouse, joystick, and graphics hardware via OpenGL and Direct3D.

This is just to show on how SDL can be implemented into WebAssembly by displaying an image.


I hope you like it and let's get started
 
Environment Specification
I am using Ubuntu 16.04 LTS with standard build tools for C/C++.

If you need HelloWorld Tutorial, you can find here.


Writing Code

$ touch hello.cpp
 
 #include <stdio.h>
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <emscripten.h>
#include <unistd.h>
#include <stdlib.h>

int testImage(SDL_Renderer* renderer, const char* fileName)
{
  SDL_Surface *image = IMG_Load(fileName);
  if (!image)
  {
     printf("IMG_Load: %s\n", IMG_GetError());
     return 0;
  }
  int result = image->w;


  SDL_Rect dest = {.x = 200, .y = 100, .w = 200, .h = 200};

  SDL_Texture *tex = SDL_CreateTextureFromSurface(renderer, image);

  SDL_RenderCopy (renderer, tex, NULL, &dest);

  SDL_DestroyTexture (tex);

  SDL_FreeSurface (image);

  return result;
}

int main()
{
  SDL_Init(SDL_INIT_VIDEO);

  SDL_Window *window;
  SDL_Renderer *renderer;

  SDL_CreateWindowAndRenderer(600, 400, 0, &window, &renderer);

  int result = 0;

  SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
  SDL_RenderClear(renderer);

  result |= testImage(renderer, "golang.png");

  SDL_RenderPresent(renderer);

  printf("you should see an image.\n");

  return 0;
}


Compile It
$ emcc hello.c -O2 -s USE_SDL=2 -s USE_SDL_IMAGE=2 -s SDL2_IMAGE_FORMATS='["png"]'     --preload-file assets -o hello.html


Run It
$ emrun hello.html


Resut






Thank you


Other Topics:

No comments:

Post a Comment