File: sdl2_canvas_write.cpp

package info (click to toggle)
emscripten 3.1.6~dfsg-5
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 114,112 kB
  • sloc: ansic: 583,052; cpp: 391,943; javascript: 79,361; python: 54,180; sh: 49,997; pascal: 4,658; makefile: 3,426; asm: 2,191; lisp: 1,869; ruby: 488; cs: 142
file content (77 lines) | stat: -rw-r--r-- 2,201 bytes parent folder | download | duplicates (2)
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
// Copyright 2015 The Emscripten Authors.  All rights reserved.
// Emscripten is available under two separate licenses, the MIT license and the
// University of Illinois/NCSA Open Source License.  Both these licenses can be
// found in the LICENSE file.

#include <SDL.h>
#include <emscripten.h>

static void sdlError(const char *str) 
{
    fprintf(stderr, "Error at %s: %s\n", str, SDL_GetError());
    emscripten_force_exit(1);
}

void draw(SDL_Window *window, SDL_Surface *surface) {
    int x, y;

    if (SDL_MUSTLOCK(surface)) {
        if (SDL_LockSurface(surface) != 0) sdlError("SDL_LockSurface");
    }

    for (y = 0; y < 256; y++) {
        Uint32 *p = (Uint32 *)(((Uint8 *)surface->pixels) +
                               surface->pitch * y);
        for (x = 0; x < 256; x++) {
            *(p++) = SDL_MapRGB(surface->format, x, x ^ y, y);
        }
    }

    if (SDL_MUSTLOCK(surface)) SDL_UnlockSurface(surface);
    if (SDL_UpdateWindowSurface(window) != 0)
        sdlError("SDL_UpdateWindowSurface");
}

int verify(void) {
    int res = EM_ASM_INT({
        var ctx = Module['canvas'].getContext('2d');
        var data = ctx.getImageData(0, 0, 256, 256).data;
        var idx = 0;
        for (var y = 0; y < 256; y++) {
            for (var x = 0; x < 256; x++) {
                if (data[idx    ] !== x || 
                    data[idx + 1] !== (x ^ y) || 
                    data[idx + 2] !== y ||
                    data[idx + 3] !== 255) {
                    return 1;
                }
                idx += 4;
            }
        }
        return 0;
    });

    printf("%s\n", res ? "FAIL" : "PASS");
    return res;
}

int main(void) {
    SDL_Window *window;
    SDL_Surface *surface;

    if (SDL_Init(SDL_INIT_VIDEO) != 0) sdlError("SDL_Init");

    window = SDL_CreateWindow("SDL 2 test",
                              0, 0,
                              256, 256,
                              SDL_WINDOW_SHOWN);
    if (window == NULL) sdlError("SDL_CreateWindow");
    surface = SDL_GetWindowSurface(window);
    if (surface == NULL) sdlError("SDL_GetWindowSurface");

    draw(window, surface);

    int result = verify();
    REPORT_RESULT(result);
}