1

Я изучаю Xlib и хочу попрактиковаться. Решил написать программу отрисовки графика, чтобы его можно было перетаскивать мышкой.

Для этого я вызываю перерисовку окна каждый раз по событию MotionNotify. Однако, картинка перерисоваться не всегда успевает и иногда мигает белым фоном (особенно - если окно на полный экран развернуть).

Можно ли вообще перерисовывать каждый раз по получению этого события? Есть ли какие-нибудь способы оптимизировать этот подход?

#include <stdio.h>
#include <stdlib.h>
#include <X11/Xlib.h>
#include <math.h>

#define MAX_X (3 * M_PI)
#define MAX_Y 2

long double f(long double x) {
    return sin(x);
}


int x_prev_position = -1;
int y_prev_position = -1;

int draw (Display *display, Window win, int shift_x, int shift_y, int resized) {
    static Window rootReturn;
    static int xReturn;
    static int yReturn;
    static unsigned int widthReturn;
    static unsigned int heightReturn;
    static unsigned int borderWidthReturn;
    static unsigned int depthReturn;
    GC gc;
    XGCValues gcv;

    int blackpixel = BlackPixel(display, DefaultScreen(display));
    int whitepixel = WhitePixel(display, DefaultScreen(display));

    int x;
    int y;

    long double x1;
    long double y1;
    long double x2;
    long double y2;
    static long double total_shift_x = 0;
    static long double total_shift_y = 0;

    int w1;
    int h1;
    int w2;
    int h2;

    int i;

    gcv.background = whitepixel;
    gcv.foreground = blackpixel;
    gc = XCreateGC(display, DefaultRootWindow(display), GCForeground | GCBackground, &gcv);

    if (resized) {
        XGetGeometry(display, win, &rootReturn, &xReturn, &yReturn, &widthReturn, &heightReturn, &borderWidthReturn, &depthReturn);
    }

    if (shift_x >= 0) {
        if (x_prev_position >= 0) {
            total_shift_x += (x_prev_position - shift_x) * 0.01;
            total_shift_y += (y_prev_position - shift_y) * 0.01;
        }

        x_prev_position = shift_x;
        y_prev_position = shift_y;
    }

    XClearWindow(display, win);

    XDrawLine(display, win, gc, 0, heightReturn / 2, widthReturn, heightReturn / 2);

    XDrawLine(display, win, gc, widthReturn / 2, 0, widthReturn / 2, heightReturn);

    for (w1 = 0; w1 < widthReturn; w1 += 5) {
        x1 = (w1*2.0/widthReturn - 1.0)*MAX_X + total_shift_x;
        y1 = f(x1) + total_shift_y;
        h1 = (1.0 - (y1/MAX_Y))*heightReturn / 2.0;

        w2 = w1 + 5;
        x2 = (w2*2.0/widthReturn - 1.0)*MAX_X + total_shift_x;
        y2 = f(x2) + total_shift_y;
        h2 = (1.0 - (y2/MAX_Y))*heightReturn / 2.0;

        XDrawLine(display, win, gc, w1, h1, w2, h2);
    }
}

int main(int argc, char *argv[]) {
    Display *dpy;
    int screen;
    Window win;
    Window rootWin;
    XEvent event;

    unsigned int depth;
    XSetWindowAttributes attrs;

    dpy = XOpenDisplay(NULL);

    if (dpy == NULL) {
        fprintf(stderr, "Cannot open display\n");
        exit(1);
    }

    screen = DefaultScreen(dpy);
    depth = DefaultDepth(dpy, screen);
    rootWin = RootWindow(dpy, screen);

    attrs.border_pixel = BlackPixel(dpy, screen);
    attrs.background_pixel = WhitePixel(dpy, screen);
    attrs.override_redirect = True;
    attrs.colormap = CopyFromParent;
    attrs.event_mask = ExposureMask | KeyPressMask | ButtonPressMask | Button1MotionMask | ButtonReleaseMask;

    win = XCreateWindow(dpy, rootWin, 700, 700, 500, 300, 0, depth, InputOutput, CopyFromParent, CWBackPixel | CWColormap | CWBorderPixel | CWEventMask, &attrs);

    XMapWindow(dpy, win);

    for (;;) {
        XNextEvent(dpy, &event);
        switch(event.type) {
        case Expose:
            draw(dpy, win, -1, -1, 1);
            break;

        case ButtonRelease:
            switch (event.xbutton.button) {
            case Button1:
                x_prev_position = -1;
                y_prev_position = -1;

                break;
            }
            break;
        case MotionNotify:
            draw(dpy, win, event.xmotion.x, event.xmotion.y, 0);

            break;
        case KeyPress:
        default:
            XDestroyWindow(dpy, win);
            XCloseDisplay(dpy);

            exit(0);
        }
    }

    return 1;
}

Я попытался избавиться от этого с помощью переменной resized, но желаемого эффекта не достиг

1
  • @Fat-Zer, обновил пример. Я просто из vim копировал, забыл номера строк убрать :) 12 апр 2018 в 2:51

1 ответ 1

1

Для того чтобы избежать мерцания стандартным приёмом при низкоуровневом рисовании является двойная буферизация и X11 здесь не исключение. Большинство высокоуровневых библиотек производят отрисовку на стороне клиента и посылают серверу готовые pixmap'ы.

Для двойной буферизации средствами голого X Api есть специальное расширение: DBE. Для его использования код потребует минимальных доработок:

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#include <X11/Xlib.h>
#include <X11/keysym.h>
#include <X11/extensions/Xdbe.h>

#define MAX_X (3 * M_PI)
#define MAX_Y 2

long double f(long double x) {
    return sin(x);
}


int x_prev_position = -1;
int y_prev_position = -1;

void draw (Display *display, Drawable win, int shift_x, int shift_y, int resized) {
    static Window rootReturn;
    static int xReturn;
    static int yReturn;
    static unsigned int widthReturn;
    static unsigned int heightReturn;
    static unsigned int borderWidthReturn;
    static unsigned int depthReturn;
    GC gc;
    XGCValues gcv;

    int blackpixel = BlackPixel(display, DefaultScreen(display));
    int whitepixel = WhitePixel(display, DefaultScreen(display));

    static long double total_shift_x = 0;
    static long double total_shift_y = 0;

    gcv.background = whitepixel;
    gcv.foreground = blackpixel;
    gc = XCreateGC(display, DefaultRootWindow(display), GCForeground | GCBackground, &gcv);

    if (resized) {
        XGetGeometry(display, win, &rootReturn, &xReturn, &yReturn, &widthReturn, &heightReturn, &borderWidthReturn, &depthReturn);
    }

    if (shift_x >= 0) {
        if (x_prev_position >= 0) {
            total_shift_x += (x_prev_position - shift_x) * 0.01;
            total_shift_y += (y_prev_position - shift_y) * 0.01;
        }

        x_prev_position = shift_x;
        y_prev_position = shift_y;
    }

    XDrawLine(display, win, gc, 0, heightReturn / 2, widthReturn, heightReturn / 2);

    XDrawLine(display, win, gc, widthReturn / 2, 0, widthReturn / 2, heightReturn);

    unsigned npoints = (widthReturn/5)+1;
    XPoint *points = malloc (sizeof(XPoint) * npoints );

    for (unsigned i = 0; i < npoints; ++i) {
        unsigned w1 = i*5;
        double x = (w1*2.0/widthReturn - 1.0)*MAX_X + total_shift_x;
        double y = f(x) + total_shift_y;
        points[i].x = w1;
        points[i].y = (1.0 - (y/MAX_Y))*heightReturn / 2.0;
    }

    XDrawLines(display, win, gc, points, npoints, CoordModeOrigin);
    free (points);
}

int main() {
    Display *dpy;
    int screen;
    Window win;
    Window rootWin;
    XEvent event;
    Status rc;
    int major, minor;

    unsigned int depth;
    XSetWindowAttributes attrs;

    dpy = XOpenDisplay(NULL);

    if (dpy == NULL) {
        fprintf(stderr, "Cannot open display\n");
        exit(1);
    }

    screen = DefaultScreen(dpy);
    depth = DefaultDepth(dpy, screen);
    rootWin = RootWindow(dpy, screen);

    attrs.border_pixel = BlackPixel(dpy, screen);
    attrs.background_pixel = WhitePixel(dpy, screen);
    attrs.override_redirect = True;
    attrs.colormap = CopyFromParent;
    attrs.event_mask = ExposureMask | KeyPressMask | ButtonPressMask | Button1MotionMask | ButtonReleaseMask;

    win = XCreateWindow(dpy, rootWin, 700, 700, 500, 300, 0, depth, InputOutput, CopyFromParent, CWBackPixel | CWColormap | CWBorderPixel | CWEventMask, &attrs);

    XMapWindow(dpy, win);

    rc = XdbeQueryExtension(dpy, &major, &minor);
    assert (rc);

    XdbeBackBuffer bbuf = XdbeAllocateBackBufferName(dpy, win, XdbeBackground);
    XdbeSwapInfo swapInfo = { .swap_window = win, .swap_action = XdbeBackground};

    for (;;) {
        XNextEvent(dpy, &event);
        switch(event.type) {
        case Expose:
            draw(dpy, bbuf, -1, -1, 1);
            XdbeSwapBuffers (dpy, &swapInfo, 1);
            break;

        case ButtonRelease:
            switch (event.xbutton.button) {
            case Button1:
                x_prev_position = -1;
                y_prev_position = -1;

                break;
            }
            break;
        case MotionNotify:
            draw(dpy, bbuf, event.xmotion.x, event.xmotion.y, 0);
            XdbeSwapBuffers (dpy, &swapInfo, 1);
            break;

        case KeyPress:
            if (XLookupKeysym(&event.xkey, 0) == XK_q) {
                XdbeDeallocateBackBufferName(dpy, bbuf);
                XDestroyWindow(dpy, win);
                XCloseDisplay(dpy);
                exit(0);
            }
        }
    }

    return 1;
}

Из подводных граблей можно выделить:

  • Хотя типы Drawable и Window в большинстве случаев взаимозаменяемые, нельзя передавать двойной буфер в функцию которая ожидает Window. И компилятор об этом не предупредит.
  • Из этого следует, что нельзя пользоваться XClearWindow(), вместо оной следует, например, передавать .swap_action = XdbeBackground в XdbeSwapBuffers (), что даёт сразу очищенный буфер.
  • Линкеру окромя -lX надо будет также передать -lXext.

Кроме того в коде есть пара мелких изменений не связанных с двойной буферизацией:

  • Изменено условие выхода.
  • Немного оптимизирована отрисовка линии.
3
  • Большое спасибо! Правда, когда я компилирую, у меня выводятся сообщения об ошибке линкёра о том, что функции Xdbe* не были найдены. Это расширение надо как-то установить? Я погуглил, говорят, на Ubuntu оно должно быть в пакете libxext-dev. Пакет у меня есть, а функции не находятся :С 12 апр 2018 в 8:09
  • @АлександрЧи -lXext скорми линкеру
    – Fat-Zer
    12 апр 2018 в 8:14
  • Оно летает, спасибо * - * 12 апр 2018 в 11:56

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.