溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

基于Qt的OpenGL可編程管線學(xué)習(xí)(3)- 使用Instanced方式繪制

發(fā)布時間:2020-07-23 19:35:03 來源:網(wǎng)絡(luò) 閱讀:1182 作者:Douzhq 欄目:編程語言

繪制多個重復(fù)的模型時,使用Instanced方式繪制可以大大加快顯然速度。

繪制效果如下圖所示:

基于Qt的OpenGL可編程管線學(xué)習(xí)(3)- 使用Instanced方式繪制


1、Vertex Shader中定義如下:

attribute vec3 pos;
attribute vec2 coord;
attribute vec3 normal;
attribute vec3 offset;

uniform mat4 M;
uniform mat4 V;
uniform mat4 P;
uniform mat4 NM;

varying vec2 M_coord;
varying vec3 M_normal;
varying vec4 M_WordPos;

void main()
{
        M_coord = coord;
        M_WordPos = M * vec4(pos, 1.0) + vec4(offset, 1.0);
        M_normal = mat3(NM) * normal;
        gl_Position = P * V * M_WordPos;
}

offset為每次繪制的偏移量。


2、CPU端實現(xiàn)

float nIndexOffset[] = {
        -100.0f, 0.0f, 0.0f,
        0.0f, 0.0f, 0.0f,
        100.0f, 0.0f, 0.0f
    };

createBufferObject為封裝創(chuàng)建OpenGL Buffer的函數(shù)

定義如下:

GLuint OpenGLOperate::createBufferObject(GLenum nBufferType, GLsizeiptr size, \
                                            const GLvoid *data, GLenum usage)
{
    GLuint BufferObjIndex = 0;
    m_OpenGLCore->glGenBuffers(1, &BufferObjIndex);
    m_OpenGLCore->glBindBuffer(nBufferType, BufferObjIndex);
    m_OpenGLCore->glBufferData(nBufferType, size, data, usage);
    m_OpenGLCore->glBindBuffer(nBufferType, 0);
    return BufferObjIndex;
}

創(chuàng)建Offset的FBO

m_OffsetIndex = m_OpenGLOperate->createBufferObject(GL_ARRAY_BUFFER, \
                                sizeof(float) * 9, \
                                (void*)nIndexOffset, GL_STATIC_DRAW);

為Offset賦值

OpenGLCore->glBindBuffer(GL_ARRAY_BUFFER, m_OffsetIndex);
OpenGLCore->glEnableVertexAttribArray(m_OffsetLocation);
OpenGLCore->glVertexAttribPointer(m_OffsetLocation, 3, GL_FLOAT, GL_FALSE, \
sizeof(float) * 3, (void*)0);
OpenGLCore->glBindBuffer(GL_ARRAY_BUFFER, 0);
OpenGLCore->glVertexAttribDivisor(m_OffsetLocation, 1);

調(diào)用繪制指令:

OpenGLCore->glDrawElementsInstanced(GL_TRIANGLES, m_VertexCount, \
                                    GL_UNSIGNED_INT, 0, 3);


向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI