Skip to main content
1 / 2

DebianでSDL2

起こっている問題

SDL2を使いたいと思っているのですが、何故かウィンドウが表示されません。
ログを見る限りではプログラムは一応動いているっぽいです。ただ、ウィンドウが表示されません。
解決法をご存知の方、どうぞよろしくお願いいたします。

ソースコード(main.cpp)

#include <iostream>
#include "SDL2/SDL.h"
using namespace std;

int main(int argc, char* argv[])
{
    cout << "Start" << endl;

    const int SCREEN_WIDTH = 800;
    const int SCREEN_HEIGHT = 600;

    if (SDL_Init(SDL_INIT_AUDIO) < 0) {
        cout << "SDL init failed." << endl;
        return 1;
    }

    // initialize screen
    SDL_Window* window = SDL_CreateWindow("Hello world !!", SDL_WINDOWPOS_UNDEFINED,
        SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);

    if (window == NULL) {
        SDL_Quit();
        return 2;
    }

    SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_PRESENTVSYNC);
    SDL_Texture* texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888,
        SDL_TEXTUREACCESS_STATIC, SCREEN_WIDTH, SCREEN_HEIGHT);

    if (renderer == NULL) {
        cout << "Could not create renderer" << endl;
        SDL_DestroyWindow(window);
        SDL_Quit();
        return 3;
    }

    if (texture == NULL) {
        cout << "Could not create texture" << endl;
        SDL_DestroyRenderer(renderer);
        SDL_DestroyWindow(window);
        SDL_Quit();
        return 4;
    }

    // prepare memory
    Uint32* buffer = new Uint32[SCREEN_WIDTH * SCREEN_HEIGHT];

    memset(buffer, 0, SCREEN_WIDTH * SCREEN_HEIGHT * sizeof(Uint32));

    // set every 4bytes as color into memory
    for (int i = 0; i < SCREEN_WIDTH * SCREEN_HEIGHT; i++) {
        buffer[i] = 0x008080FF;
    }

    // update screen
    SDL_UpdateTexture(texture, NULL, buffer, SCREEN_WIDTH * sizeof(Uint32));
    SDL_RenderClear(renderer);
    SDL_RenderCopy(renderer, texture, NULL, NULL);
    SDL_RenderPresent(renderer);

    bool quit = false;
    SDL_Event event;

    while (!quit) {
        while (SDL_PollEvent(&event)) {
            if (event.type == SDL_QUIT) {
                quit = true;
            };
        }
        cout << "Loop" << endl;
    }

    // finalize screen
    delete[] buffer;
    SDL_DestroyRenderer(renderer);
    SDL_DestroyTexture(texture);
    SDL_DestroyWindow(window);
    SDL_Quit();

    cout << "End" << endl;

    return 0;
}

実行結果

$ g++ -o main main.cpp `sdl2-config --cflags --libs` -lSDL2
$ ./main
Start
Loop
Loop
Loop
Loop
Loop
        //省略
Loop
Loop
Loop
Loop^C  //ctrl + c
Loop
End