【问题标题】:How to speed up drawing with Cairo on Opengl windows?如何在 Opengl windows 上加速使用 Cairo 绘图?
【发布时间】:2016-03-29 04:33:53
【问题描述】:

我的问题是如何加快在 windows 上的 OpenGL 上绘图。

测试代码如下。我从网上的一些 cairo 示例中复制了它。

fps 下降到每秒 30 到 40,甚至比网络浏览器还要慢。

每帧画一条线,我尝试在 html5 上编写 javascript。同一个函数只是画一条线,而且运行得更快。

为什么cairo在opengl上画线这么慢?我做错什么了吗? 以及如何加快速度?

我认为c++应该比javascript快很多

#include <stdlib.h>
#include <stdio.h>
#include <malloc.h>

#define _USE_MATH_DEFINES
#include <math.h>

#include <iostream>
#include <chrono>
#include <random>

#include <gl/glut.h>
#include <gl/glext.h>

#include <cairo.h>

using namespace std;

double win_width = 800;
double win_height = 600;
double hw = win_width / 2;
double hh = win_height / 2;
double line_width = 1;
//double line_width = 1 / win_width;

cairo_surface_t * surf = NULL;
cairo_t         * cr = NULL;
unsigned char   * surf_data = NULL;

GLuint texture_id;

// Interface //

void opengl_init(void)
{
    printf("OpenGL version: %s\n", glGetString(GL_VERSION));
    printf("OpenGL vendor: %s\n", glGetString(GL_VENDOR));
    printf("OpenGL renderer: %s\n", glGetString(GL_RENDERER));

    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
    glDisable(GL_DEPTH_TEST);
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glEnable(GL_TEXTURE_RECTANGLE_ARB);
}

void opengl_cleanup(void)
{
    glDeleteTextures(1, &texture_id);
}

void opengl_draw(int width, int height, unsigned char * surf_data)
{
    if (!surf_data)
    {
        printf("draw_func() - No valid pointer to surface-data passed\n");
        return;
    }

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glClear(GL_COLOR_BUFFER_BIT);

    glPushMatrix();

    glBindTexture(GL_TEXTURE_RECTANGLE_ARB, texture_id);
    glTexImage2D(GL_TEXTURE_RECTANGLE_ARB,
        0,
        GL_RGBA,
        width,
        height,
        0,
        GL_BGRA,
        GL_UNSIGNED_BYTE,
        surf_data);

    glColor3f(0.25f, 0.5f, 1.0f);
    glBegin(GL_QUADS);
    glTexCoord2f(0.0f, 0.0f);
    glVertex2f(0.0f, 0.0f);
    glTexCoord2f((GLfloat)width, 0.0f);
    glVertex2f(1.0f, 0.0f);
    glTexCoord2f((GLfloat)width, (GLfloat)height);
    glVertex2f(1.0f, 1.0f);
    glTexCoord2f(0.0f, (GLfloat)height);
    glVertex2f(0.0f, 1.0f);
    glEnd();

    glPopMatrix();
}

void opengl_resize(int width, int height)
{
    glViewport(0, 0, width, height);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(0.0f, 1.0f, 0.0f, 1.0f, -1.0f, 1.0f);

    glClear(GL_COLOR_BUFFER_BIT);

    glDeleteTextures(1, &texture_id);
    glGenTextures(1, &texture_id);
    glBindTexture(GL_TEXTURE_RECTANGLE_ARB, texture_id);
    glTexImage2D(GL_TEXTURE_RECTANGLE_ARB,
        0,
        GL_RGBA,
        width,
        height,
        0,
        GL_BGRA,
        GL_UNSIGNED_BYTE,
        NULL);
    glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);
}


void drawShape()
{
    //save current brush
    cairo_save(cr);

    // clear background
    cairo_set_operator(cr, CAIRO_OPERATOR_OVER);
    //cairo_scale(cr, (double)win_height / 1.0f, (double)win_height / 1.0f);
    cairo_set_source_rgba(cr, 1, 1, 1, 1);
    cairo_paint(cr);

    //set line color and style
    cairo_set_line_cap(cr, CAIRO_LINE_CAP_ROUND);
    cairo_set_line_width(cr, line_width);



    static double angle = 0;
    angle += 0.01f;

    //draw rect
    cairo_set_source_rgba(cr, 1, 0, 0, 1);
    //cairo_rectangle(cr, 0.5f + sinf(angle) * 0.1f, 0.5f, 0.1f, 0.1f);
    cairo_rectangle(cr, hw + sin(angle) * 100, hh, 100, 100);
    cairo_fill(cr);
    cairo_stroke(cr);

    //draw circle
    cairo_set_source_rgba(cr, 0, 0, 1, 1);
    cairo_arc(cr, 300, hh, 100, 0, 2 * M_PI);
    //cairo_fill(cr);
    cairo_stroke(cr);

    //draw line
    static double r = 100;
    static double posx = 500;
    static double posy = 500;
    static double x = 0;
    static double y = 0;

    x = r * cosf(angle);
    y = r * sinf(angle);

    cairo_set_source_rgba(cr, 0, 1, 0, 1);
    cairo_move_to(cr, x + posx, y + posy);
    cairo_line_to(cr, -x + posx, -y + posy);
    cairo_stroke(cr);


    int minx = 5;
    int maxx = win_width - 5;
    int miny = 5;
    int maxy = win_height - 5;
    int n = 50 * 2;

    std::default_random_engine randomEngine;
    randomEngine.seed(std::chrono::steady_clock::now().time_since_epoch().count());


    std::uniform_real_distribution<float> rangeX(minx, maxx);
    std::uniform_real_distribution<float> rangeY(miny, maxy);

    cairo_set_source_rgba(cr, 0, 0, 0, 1);
    for (int i = 0; i < n * 2; i += 4)
    {
        float x1 = rangeX(randomEngine);
        float y1 = rangeY(randomEngine);

        float x2 = rangeX(randomEngine);
        float y2 = rangeY(randomEngine);

        cairo_move_to(cr, x1, y1);
        cairo_line_to(cr, x2, y2);

    }
    cairo_stroke(cr);


    //restore previous brush
    cairo_restore(cr);
}


void display(void)
{
    static int fps = 0;
    static int frame = 0;
    static long long startTime = chrono::system_clock::now().time_since_epoch().count();
    static long long lastTime = 2;
    long long now = chrono::system_clock::now().time_since_epoch().count();

    ++frame;

    //update per second
    if (now - lastTime > 10000000)
    {
        lastTime = now;
        fps = frame;
        frame = 0;
        cout << fps << endl;
    }

    drawShape();

    opengl_draw(win_width, win_height, surf_data);

    glutSwapBuffers();
}

cairo_t*
create_cairo_context(int               width,
    int               height,
    int               channels,
    cairo_surface_t** surf,
    unsigned char**   buffer)
{
    cairo_t* cr;

    // create cairo-surface/context to act as OpenGL-texture source
    *buffer = (unsigned char*)calloc(channels * width * height, sizeof(unsigned char));
    if (!*buffer)
    {
        printf("create_cairo_context() - Couldn't allocate buffer\n");
        return NULL;
    }

    *surf = cairo_image_surface_create_for_data(*buffer,
        CAIRO_FORMAT_ARGB32,
        width,
        height,
        channels * width);
    if (cairo_surface_status(*surf) != CAIRO_STATUS_SUCCESS)
    {
        free(*buffer);
        printf("create_cairo_context() - Couldn't create surface\n");
        return NULL;
    }

    cr = cairo_create(*surf);
    if (cairo_status(cr) != CAIRO_STATUS_SUCCESS)
    {
        free(*buffer);
        printf("create_cairo_context() - Couldn't create context\n");
        return NULL;
    }

    return cr;
}

void cleanup(void)
{
    opengl_cleanup();
    free(surf_data);
    cairo_destroy(cr);
    exit(0);
}

void keyboard(unsigned char key, int x, int y)
{
    switch (key)
    {
    //27 is ESC key
    case 27:
    case 'q':
        cleanup();
        break;

    case 'd':
        cairo_surface_write_to_png(surf, "frame.png");
        break;

    case '+':
        if (line_width < 10)
            line_width += 1;
        break;

    case '-':
        if (line_width > 1)
            line_width -= 1;
        break;

    }
}

void idle(void)
{
    glutPostRedisplay();
}

int main(int argc, char ** argv)
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA);
    glutInitWindowSize(win_width, win_height);

    if (glutCreateWindow("Opengl Test") == 0)
        exit(-2);

    // create cairo-surface/context to act as OpenGL-texture source
    cr = create_cairo_context(win_width, win_height, 4, &surf, &surf_data);

    // setup "GL-context"
    opengl_init();

    glutDisplayFunc(display);
    glutKeyboardFunc(keyboard);
    glutIdleFunc(idle);
    opengl_resize(win_width, win_height);

    glutMainLoop();

    return 0;
}

这是我使用的html和js

index.html

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script type="text/javascript" src="main.js"></script>
    <style type="text/css">
    html, body {
        margin: 0px;
    }

    canvas {
        display: block;
    }

    </style>
</head>
<body>
<canvas id="canvas"></canvas>
</body>
</html>

main.js

window.onload = function() {
    var canvas = document.getElementById("canvas"),
        context = canvas.getContext("2d"),
        width = canvas.width = window.innerWidth,
        height = canvas.height = window.innerHeight;

    render();

    function render() {
        context.clearRect(0, 0, width, height);
        for(var i = 0; i < 100; i += 1){
            context.beginPath();
            context.moveTo(Math.random() * width, Math.random() * height);
            context.lineTo(Math.random() * width, Math.random() * height);
            context.stroke();
        }
        requestAnimationFrame(render);
    }   
};

【问题讨论】:

    标签: c++ windows performance opengl cairo


    【解决方案1】:

    您的瓶颈实际上不是 OpenGL,而是 Cairo。您正在使用具有标准软件光栅化后端的 Cairo;因此 CPU 承担了所有繁重的工作,而 OpenGL 只是用作美化的表面 blitter。诚然,将完成的图像加载到 OpenGL 中的方法不是最佳的(应该使用 glTexSubImage2D 代替 glTexImage2D),但这几乎不是您的瓶颈。

    那么你应该怎么做:理想情况下,你会为​​ Cairo 使用 OpenGL 加速后端,如 http://cairographics.org/OpenGL/ 中所述

    另一个选择是放弃 Cairo 并使用直接针对 OpenGL 的矢量渲染库;我在这里考虑的是 NanoVG(我与这个项目没有隶属关系)。 NanoVG 的主要优势在于,其整个内部架构在设计时都考虑到了 OpenGL 作为后端。

    如果你想分析错误选择的纹理上传方法的影响,这里有一个固定的代码变体(删除opengl_cleanup,它对这个例子没有任何好处,也去掉opengl_resize,这是非常糟糕的练习在调整大小处理程序中进行投影设置)。

    void opengl_draw(int width, int height, void const * surf_data)
    {
        static GLuint texture_id = 0;
        static int tex_width = 0;
        static int tex_height = 0;
    
        if (!surf_data)
        {
            printf("draw_func() - No valid pointer to surface-data passed\n");
            return;
        }
    
        if( !texture_id ) {
            glGenTextures(1, &texture_id);
        }
        glBindTexture(GL_TEXTURE_RECTANGLE_ARB, texture_id);
        if( width != tex_width || height != tex_height ) {
            glTexImage2D(GL_TEXTURE_RECTANGLE_ARB,
                0,
                GL_RGBA,
                tex_width = width,
                tex_height = height,
                0,
                GL_BGRA,
                GL_UNSIGNED_BYTE,
                surf_data);
        } else {
            glTexSubImage2D(GL_TEXTURE_RECTANGLE_ARB,
                0, 0, 0,
                tex_width, tex_height,
                GL_BGRA,
                GL_UNSIGNED_BYTE,
                surf_data);
        }
    
        glViewport(0, 0, width, height);
    
        glMatrixMode(GL_PROJECTION);
        glPushMatrix();
        glLoadIdentity();
        glOrtho(0.0f, 1.0f, 0.0f, 1.0f, -1.0f, 1.0f);
    
        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();
        glPushMatrix();
    
        glColor3f(0.25f, 0.5f, 1.0f);
        glBegin(GL_QUADS);
        glTexCoord2f(0.0f, 0.0f);
        glVertex2f(0.0f, 0.0f);
        glTexCoord2f((GLfloat)width, 0.0f);
        glVertex2f(1.0f, 0.0f);
        glTexCoord2f((GLfloat)width, (GLfloat)height);
        glVertex2f(1.0f, 1.0f);
        glTexCoord2f(0.0f, (GLfloat)height);
        glVertex2f(0.0f, 1.0f);
        glEnd();
    
        glMatrixMode(GL_PROJECTION);
        glPopMatrix();
        glMatrixMode(GL_MODELVIEW);
        glPopMatrix();
    }
    

    每帧画一条线,我尝试在 html5 上编写 javascript。同一个函数只是画一条线,而且运行得更快。

    你认为这告诉你什么?我可以以任何满足规范的方式实现 HTML Canvas。浏览器可能使用 Cairo,它自己的渲染引擎,可能使用也可能不使用 GPU。这不是一个有用的比较,因为你不知道你在那里实际比较的是什么。

    【讨论】:

    • 谢谢你,datenwolf。我不是以英语为母语的人,你是什么意思——理想情况下你会为开罗使用 OpenGL 加速后端?我没有找到任何描述或链接那个opengl页面。我到底应该使用什么加速后端?
    • 我只想在 Opengl 上每帧画大约 512 - 1024 条线,最好是矢量绘图,所以我尝试了 Cairo,我听说 cairo 可以在许多上下文中绘制,所以我只是尝试一下。没有意识到它使用的CPU或GPU。但我不仅限于Cario,我现在会尝试NanoVG,看看它是否可以快速绘制每帧1024行
    • 好的,在 gl3 示例中以每秒 3000 行的速度尝试了 NanoVG,我的计算机为 100+ fps,我对结果非常满意,再次感谢,datenwolf,我想我会使用 NanoVG而是:)
    【解决方案2】:

    在 Windows 上用 OpenGL 后端编译 cairo 非常痛苦。但我是这样做的。使用 x86_64-w64-mingw32 工具链在 cygwin 和 msys2 上工作。

    1. Cygwin 为 Win64 提供了预编译的 cairo 包。它不支持 OpenGL。但是,如果您安装该软件包,它将自动引入 cairo 的所有依赖项,包括 pixman。同时安装 GLEW 包(OpenGL Extension Wrangler)。

    2. 下载 cairo 源代码,并将其解压缩到您的工作区。

    3. 打开配置文件。搜索 -lGL 并将所有实例替换为 -lglew32 -lopengl32。这将使 cairo 链接到 Windows OpenGL 库而不是 Linux 库。这里的库名区分大小写,必须与C:\Windows\system32中的opengl32.dll匹配。如果没有,那么构建系统会抱怨找不到opengl32.dll

    4. 打开src/cairo-gl.h。线下

      #if CAIRO_HAS_GL_SURFACE || CAIRO_HAS_GLESV2_SURFACE
      

      添加

      #include <GL/glew.h>
      

      线下

      #if CAIRO_HAS_WGL_FUNCTIONS
      

      添加

      #include <GL/wglew.h>
      

      此文件必须在 windows.h 之前包含,否则 GLEW 会抱怨 gl.h 已包含。

    5. cairo wgl 设备创建过程中存在错误。基本上 cairo 将创建一个不可见的窗口,并将您提供的 GL 上下文附加到该窗口。但是,如果您的上下文与虚拟窗口的像素格式不同,则绑定将失败。这是我的快速修复。打开src/cairo-wgl-context.c,找到static cairo_status_t _wgl_dummy_ctx (cairo_wgl_context_t *ctx)

      行前

      wglMakeCurrent(ctx->dummy_dc, ctx->rc);
      

      添加

      ctx->rc = wglCreateContextAttribsARB(ctx->dummy_dc,ctx->rc,NULL);
      
    6. 现在执行

      ./configure --host=x86_64-w64-mingw32 --enable-gl --enable-wgl
      make
      

      如果configure 抱怨找不到某些程序,首先确保安装了 Win64 工具链的 binutils。然后使用ln 硬链接到带有x86_64-w64-mingw32 前缀的程序。

      test 文件夹中的 make 过程不可避免地会失败,因为它会尝试编译需要 Linux GL 库的测试。忽略失败,转至/src/.libs。您应该会看到 libcairo-2.dll 和链接所需的其他文件。

      最常见的问题是只产生libcairo.a,而没有产生libcairo-2.dll。确保您完全按照我所说的修改了configure 文件。

    7. libcairo-2.dll 复制到您想要的任何位置。如果您的程序动态链接到 cairo,它现在应该可以正常工作了。但是,如果要静态链接,还有另一个复杂之处。 cairo 的某些部分使用 Windows 临界区来实现互斥锁。关键部分在 DllMain 期间初始化。但是,如果您静态链接,则必须手动初始化它们。只需在cairo-mutex.c 中调用void _cairo_mutex_initialize (void) 函数即可。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多