Search code examples
c++emscriptensdl-imagewebassembly

How to load textures using SDL to a WebAssembly project using emscripten?


I'm trying to load a texture to my application using SDL. When building as a native application, it works as it should. But when I'm building it with Emscripten, the texture cannot be loaded.

The width of the texture image is 64 pixels, which I can verify by printing out the w member of the SDL_Surface instance. But when I try to print out the same member in the WebAssembly application, it yields 5076...

Does the image become "broken" somehow when packed with emscripten?

Here's the code to load the texture:

SDL_Surface *image = IMG_Load("resources/binaries/crate.jpg");
GLuint textureID;
glGenTextures(1, &textureID);
glBindTexture(GL_TEXTURE_2D, textureID);
std::cout << image->w << std::endl;
glTexImage2D(GL_TEXTURE_2D, 0, 3, 64, 64, 0, GL_RGB, GL_UNSIGNED_BYTE, image->pixels);

Here's the command to build the web app with Emscripten

emcc --bind -s USE_SDL=2 -s USE_SDL_IMAGE=2 -o webapp.js src/webapp.cpp --preload-file resources

The error message I'm getting the browser when launching the web app is

webapp.js:9533 WebGL: INVALID_VALUE: texImage2D: width or height out of range

Which makes sense, since the resolution of the image is so crazy...


Solution

  • Turns out I had to use --use-preload-plugins when executing emcc to create the preload file. Finally, the command looks like this:

    emcc --bind -s USE_SDL=2 -s USE_SDL_IMAGE=2 -o webapp.js src/webapp.cpp --preload-file resources --use-preload-plugins