summaryrefslogtreecommitdiff
path: root/md/writeup/web_assembly_sdl_example.md
blob: d2fc0aa9e100d4de635b9d32e87f7e655a010399 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
title: WebAssembly SDL example
keywords:c,webassembly,js,SDL

# WebAssembly SDL example

## Intro

There is many examples of how to compile SDL for webassembly, but many of them isnt 
minimal as necessary, so here tried to make just bare minimum for application
that can be compiled for 2 targets webassembly and pc.

## How things works

Webassembly is virtual machine that you can run in your browser, it allows you to run compiled code.
Its not 100% like real pc virtual machine and more oriented on web. But its close enough to just
port and run you C/C++ or any other language that supports LLVM as backend. 

There need to be included emscripten header that gives callback for javascript to be runned.

```c
#include <emscripten/emscripten.h>
```

And as all this going to be compiled to webassembly byte code then you can _just_ load compiled file.
There is many ways how wasm bytecode going to be runned. We registed our code so its runes specified
number of frames per second. Check functions docs for better description. 

```c
void emscripten_set_main_loop(em_callback_func func, int fps, int simulate_infinite_loop)
```

Porting requiring to define loop that will be registered for webassembly engine and thats all. 
There need to be covered more things if there is need to use some fonts,images or files. But for
now its minimal example that will draw SDL window in your browser ;]

## Demo

This example compilable for PC target and for webassembly. Enjoy playing with it.

<script type='text/javascript'>
	var Module = {};
	fetch('/demo/sdl/index.wasm')
	.then(response =>
		response.arrayBuffer()
	).then(buffer => {
		Module.canvas = document.getElementById("canvas");
		Module.wasmBinary = buffer;
		var script = document.createElement('script');
		script.src = "/demo/sdl/index.js";
		script.onload = function() {
		console.log("Emscripten boilerplate loaded.")
		}
		document.body.appendChild(script);
	});
</script><canvas id="canvas" style="width:100%; height:100%;"></canvas>


## Source


```c
#include <stdio.h>
#include <stdlib.h>

#if __EMSCRIPTEN__
#include <emscripten/emscripten.h>
#include <SDL2/SDL.h>
#include <SDL/SDL_ttf.h>
#else
#include <SDL2/SDL.h>
#include <SDL2/SDL_ttf.h>
#endif

#define SCREEN_WIDTH  200
#define SCREEN_HEIGHT 200

SDL_Window *window = NULL;
SDL_Renderer *renderer = NULL;

#define MAX(a,b) ((a) > (b) ? a : b)
#define MIN(a,b) ((a) < (b) ? a : b)

int posX=0;
int posY=0;
int sizeW=20;
int sizeH=20;

static int quit = 0;

void render()
{
	
	SDL_Rect r_scr;
	r_scr.x = posX;
	r_scr.y = posY;
	r_scr.w = sizeW;
	r_scr.h = sizeH;
	SDL_SetRenderDrawColor( renderer, 0x00, 0x00, 0x00, 0xFF );
	SDL_RenderClear(renderer);

	SDL_SetRenderDrawColor(renderer, 0xff, 0xff, 0x00, 0x00);
	SDL_RenderDrawRect(renderer, &r_scr);
	SDL_RenderPresent(renderer);
}

#if __EMSCRIPTEN__
void main_tick() {
#else
int main_tick() {
#endif
	
	SDL_Event event;

		while (SDL_PollEvent(&event))
		{
			switch (event.type)
			{
			case SDL_QUIT:
			{
				quit = 1;
				break;
			}
			case SDL_KEYDOWN:
			{
				switch (event.key.keysym.sym)
				{
				case SDLK_UP:
				{
					if (posY>=20)
					{
						posY-=20;
					}
					break;
				}
				case SDLK_DOWN:
				{
					if (posY+sizeH<SCREEN_HEIGHT)
					{
						posY += 20;
					}
					break;
				}
				case SDLK_LEFT:
				{
					if (posX>=20)
					{
						posX-=20;
					}
					break;
				}
				case SDLK_RIGHT:
				{
					if (posX+sizeW<SCREEN_WIDTH)
					{
						posX+=20;
					}
					break;
				}
				}
				break;
			}
			}
			
		}
	

	render();
	SDL_UpdateWindowSurface(window);

#if !__EMSCRIPTEN__
	return 0;
#endif
}

void main_loop()
{

#if __EMSCRIPTEN__
	emscripten_set_main_loop(main_tick, -1, 1);
#else
	while (0 == quit)
	{
		main_tick();
	}
#endif
}

int main()
{
	SDL_Init(SDL_INIT_VIDEO);

	window = SDL_CreateWindow(
		"WEBASM",
		SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
		SCREEN_WIDTH, SCREEN_HEIGHT,
		SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL);

	renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
	SDL_SetRenderDrawColor(renderer, 0xff, 0xff, 0xff, 0xff);

	main_loop();

	SDL_DestroyRenderer(renderer);
	SDL_DestroyWindow(window);
	SDL_Quit();

	return 0;
}
```


```js
<html>
    <head>
    	<meta charset="utf-8">
    	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    </head>
    <body>
    	<script type='text/javascript'>
	      var Module = {};
	      fetch('index.wasm')
	        .then(response =>
	          response.arrayBuffer()
	        ).then(buffer => {
	          Module.canvas = document.getElementById("canvas");
	          Module.wasmBinary = buffer;
	          var script = document.createElement('script');
	          script.src = "index.js";
	          script.onload = function() {
	            console.log("Emscripten boilerplate loaded.")
	          }
	          document.body.appendChild(script);
	        });
	    </script>
	    <canvas id="canvas" style="width:100%; height:100%"></canvas>

	</body>
</html>
```

```makefile
CC=gcc
CFALGS=
LDFLAGS=-lSDL2 -lSDL2_ttf

EM_ENV=LLVM=/usr/bin NODE_JS=node EMSCRIPTEN_ROOT=/usr/lib/emscripten
EM_CC=emcc
EM_CFLAGS=-s WASM=1 -O3
EM_LDFALGS=-s USE_SDL=2 -s USE_SDL_IMAGE=2 -s SDL2_IMAGE_FORMATS='["png"]' -s USE_SDL_TTF=2

pc:
	$(CC) $(CFLAGS) $(LDFLAGS) main.c -o main

em:
	$(EM_CC) main.c $(EM_CFLAGS) $(EM_LDFALGS) -o index.js -s EXTRA_EXPORTED_RUNTIME_METHODS='["ccall", "cwrap"]'  
```

## Links

1. https://wiki.libsdl.org/CategoryAPI
2. https://developer.mozilla.org/en-US/docs/WebAssembly/C_to_wasm
3. https://github.com/kvark/wasm-triangle/blob/master/src/main.rs
4. https://github.com/belen-albeza/space-shooter-wasm/blob/master/src/main.c
5. https://kripken.github.io/emscripten-site/docs/api_reference/emscripten.h.html