예제 #1
0
// This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure)
// If text or lines are blurry when integrating ImGui in your engine:
// - in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f)
static void ImGui_ImplGlfwGL3_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
{
    if (cmd_lists_count == 0)
        return;

    // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
    GLint last_program, last_texture;
    glGetIntegerv(GL_CURRENT_PROGRAM, &last_program);
    glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
    glEnable(GL_BLEND);
    glBlendEquation(GL_FUNC_ADD);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glDisable(GL_CULL_FACE);
    glDisable(GL_DEPTH_TEST);
    glEnable(GL_SCISSOR_TEST);
    glActiveTexture(GL_TEXTURE0);

    // Setup orthographic projection matrix
    const float width = ImGui::GetIO().DisplaySize.x;
    const float height = ImGui::GetIO().DisplaySize.y;
    const float ortho_projection[4][4] =
    {
        { 2.0f/width,	0.0f,			0.0f,		0.0f },
        { 0.0f,			2.0f/-height,	0.0f,		0.0f },
        { 0.0f,			0.0f,			-1.0f,		0.0f },
        { -1.0f,		1.0f,			0.0f,		1.0f },
    };
    glUseProgram(g_ShaderHandle);
    glUniform1i(g_AttribLocationTex, 0);
    glUniformMatrix4fv(g_AttribLocationProjMtx, 1, GL_FALSE, &ortho_projection[0][0]);

    // Grow our buffer according to what we need
    size_t total_vtx_count = 0;
    for (int n = 0; n < cmd_lists_count; n++)
        total_vtx_count += cmd_lists[n]->vtx_buffer.size();
    glBindBuffer(GL_ARRAY_BUFFER, g_VboHandle);
    size_t needed_vtx_size = total_vtx_count * sizeof(ImDrawVert);
    if (g_VboSize < needed_vtx_size)
    {
        g_VboSize = needed_vtx_size + 5000 * sizeof(ImDrawVert);  // Grow buffer
        glBufferData(GL_ARRAY_BUFFER, g_VboSize, NULL, GL_STREAM_DRAW);
    }

    // Copy and convert all vertices into a single contiguous buffer
    unsigned char* buffer_data = (unsigned char*)glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY);
    if (!buffer_data)
        return;
    for (int n = 0; n < cmd_lists_count; n++)
    {
        const ImDrawList* cmd_list = cmd_lists[n];
        memcpy(buffer_data, &cmd_list->vtx_buffer[0], cmd_list->vtx_buffer.size() * sizeof(ImDrawVert));
        buffer_data += cmd_list->vtx_buffer.size() * sizeof(ImDrawVert);
    }
    glUnmapBuffer(GL_ARRAY_BUFFER);
    glBindBuffer(GL_ARRAY_BUFFER, 0);
    glBindVertexArray(g_VaoHandle);

    int cmd_offset = 0;
    for (int n = 0; n < cmd_lists_count; n++)
    {
        const ImDrawList* cmd_list = cmd_lists[n];
        int vtx_offset = cmd_offset;
        const ImDrawCmd* pcmd_end = cmd_list->commands.end();
        for (const ImDrawCmd* pcmd = cmd_list->commands.begin(); pcmd != pcmd_end; pcmd++)
        {
            if (pcmd->user_callback)
            {
                pcmd->user_callback(cmd_list, pcmd);
            }
            else
            {
                glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->texture_id);
                glScissor((int)pcmd->clip_rect.x, (int)(height - pcmd->clip_rect.w), (int)(pcmd->clip_rect.z - pcmd->clip_rect.x), (int)(pcmd->clip_rect.w - pcmd->clip_rect.y));
                glDrawArrays(GL_TRIANGLES, vtx_offset, pcmd->vtx_count);
            }
            vtx_offset += pcmd->vtx_count;
        }
        cmd_offset = vtx_offset;
    }

    // Restore modified state
    glBindVertexArray(0);
    glUseProgram(last_program);
    glDisable(GL_SCISSOR_TEST);
    glBindTexture(GL_TEXTURE_2D, last_texture);
}
예제 #2
0
    void ParticlePainter::Render(unsigned int& renderIndex,GFX::FBOTexture* particleTarget, GFX::FBOTexture* depthBuffer, 
		GFX::FBOTexture* normalDepth, GFX::FBOTexture* specular, GFX::FBOTexture* glowMatID, GLuint toneMappedTexture, 
		const glm::mat4& viewMatrix, const glm::mat4& projectionMatrix, float gamma, RenderInfo& out_RenderInfo)
    {
		BasePainter::Render();
		unsigned int numDrawCalls = 0;
		unsigned int numTris = 0;

        glBindFramebuffer(GL_FRAMEBUFFER, m_FBO);

        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, particleTarget->GetTextureHandle(), 0);

        glDrawBuffer(GL_COLOR_ATTACHMENT0);

        glClear(GL_COLOR_BUFFER_BIT);
        
        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D, depthBuffer->GetTextureHandle(), 0);
        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, glowMatID->GetTextureHandle(), 0);

        GLenum particleDrawBuffers[] = { GL_NONE, GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 };

        glDrawBuffers(3, particleDrawBuffers);

        glEnable(GL_DEPTH_TEST);
        glDepthMask(GL_FALSE);

	    BasicCamera bc;
		bc.viewMatrix = viewMatrix;
		bc.projMatrix = projectionMatrix;

		m_uniformBufferManager->SetBasicCameraUBO(bc);

        std::vector<GFX::RenderJobManager::RenderJob> renderJobs = m_renderJobManager->GetJobs();

        unsigned int currentShader = std::numeric_limits<decltype(currentShader)>::max();
        unsigned int currentMesh = std::numeric_limits<decltype(currentMesh)>::max();
        unsigned int currentMaterial = std::numeric_limits<decltype(currentMaterial)>::max();
        unsigned int currentLayer = std::numeric_limits<decltype(currentLayer)>::max();
        unsigned int currentTranslucency = std::numeric_limits<decltype(currentTranslucency)>::max();

        unsigned int mesh = 0;        
        unsigned int material = 0;        
        unsigned int layer = 0;
        unsigned int translucency = 0;
        unsigned int objectType = 0;

        const GFX::ParticleData* particleData;
        GFX::GFXBitmask renderJob;


        for(unsigned int i=0; renderIndex < renderJobs.size(); ++i, ++renderIndex)        
        {
            renderJob = renderJobs[renderIndex].bitmask;
            
            objectType = GFX::GetBitmaskValue(renderJob, GFX::BITMASK::TYPE);

            if(objectType != GFX::OBJECT_TYPES::PARTICLE_GEOMETRY)
            {
                renderIndex--;
                break;
            }            

            layer = GetBitmaskValue(renderJob, GFX::BITMASK::LAYER);
            translucency = GetBitmaskValue(renderJob, GFX::BITMASK::TRANSLUCENCY_TYPE);
            mesh = GetBitmaskValue(renderJob, GFX::BITMASK::MESH_ID);
            material = GetBitmaskValue(renderJob, GFX::BITMASK::MATERIAL_ID);


            if(material != currentMaterial)
            {
                GFX::Material mat = m_materialManager->GetMaterial(material);
                
                currentMaterial = material;

                if(mat.shaderProgramID != currentShader)
                {
                    currentShader = mat.shaderProgramID;

                    m_texture0Uniform = m_shaderManager->GetUniformLocation(currentShader, "gDiffuse");
                    m_texture1Uniform = m_shaderManager->GetUniformLocation(currentShader, "gNormal");
                    m_texture2Uniform = m_shaderManager->GetUniformLocation(currentShader, "gSpecular");
                    m_texture3Uniform = m_shaderManager->GetUniformLocation(currentShader, "gGlow");
                    m_depthBufferSizeUniform = m_shaderManager->GetUniformLocation(currentShader, "depthBufferSize");
                    m_depthBufferUniform = m_shaderManager->GetUniformLocation(currentShader, "gDepthBuffer");
                    m_gammaUniform = m_shaderManager->GetUniformLocation(currentShader, "gGamma");
                }
                
                glUseProgram(currentShader);

                m_textureManager->BindTexture(m_textureManager->GetTexture(mat.textures[0]).textureHandle, m_texture0Uniform, 0, GL_TEXTURE_2D);
                m_textureManager->BindTexture(m_textureManager->GetTexture(mat.textures[1]).textureHandle, m_texture1Uniform, 1, GL_TEXTURE_2D);
                m_textureManager->BindTexture(m_textureManager->GetTexture(mat.textures[2]).textureHandle, m_texture2Uniform, 2, GL_TEXTURE_2D);
                m_textureManager->BindTexture(m_textureManager->GetTexture(mat.textures[3]).textureHandle, m_texture3Uniform, 3, GL_TEXTURE_2D);

                if(m_depthBufferUniform >= 0)
                {
                    m_textureManager->BindTexture(normalDepth->GetTextureHandle(), m_depthBufferUniform, 4, GL_TEXTURE_2D);
                }

                if(m_depthBufferSizeUniform >= 0)
                {
                    glUniform2fv(m_depthBufferSizeUniform, 1, &glm::vec2(normalDepth->GetWidth(), normalDepth->GetHeight())[0]);
                }

                if(m_gammaUniform >= 0)
                {
                    glUniform1f(m_depthBufferSizeUniform, gamma);
                }
            }

            if(mesh != currentMesh)
            {
                currentMesh = mesh;
                particleData = m_particleManager->GetParticleData(currentMesh);

                //TODO: Remove this check once the level heap is destroyed in a finalizer in the content manager
                //This check is needed since the level heap is destroyed before calling render. The particle data is destroyed when the level heap is cleared.
                if(particleData == nullptr)
                {
                    continue;
                }
                
                glBindBuffer(GL_ARRAY_BUFFER, particleData->VBO);
                glBindVertexArray(particleData->VAO);
            }
            
            if(translucency != currentTranslucency)
            {
                currentTranslucency = translucency;
                switch (currentTranslucency)
                {
				case GFX::TRANSLUCENCY_TYPES::OPAQUE_TRANSLUCENCY:
                    {
                        glDisable(GL_BLEND);
                        glBlendEquation(GL_FUNC_ADD);
                        glBlendFunc(GL_ONE, GL_ZERO);
                        break;
                    }

				case GFX::TRANSLUCENCY_TYPES::ADDITIVE_TRANSLUCENCY:
                    {
                        glEnable(GL_BLEND);
                        glBlendEquation(GL_FUNC_ADD);
                        glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
                        break;
                    }

				case GFX::TRANSLUCENCY_TYPES::SUBTRACTIVE_TRANSLUCENCY:
                    {
                        glEnable(GL_BLEND);
                        glBlendEquation(GL_FUNC_SUBTRACT);
                        glBlendFunc(GL_SRC_ALPHA, GL_ONE);
                        break;
                    }

				case GFX::TRANSLUCENCY_TYPES::MULTIPLICATIVE_TRANSLUCENCY:
                    {
                        glEnable(GL_BLEND);
                        glBlendEquation(GL_FUNC_ADD);
                        glBlendFunc(GL_DST_COLOR, GL_ZERO);
                        break;
                    }
                }
            }

            if(layer != currentLayer)            
            {
                currentLayer = layer;
                switch (currentLayer)
                {
                    case GFX::LAYER_TYPES::OUTLINE_LAYER:
                    {
						glDisable(GL_DEPTH_TEST);
						glStencilFunc(GL_NOTEQUAL, 1, -1);
						glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
						glLineWidth(m_outlineThickness);
						glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
                        break;
                    }
                    case GFX::LAYER_TYPES::MESH_LAYER:
                    {
						glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
						glEnable(GL_DEPTH_TEST);
						glDisable(GL_STENCIL_TEST);
                        break;
                    }
                }
            }
            glDrawArrays(GL_POINTS, 0, particleData->particleCount);
			numDrawCalls++;
			numTris += 2 * particleData->particleCount;
        }
        
        glBindFramebuffer(GL_FRAMEBUFFER, m_FBO);

        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D, depthBuffer->GetTextureHandle(), 0);
        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, normalDepth->GetTextureHandle(), 0);
        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, toneMappedTexture, 0);
        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, GL_TEXTURE_2D, specular->GetTextureHandle(), 0);
        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT3, GL_TEXTURE_2D, glowMatID->GetTextureHandle(), 0);

        GLenum drawBuffers[] = { GL_NONE, GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2, GL_COLOR_ATTACHMENT3 };

        glDrawBuffers(5, drawBuffers);
        glEnable(GL_BLEND);
        glBlendEquation(GL_FUNC_ADD);
        glBlendFunc(GL_SRC_ALPHA, GL_ONE);    
       
        m_shaderManager->UseProgram("ParticleApply");
        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, particleTarget->GetTextureHandle());

        glBindVertexArray(m_dummyVAO);
        glDrawArrays(GL_POINTS, 0, 1);
        
        glDisable(GL_BLEND);
        glDepthMask(GL_TRUE);
		out_RenderInfo.numDrawCalls = numDrawCalls;
		out_RenderInfo.numTris = numTris;
    }
예제 #3
0
void ImGuiRenderer::renderDrawList(ImDrawData *draw_data)
{
    // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
    ImGuiIO& io = ImGui::GetIO();
    int fb_width = (int)(io.DisplaySize.x * io.DisplayFramebufferScale.x);
    int fb_height = (int)(io.DisplaySize.y * io.DisplayFramebufferScale.y);
    if (fb_width == 0 || fb_height == 0)
        return;
    draw_data->ScaleClipRects(io.DisplayFramebufferScale);

    // Backup GL state
    GLint last_active_texture; glGetIntegerv(GL_ACTIVE_TEXTURE, &last_active_texture);
    glActiveTexture(GL_TEXTURE0);
    GLint last_program; glGetIntegerv(GL_CURRENT_PROGRAM, &last_program);
    GLint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
    GLint last_array_buffer; glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer);
    GLint last_element_array_buffer; glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &last_element_array_buffer);
    GLint last_vertex_array; glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array);
    GLint last_blend_src_rgb; glGetIntegerv(GL_BLEND_SRC_RGB, &last_blend_src_rgb);
    GLint last_blend_dst_rgb; glGetIntegerv(GL_BLEND_DST_RGB, &last_blend_dst_rgb);
    GLint last_blend_src_alpha; glGetIntegerv(GL_BLEND_SRC_ALPHA, &last_blend_src_alpha);
    GLint last_blend_dst_alpha; glGetIntegerv(GL_BLEND_DST_ALPHA, &last_blend_dst_alpha);
    GLint last_blend_equation_rgb; glGetIntegerv(GL_BLEND_EQUATION_RGB, &last_blend_equation_rgb);
    GLint last_blend_equation_alpha; glGetIntegerv(GL_BLEND_EQUATION_ALPHA, &last_blend_equation_alpha);
    GLint last_viewport[4]; glGetIntegerv(GL_VIEWPORT, last_viewport);
    GLint last_scissor_box[4]; glGetIntegerv(GL_SCISSOR_BOX, last_scissor_box);
    GLboolean last_enable_blend = glIsEnabled(GL_BLEND);
    GLboolean last_enable_cull_face = glIsEnabled(GL_CULL_FACE);
    GLboolean last_enable_depth_test = glIsEnabled(GL_DEPTH_TEST);
    GLboolean last_enable_scissor_test = glIsEnabled(GL_SCISSOR_TEST);

    // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
    glEnable(GL_BLEND);
    glBlendEquation(GL_FUNC_ADD);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glDisable(GL_CULL_FACE);
    glDisable(GL_DEPTH_TEST);
    glEnable(GL_SCISSOR_TEST);

    // Setup viewport, orthographic projection matrix
    glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height);
    //const float ortho_projection[4][4] =
    ngl::Mat4 ortho_projection
    (
         2.0f/io.DisplaySize.x, 0.0f,                   0.0f, 0.0f ,
         0.0f,                  2.0f/-io.DisplaySize.y, 0.0f, 0.0f ,
         0.0f,                  0.0f,                  -1.0f, 0.0f ,
        -1.0f,                  1.0f,                   0.0f, 1.0f
    );
    ngl::ShaderLib *shader = ngl::ShaderLib::instance();
    shader->use(ImGUIShader);
    shader->setUniform("Texture",0);
    shader->setUniform("ProjMtx",ortho_projection);
    std::unique_ptr<ngl::AbstractVAO> vao;
    vao=ngl::VAOFactory::createVAO(ngl::simpleIndexVAO,GL_TRIANGLES);

    vao->bind();
    for (int n = 0; n < draw_data->CmdListsCount; n++)
    {
        const ImDrawList* cmd_list = draw_data->CmdLists[n];
        const ImDrawIdx* idx_buffer_offset = nullptr;
        vao->setData(ngl::SimpleIndexVAO::VertexData(
                         cmd_list->VtxBuffer.Size * sizeof(ImDrawVert),
                         cmd_list->VtxBuffer.Data->pos.x,
                         (GLsizeiptr)cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx),(const GLvoid*)cmd_list->IdxBuffer.Data,
                         sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT));
        vao->setVertexAttributePointer(0,2,GL_FLOAT,sizeof(ImDrawVert), 0);
        vao->setVertexAttributePointer(1,2,GL_FLOAT,sizeof(ImDrawVert), 2);
        vao->setVertexAttributePointer(2,4,GL_UNSIGNED_BYTE,sizeof(ImDrawVert), 4,GL_TRUE);

        vao->setNumIndices(cmd_list->IdxBuffer.Size);
        for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
        {
            const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
            if (pcmd->UserCallback)
            {
                pcmd->UserCallback(cmd_list, pcmd);
            }
            else
            {
                glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->TextureId);
                glScissor((int)pcmd->ClipRect.x, (int)(fb_height - pcmd->ClipRect.w), (int)(pcmd->ClipRect.z - pcmd->ClipRect.x), (int)(pcmd->ClipRect.w - pcmd->ClipRect.y));
               // glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer_offset);
               vao->draw();
            }
            idx_buffer_offset += pcmd->ElemCount;
        }
    }
    vao->unbind();
    // Restore modified GL state
    glUseProgram(last_program);
    glBindTexture(GL_TEXTURE_2D, last_texture);
    glActiveTexture(last_active_texture);
    glBindVertexArray(last_vertex_array);
    glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, last_element_array_buffer);
    glBlendEquationSeparate(last_blend_equation_rgb, last_blend_equation_alpha);
    glBlendFuncSeparate(last_blend_src_rgb, last_blend_dst_rgb, last_blend_src_alpha, last_blend_dst_alpha);
    if (last_enable_blend) glEnable(GL_BLEND); else glDisable(GL_BLEND);
    if (last_enable_cull_face) glEnable(GL_CULL_FACE); else glDisable(GL_CULL_FACE);
    if (last_enable_depth_test) glEnable(GL_DEPTH_TEST); else glDisable(GL_DEPTH_TEST);
    if (last_enable_scissor_test) glEnable(GL_SCISSOR_TEST); else glDisable(GL_SCISSOR_TEST);
    glViewport(last_viewport[0], last_viewport[1], (GLsizei)last_viewport[2], (GLsizei)last_viewport[3]);
    glScissor(last_scissor_box[0], last_scissor_box[1], (GLsizei)last_scissor_box[2], (GLsizei)last_scissor_box[3]);
}
예제 #4
0
void BlendEquationProtocol::onBlendEquationEnd(
	const cocos2d::Mat4 &transform, uint32_t flags)
{
	glBlendEquation(GL_FUNC_ADD);
}
예제 #5
0
void rglBlendEquation(GLenum mode)
{
   glBlendEquation(mode);
}
// This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure)
// If text or lines are blurry when integrating ImGui in your engine:
// - in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f)
void ImGui_ImplCinder_RenderDrawLists(ImDrawData* draw_data)
{
    // Backup GL state
    GLint last_program; glGetIntegerv(GL_CURRENT_PROGRAM, &last_program);
    GLint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
    GLint last_array_buffer; glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer);
    GLint last_element_array_buffer; glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &last_element_array_buffer);
    GLint last_vertex_array; glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array);
	GLint last_blend_src; glGetIntegerv(GL_BLEND_SRC, &last_blend_src);
	GLint last_blend_dst; glGetIntegerv(GL_BLEND_DST, &last_blend_dst);
	GLint last_blend_equation_rgb; glGetIntegerv(GL_BLEND_EQUATION_RGB, &last_blend_equation_rgb);
	GLint last_blend_equation_alpha; glGetIntegerv(GL_BLEND_EQUATION_ALPHA, &last_blend_equation_alpha);
	GLboolean last_enable_blend = glIsEnabled(GL_BLEND);
	GLboolean last_enable_cull_face = glIsEnabled(GL_CULL_FACE);
	GLboolean last_enable_depth_test = glIsEnabled(GL_DEPTH_TEST);
	GLboolean last_enable_scissor_test = glIsEnabled(GL_SCISSOR_TEST);

    // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
    glEnable(GL_BLEND);
    glBlendEquation(GL_FUNC_ADD);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glDisable(GL_CULL_FACE);
    glDisable(GL_DEPTH_TEST);
    glEnable(GL_SCISSOR_TEST);
    glActiveTexture(GL_TEXTURE0);

    // Handle cases of screen coordinates != from framebuffer coordinates (e.g. retina displays)
    ImGuiIO& io = ImGui::GetIO();
    float fb_height = io.DisplaySize.y * io.DisplayFramebufferScale.y;
    draw_data->ScaleClipRects(io.DisplayFramebufferScale);

    // Setup orthographic projection matrix
    const float ortho_projection[4][4] =
    {
        { 2.0f/io.DisplaySize.x, 0.0f,                   0.0f, 0.0f },
        { 0.0f,                  2.0f/-io.DisplaySize.y, 0.0f, 0.0f },
        { 0.0f,                  0.0f,                  -1.0f, 0.0f },
        {-1.0f,                  1.0f,                   0.0f, 1.0f },
    };
    glUseProgram(g_ShaderHandle);
    glUniform1i(g_AttribLocationTex, 0);
    glUniformMatrix4fv(g_AttribLocationProjMtx, 1, GL_FALSE, &ortho_projection[0][0]);
    glBindVertexArray(g_VaoHandle);

    for (int n = 0; n < draw_data->CmdListsCount; n++)
    {
        const ImDrawList* cmd_list = draw_data->CmdLists[n];
        const ImDrawIdx* idx_buffer_offset = 0;

        glBindBuffer(GL_ARRAY_BUFFER, g_VboHandle);
        glBufferData(GL_ARRAY_BUFFER, (GLsizeiptr)cmd_list->VtxBuffer.size() * sizeof(ImDrawVert), (GLvoid*)&cmd_list->VtxBuffer.front(), GL_STREAM_DRAW);

        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_ElementsHandle);
        glBufferData(GL_ELEMENT_ARRAY_BUFFER, (GLsizeiptr)cmd_list->IdxBuffer.size() * sizeof(ImDrawIdx), (GLvoid*)&cmd_list->IdxBuffer.front(), GL_STREAM_DRAW);

        for (const ImDrawCmd* pcmd = cmd_list->CmdBuffer.begin(); pcmd != cmd_list->CmdBuffer.end(); pcmd++)
        {
            if (pcmd->UserCallback)
            {
                pcmd->UserCallback(cmd_list, pcmd);
            }
            else
            {
                glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->TextureId);
                glScissor((int)pcmd->ClipRect.x, (int)(fb_height - pcmd->ClipRect.w), (int)(pcmd->ClipRect.z - pcmd->ClipRect.x), (int)(pcmd->ClipRect.w - pcmd->ClipRect.y));
                glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer_offset);
            }
            idx_buffer_offset += pcmd->ElemCount;
        }
    }

    // Restore modified GL state
    glUseProgram(last_program);
    glBindTexture(GL_TEXTURE_2D, last_texture);
    glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, last_element_array_buffer);
    glBindVertexArray(last_vertex_array);
	glBlendEquationSeparate(last_blend_equation_rgb, last_blend_equation_alpha);
	glBlendFunc(last_blend_src, last_blend_dst);
	if (last_enable_blend) glEnable(GL_BLEND); else glDisable(GL_BLEND);
	if (last_enable_cull_face) glEnable(GL_CULL_FACE); else glDisable(GL_CULL_FACE);
	if (last_enable_depth_test) glEnable(GL_DEPTH_TEST); else glDisable(GL_DEPTH_TEST);
	if (last_enable_scissor_test) glEnable(GL_SCISSOR_TEST); else glDisable(GL_SCISSOR_TEST);
}
void FSlateOpenGLRenderingPolicy::DrawElements( const FMatrix& ViewProjectionMatrix, const TArray<FSlateRenderBatch>& RenderBatches )
{
	// Bind the vertex buffer.  Each element uses the same buffer
	VertexBuffer.Bind();

	// Bind the shader program.  Each element uses the same shader program
	ElementProgram.BindProgram();

	// Set the view projection matrix for the current viewport.
	ElementProgram.SetViewProjectionMatrix( ViewProjectionMatrix );

	// OpenGL state toggles
	glDisable(GL_DEPTH_TEST);
	glDisable(GL_CULL_FACE);
#if !PLATFORM_USES_ES2 && !PLATFORM_LINUX
	glEnable(GL_TEXTURE_2D);
#endif

	// Set up alpha testing
#if !PLATFORM_USES_ES2 && !PLATFORM_LINUX
	glEnable(GL_ALPHA_TEST);
	glAlphaFunc( GL_GREATER, 0.0f );
#endif
	
	// Set up blending
	glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
	glBlendEquation( GL_FUNC_ADD );

	// Setup stencil
	glStencilMask(0xFF);
	glStencilFunc(GL_GREATER, 0, 0xFF);
	glStencilOp(GL_KEEP, GL_INCR, GL_INCR);

	for( int32 BatchIndex = 0; BatchIndex < RenderBatches.Num(); ++BatchIndex )
	{
		const FSlateRenderBatch& RenderBatch = RenderBatches[BatchIndex];

		const FSlateShaderResource* Texture = RenderBatch.Texture;

		const ESlateBatchDrawFlag::Type DrawFlags = RenderBatch.DrawFlags;

		if( DrawFlags & ESlateBatchDrawFlag::NoBlending )
		{
			glDisable( GL_BLEND );
		}
		else
		{
			glEnable( GL_BLEND );
		}

#if !PLATFORM_USES_ES2
		if( DrawFlags & ESlateBatchDrawFlag::Wireframe )
		{
			glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
			glDisable(GL_BLEND);
		}
		else
		{
			glPolygonMode( GL_FRONT_AND_BACK, GL_FILL );
		}
#endif

		ElementProgram.SetShaderType( RenderBatch.ShaderType );
		ElementProgram.SetMarginUVs( RenderBatch.ShaderParams.PixelParams );
		ElementProgram.SetDrawEffects( RenderBatch.DrawEffects );

		// Disable stenciling and depth testing by default
		glDisable(GL_STENCIL_TEST);
		
		if( RenderBatch.ShaderType == ESlateShader::LineSegment )
		{
			// Test that the pixels in the line segment have only been drawn once
			glEnable(GL_STENCIL_TEST);
		}
		else if( Texture )
		{
			uint32 RepeatU = DrawFlags & ESlateBatchDrawFlag::TileU ? GL_REPEAT : GL_CLAMP_TO_EDGE;
			uint32 RepeatV = DrawFlags & ESlateBatchDrawFlag::TileV ? GL_REPEAT : GL_CLAMP_TO_EDGE;

#if PLATFORM_USES_ES2
			if(!FMath::IsPowerOfTwo(Texture->GetWidth()) || !FMath::IsPowerOfTwo(Texture->GetHeight()))
			{
				RepeatU = GL_CLAMP_TO_EDGE;
				RepeatV = GL_CLAMP_TO_EDGE;
			}
#endif

			ElementProgram.SetTexture( ((FSlateOpenGLTexture*)Texture)->GetTypedResource(), RepeatU, RepeatV );
		}
		else
		{
			ElementProgram.SetTexture( WhiteTexture->GetTypedResource(), GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE );
		}

		check( RenderBatch.NumIndices > 0 );

		const uint32 IndexCount = RenderBatch.NumIndices;

		uint32 Offset = 0;
		// The offset into the vertex buffer where this batches vertices are located
		uint32 BaseVertexIndex = RenderBatch.VertexOffset;
		// The starting index in the index buffer for this element batch
		uint32 StartIndex = RenderBatch.IndexOffset * sizeof(SlateIndex);


		// Size of each vertex
		const uint32 Stride = sizeof(FSlateVertex);

		// Set up offsets into the vertex buffer for each vertex
		glEnableVertexAttribArray(0);
		Offset = STRUCT_OFFSET( FSlateVertex, TexCoords );
		glVertexAttribPointer( 0, 4, GL_FLOAT, GL_FALSE, Stride, BUFFER_OFFSET(Stride*BaseVertexIndex+Offset) );

		glEnableVertexAttribArray(1);
		Offset = STRUCT_OFFSET( FSlateVertex, Position );
		glVertexAttribPointer( 1, 2, GL_SHORT, GL_FALSE, Stride, BUFFER_OFFSET(Stride*BaseVertexIndex+Offset) );

		bool bUseFloat16 =
#if SLATE_USE_FLOAT16
			true;
#else
			false;
#endif

		glEnableVertexAttribArray(2);
		Offset = STRUCT_OFFSET( FSlateVertex, ClipRect );
		glVertexAttribPointer( 2, 2, bUseFloat16 ? GL_HALF_FLOAT : GL_FLOAT, GL_FALSE, Stride, BUFFER_OFFSET(Stride*BaseVertexIndex+Offset) );

		glEnableVertexAttribArray(3);
		Offset = STRUCT_OFFSET( FSlateVertex, ClipRect ) + STRUCT_OFFSET( FSlateRotatedClipRectType, ExtentX );
		glVertexAttribPointer( 3, 4, bUseFloat16 ? GL_HALF_FLOAT : GL_FLOAT, GL_FALSE, Stride, BUFFER_OFFSET(Stride*BaseVertexIndex+Offset) );

		glEnableVertexAttribArray(4);
		Offset = STRUCT_OFFSET( FSlateVertex, Color );
		glVertexAttribPointer( 4, 4, GL_UNSIGNED_BYTE, GL_TRUE, Stride, BUFFER_OFFSET(Stride*BaseVertexIndex+Offset) );


		
		// Bind the index buffer so glDrawRangeElements knows which one to use
		IndexBuffer.Bind();


#if SLATE_USE_32BIT_INDICES
#define GL_INDEX_FORMAT GL_UNSIGNED_INT
#else
#define GL_INDEX_FORMAT GL_UNSIGNED_SHORT
#endif

#if PLATFORM_USES_ES2
		glDrawElements(GetOpenGLPrimitiveType(RenderBatch.DrawPrimitiveType), RenderBatch.NumIndices, GL_INDEX_FORMAT, (void*)StartIndex);
#else
		// Draw all elements in batch
		glDrawRangeElements( GetOpenGLPrimitiveType(RenderBatch.DrawPrimitiveType), 0, RenderBatch.NumVertices, RenderBatch.NumIndices, GL_INDEX_FORMAT, (void*)(PTRINT)StartIndex );
#endif
		CHECK_GL_ERRORS;
		
	}

	// Disable active textures and shaders
	glActiveTexture( GL_TEXTURE0 );
	glBindTexture( GL_TEXTURE_2D, 0 );
	glUseProgram(0);

}
예제 #8
0
void Splatterer::splat( GLuint                  count,
                        const BufferTexture*    positions,
                        const BufferTexture*    directions,
                        const BufferTexture*    speeds,
                        const BufferTexture*    ids,
                        const BufferTexture*    radii        )
{
    glBindBuffer(GL_ARRAY_BUFFER, pointBuffer);
    GL_ERROR;

    glVertexAttribPointer(splatAttribVertex, 4, GL_FLOAT, GL_FALSE, 0, NULL);
    GL_ERROR;

    glEnableVertexAttribArray(splatAttribVertex);
    GL_ERROR;

    glBlendFunc(GL_ONE, GL_ONE);
    glBlendEquation(GL_FUNC_ADD);
    glEnable(GL_BLEND);
    GL_ERROR;

    glActiveTexture(GL_TEXTURE0);
    GL_ERROR;
    positions->enable();

    glActiveTexture(GL_TEXTURE1);
    GL_ERROR;
    directions->enable();

    glActiveTexture(GL_TEXTURE2);
    GL_ERROR;
    speeds->enable();

    glActiveTexture(GL_TEXTURE3);
    GL_ERROR;
    ids->enable();

    glActiveTexture(GL_TEXTURE4);
    GL_ERROR;
    radii->enable();

    glActiveTexture(GL_TEXTURE5);
    GL_ERROR;
    agent->enable();

    // Draw discomfort brush

    discomfortProgram->enable();

    glDrawArraysInstanced(GL_POINTS, 0, 1, 1);
    GL_ERROR;

    // Draw agent splats

    splatProgram->enable();

    glDrawArraysInstanced(GL_POINTS, 0, 1, count);
    GL_ERROR;

    glDisable(GL_BLEND);
    GL_ERROR;

    glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
    GL_ERROR;

    glDisableVertexAttribArray(splatAttribVertex);
    GL_ERROR;

    glBindTexture(GL_TEXTURE_BUFFER, 0);
}
예제 #9
0
파일: main.cpp 프로젝트: naumov91/idsc
int main(int argc, char* argv[]) {

    printf("Creating OpenGL context...\n");
    sf::ContextSettings settings;
    settings.antialiasingLevel = 8;
    settings.majorVersion = 3;
    settings.minorVersion = 2;
    sf::RenderWindow window(sf::VideoMode(WINDOW_WIDTH, WINDOW_HEIGHT), "DSC Demo", sf::Style::Default, settings);

    printf("Initializing OpenGL...\n");
    glewExperimental = GL_TRUE;
    glewInit();

    printf("VENDOR = %s\n", glGetString(GL_VENDOR));
    printf("RENDERER = %s\n", glGetString(GL_RENDERER));
    printf("VERSION = %s\n", glGetString(GL_VERSION));

    GLuint vao;
    glGenVertexArrays(1, &vao);

    glDisable(GL_CULL_FACE);
    glDisable(GL_DEPTH_TEST);
    glEnable(GL_BLEND);
    glDepthFunc(GL_LESS);
    glBlendEquation(GL_FUNC_ADD);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    // Load/generate tet mesh based on command line argument:
    TetMesh * tet_mesh;
    printf("Generating tet mesh...\n");
    /*
     * 1: Sphere
     * 2: Debug tetmesh
     * 3: Big debug tetmesh
     * 4: Collapsed tetmesh
     * 5: Sphere, rotated
     * 6: C-mesh, joining together
     * 7: Sphere, stretched in the x-direction
     */
    std::string meshArg = "1";
    if (argc >= 2) { meshArg = argv[1]; }

    if (meshArg == "2") { // Debug tetmesh
        tet_mesh = TetMeshFactory::create_debug_tetmesh();
        printf("Evolving tet mesh ...\n");
        tet_mesh->evolve();
    } else if (meshArg == "3") { // Big debug tetmesh
        tet_mesh = TetMeshFactory::create_big_debug_tetmesh();
        printf("Evolving tet mesh ...\n");
        tet_mesh->evolve();
    } else if (meshArg == "4") { // Collapsed tetmesh
        tet_mesh = TetMeshFactory::create_collapsed_tetmesh();
        printf("Evolving tet mesh ...\n");
        tet_mesh->evolve();
    } else if (meshArg == "5") { // Rotated sphere tetmesh
        IndexedFaceSet * mesh = IndexedFaceSet::load_from_obj("assets/models/sphere.obj");
        tet_mesh = TetMeshFactory::from_indexed_face_set(*mesh);
        delete mesh;


        for (int deg = 1; deg <= 57; deg++) {
            REAL angle = PI / 180;
            for (unsigned int i = 0; i < tet_mesh->vertices.size() / 3; i++) {
                if (tet_mesh->get_vertex_status(i) == INTERFACE) {
                    glm::detail::tvec4<REAL, glm::precision::defaultp> v(tet_mesh->vertices[i*3], tet_mesh->vertices[i*3+1], tet_mesh->vertices[i*3+2], 1);
                    glm::detail::tvec4<REAL, glm::precision::defaultp> v2 = glm::rotateX(v, angle);
                    tet_mesh->vertex_targets[i*3] = v2[0];
                    tet_mesh->vertex_targets[i*3+1] = v2[1];
                    tet_mesh->vertex_targets[i*3+2] = v2[2];
                    tet_mesh->vertex_statuses[i] = MOVING;
                }
            }
            printf("Evolving tet mesh (%d deg)...\n", deg);
            tet_mesh->evolve();
        }
    } else if (meshArg == "6") { // C-mesh
        IndexedFaceSet * mesh = IndexedFaceSet::load_from_obj("assets/models/c_mesh.obj");
        tet_mesh = TetMeshFactory::from_indexed_face_set(*mesh);
        delete mesh;

        for (unsigned int i = 0; i < tet_mesh->vertices.size() / 3; i++) {
			if (tet_mesh->get_vertex_status(i) == INTERFACE) 
			{
		        glm::detail::tvec4<REAL, glm::precision::defaultp> v(tet_mesh->vertices[i*3], tet_mesh->vertices[i*3+1], tet_mesh->vertices[i*3+2], 1);
                if (tet_mesh->vertices[i*3] == 0.64f && tet_mesh->vertices[i*3+1] == 0.10f)
				{
					tet_mesh->vertex_targets[i*3] = tet_mesh->vertices[i*3];		// Stays the same
					tet_mesh->vertex_targets[i*3+1] = -0.10f;	// Moves to create C Mesh case
					tet_mesh->vertex_targets[i*3+2] = tet_mesh->vertices[i*3+2];	// Stays the same
				}
				else
				{
					tet_mesh->vertex_targets[i*3] = tet_mesh->vertices[i*3];
					tet_mesh->vertex_targets[i*3+1] = tet_mesh->vertices[i*3+1];
					tet_mesh->vertex_targets[i*3+2] = tet_mesh->vertices[i*3+2];
				}
				tet_mesh->vertex_statuses[i] = MOVING;
            }
		}
        printf("Evolving tet mesh from C mesh...\n");
        tet_mesh->evolve();
		
    }  else if (meshArg == "7") { // Stretched sphere
        IndexedFaceSet * mesh = IndexedFaceSet::load_from_obj("assets/models/sphere.obj");
        tet_mesh = TetMeshFactory::from_indexed_face_set(*mesh);
        for (unsigned int i = 0; i < tet_mesh->vertices.size() / 3; i++) {
            if (tet_mesh->get_vertex_status(i) == INTERFACE) {
                // scale x
                tet_mesh->vertex_targets[i * 3] = tet_mesh->vertices[i * 3] * 1.2;
                tet_mesh->vertex_targets[i * 3 + 1] = tet_mesh->vertices[i * 3 + 1];
                tet_mesh->vertex_targets[i * 3 + 2] = tet_mesh->vertices[i * 3 + 2];
                tet_mesh->vertex_statuses[i] = MOVING;
            }
        }
        printf("Evolving tet mesh ...\n");
        tet_mesh->evolve();
    } else { // Default case (tet mesh #1)
        IndexedFaceSet * mesh = IndexedFaceSet::load_from_obj("assets/models/sphere.obj");
        tet_mesh = TetMeshFactory::from_indexed_face_set(*mesh);
        printf("Evolving tet mesh ...\n");
        tet_mesh->evolve();
        delete mesh;
    }

    printf("Displaying tet mesh...\n");

    printf("Initializing display...\n");
    Shader * shader = Shader::compile_from("shaders/dsc.vsh", "shaders/dsc.gsh", "shaders/dsc.fsh");
    glUseProgram(shader->get_id());
    glBindVertexArray(vao);
    Renderable renderable(shader, true, false, GL_TRIANGLES);

    tgui::Gui gui(window);
    gui.setGlobalFont("assets/fonts/DejaVuSans.ttf");
    TetrahedralViewer viewer(&renderable, &gui);
    viewer.init(WINDOW_WIDTH, WINDOW_HEIGHT, FOV);
    viewer.bind_attributes(*tet_mesh, renderable);
    check_gl_error();
    delete tet_mesh;

    printf("Starting display...\n");
    sf::Event event;
    sf::Clock clock;
    tgui::Callback callback;
    while (window.isOpen()) {
        // float frame_length = clock.restart().asSeconds();

        glUseProgram(shader->get_id());
        glBindVertexArray(vao);
        while (gui.pollCallback(callback)) {
            viewer.handle_callback(callback);
        }

        viewer.update();
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        renderable.render();
        check_gl_error();

        glUseProgram(0);
        glBindVertexArray(0);
        gui.draw();
        window.display();

        while (window.pollEvent(event)) {
            if (event.type == sf::Event::Closed) {
                printf("Closing window...\n");
                window.close();
            }
            viewer.handle_event(event);
        }

        sf::sleep(sf::seconds(1.0f / FRAME_RATE));
    }

    printf("Cleaning up...\n");
    delete shader;

    return 0;
}
예제 #10
0
파일: blendMode.cpp 프로젝트: nystep/Scream
 void blendMode::set() {
     glEnable( GL_BLEND_ADVANCED_COHERENT_NV );
     glBlendEquation( bm );
 }
예제 #11
0
파일: renderer.c 프로젝트: palistov/cs371
void renderer_bind_light(struct renderer *r)
{
	GLuint prog;

	prog = r->light.prog;
	glDrawBuffer(GL_COLOR_ATTACHMENT0 + NUM_FRAMEBUFFER_ATTACHMENTS);
	glActiveTexture(GL_TEXTURE0);
	glBindTexture(GL_TEXTURE_2D, r->fb.fba[POSITION_ATTACHMENT]);
	glActiveTexture(GL_TEXTURE1);
	glBindTexture(GL_TEXTURE_2D, r->fb.fba[COLOR_ATTACHMENT]);
	glActiveTexture(GL_TEXTURE2);
	glBindTexture(GL_TEXTURE_2D, r->fb.fba[NORMAL_ATTACHMENT]);
	glActiveTexture(GL_TEXTURE3);
	glBindTexture(GL_TEXTURE_2D, r->fb.fba[TEXCOORD_ATTACHMENT]);
	glActiveTexture(GL_TEXTURE4);
	glBindTexture(GL_TEXTURE_2D, r->fb.fba[VELOCITY_ATTACHMENT]);
	glStencilFunc(GL_NOTEQUAL, 0, 0xFF);
	glDisable(GL_DEPTH_TEST);
	glEnable(GL_BLEND);
	glBlendEquation(GL_FUNC_ADD);
	glBlendFunc(GL_ONE, GL_ONE);
	glEnable(GL_CULL_FACE);
	glCullFace(GL_FRONT);

	glUseProgram(prog);
	glUniform1i(
		glGetUniformLocation(prog, "PositionMap"),
		0
	);
	glUniform1i(
		glGetUniformLocation(prog, "ColorMap"),
		1
	);
	glUniform1i(
		glGetUniformLocation(prog, "NormalMap"),
		2
	);
	glUniform1i(
		glGetUniformLocation(prog, "TexcoordMap"),
		3
	);
	glUniform1i(
		glGetUniformLocation(prog, "VelocityMap"),
		4
	);
	glUniformMatrix4fv(
		glGetUniformLocation(prog, "ModelViewProjectionMatrix"),
		1,
		GL_FALSE,
		r->mvp.a
	);
	glUniform2f(
		glGetUniformLocation(prog, "ScreenDimensions"),
		r->width,
		r->height
	);
	glUniform3fv(
		glGetUniformLocation(prog, "EyePosition"),
		1,
		&r->pos.x
	);
	
	glBindBuffer(GL_ARRAY_BUFFER, r->cube_attr);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, r->cube_idx);
	glEnableVertexAttribArray(0);
	glVertexAttribPointer(
		0,
		3,
		GL_FLOAT,
		GL_FALSE,
		sizeof(struct attribs),
		0
	);
}
예제 #12
0
// OpenGL3 Render function.
// (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop)
// Note that this implementation is little overcomplicated because we are saving/setting up/restoring every OpenGL state explicitly, in order to be able to run within any OpenGL engine that doesn't do so. 
void ImGui_ImplGlfwGL3_RenderDrawData(ImDrawData* draw_data)
{
    // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
    ImGuiIO& io = ImGui::GetIO();
    int fb_width = (int)(io.DisplaySize.x * io.DisplayFramebufferScale.x);
    int fb_height = (int)(io.DisplaySize.y * io.DisplayFramebufferScale.y);
    if (fb_width == 0 || fb_height == 0)
        return;
    draw_data->ScaleClipRects(io.DisplayFramebufferScale);

    // Backup GL state
    GLenum last_active_texture; glGetIntegerv(GL_ACTIVE_TEXTURE, (GLint*)&last_active_texture);
    glActiveTexture(GL_TEXTURE0);
    GLint last_program; glGetIntegerv(GL_CURRENT_PROGRAM, &last_program);
    GLint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
    GLint last_sampler; glGetIntegerv(GL_SAMPLER_BINDING, &last_sampler);
    GLint last_array_buffer; glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer);
    GLint last_element_array_buffer; glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &last_element_array_buffer);
    GLint last_vertex_array; glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array);
    GLint last_polygon_mode[2]; glGetIntegerv(GL_POLYGON_MODE, last_polygon_mode);
    GLint last_viewport[4]; glGetIntegerv(GL_VIEWPORT, last_viewport);
    GLint last_scissor_box[4]; glGetIntegerv(GL_SCISSOR_BOX, last_scissor_box);
    GLenum last_blend_src_rgb; glGetIntegerv(GL_BLEND_SRC_RGB, (GLint*)&last_blend_src_rgb);
    GLenum last_blend_dst_rgb; glGetIntegerv(GL_BLEND_DST_RGB, (GLint*)&last_blend_dst_rgb);
    GLenum last_blend_src_alpha; glGetIntegerv(GL_BLEND_SRC_ALPHA, (GLint*)&last_blend_src_alpha);
    GLenum last_blend_dst_alpha; glGetIntegerv(GL_BLEND_DST_ALPHA, (GLint*)&last_blend_dst_alpha);
    GLenum last_blend_equation_rgb; glGetIntegerv(GL_BLEND_EQUATION_RGB, (GLint*)&last_blend_equation_rgb);
    GLenum last_blend_equation_alpha; glGetIntegerv(GL_BLEND_EQUATION_ALPHA, (GLint*)&last_blend_equation_alpha);
    GLboolean last_enable_blend = glIsEnabled(GL_BLEND);
    GLboolean last_enable_cull_face = glIsEnabled(GL_CULL_FACE);
    GLboolean last_enable_depth_test = glIsEnabled(GL_DEPTH_TEST);
    GLboolean last_enable_scissor_test = glIsEnabled(GL_SCISSOR_TEST);

    // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, polygon fill
    glEnable(GL_BLEND);
    glBlendEquation(GL_FUNC_ADD);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glDisable(GL_CULL_FACE);
    glDisable(GL_DEPTH_TEST);
    glEnable(GL_SCISSOR_TEST);
    glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);

    // Setup viewport, orthographic projection matrix
    glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height);
    const float ortho_projection[4][4] =
    {
        { 2.0f/io.DisplaySize.x, 0.0f,                   0.0f, 0.0f },
        { 0.0f,                  2.0f/-io.DisplaySize.y, 0.0f, 0.0f },
        { 0.0f,                  0.0f,                  -1.0f, 0.0f },
        {-1.0f,                  1.0f,                   0.0f, 1.0f },
    };
    glUseProgram(g_ShaderHandle);
    glUniform1i(g_AttribLocationTex, 0);
    glUniformMatrix4fv(g_AttribLocationProjMtx, 1, GL_FALSE, &ortho_projection[0][0]);
    glBindSampler(0, 0); // Rely on combined texture/sampler state.

    // Recreate the VAO every time 
    // (This is to easily allow multiple GL contexts. VAO are not shared among GL contexts, and we don't track creation/deletion of windows so we don't have an obvious key to use to cache them.)
    GLuint vao_handle = 0;
    glGenVertexArrays(1, &vao_handle);
    glBindVertexArray(vao_handle);
    glBindBuffer(GL_ARRAY_BUFFER, g_VboHandle);
    glEnableVertexAttribArray(g_AttribLocationPosition);
    glEnableVertexAttribArray(g_AttribLocationUV);
    glEnableVertexAttribArray(g_AttribLocationColor);
    glVertexAttribPointer(g_AttribLocationPosition, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)IM_OFFSETOF(ImDrawVert, pos));
    glVertexAttribPointer(g_AttribLocationUV, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)IM_OFFSETOF(ImDrawVert, uv));
    glVertexAttribPointer(g_AttribLocationColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid*)IM_OFFSETOF(ImDrawVert, col));

    // Draw
    for (int n = 0; n < draw_data->CmdListsCount; n++)
    {
        const ImDrawList* cmd_list = draw_data->CmdLists[n];
        const ImDrawIdx* idx_buffer_offset = 0;

        glBindBuffer(GL_ARRAY_BUFFER, g_VboHandle);
        glBufferData(GL_ARRAY_BUFFER, (GLsizeiptr)cmd_list->VtxBuffer.Size * sizeof(ImDrawVert), (const GLvoid*)cmd_list->VtxBuffer.Data, GL_STREAM_DRAW);

        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_ElementsHandle);
        glBufferData(GL_ELEMENT_ARRAY_BUFFER, (GLsizeiptr)cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx), (const GLvoid*)cmd_list->IdxBuffer.Data, GL_STREAM_DRAW);

        for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
        {
            const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
            if (pcmd->UserCallback)
            {
                pcmd->UserCallback(cmd_list, pcmd);
            }
            else
            {
                glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->TextureId);
                glScissor((int)pcmd->ClipRect.x, (int)(fb_height - pcmd->ClipRect.w), (int)(pcmd->ClipRect.z - pcmd->ClipRect.x), (int)(pcmd->ClipRect.w - pcmd->ClipRect.y));
                glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer_offset);
            }
            idx_buffer_offset += pcmd->ElemCount;
        }
    }
    glDeleteVertexArrays(1, &vao_handle);

    // Restore modified GL state
    glUseProgram(last_program);
    glBindTexture(GL_TEXTURE_2D, last_texture);
    glBindSampler(0, last_sampler);
    glActiveTexture(last_active_texture);
    glBindVertexArray(last_vertex_array);
    glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, last_element_array_buffer);
    glBlendEquationSeparate(last_blend_equation_rgb, last_blend_equation_alpha);
    glBlendFuncSeparate(last_blend_src_rgb, last_blend_dst_rgb, last_blend_src_alpha, last_blend_dst_alpha);
    if (last_enable_blend) glEnable(GL_BLEND); else glDisable(GL_BLEND);
    if (last_enable_cull_face) glEnable(GL_CULL_FACE); else glDisable(GL_CULL_FACE);
    if (last_enable_depth_test) glEnable(GL_DEPTH_TEST); else glDisable(GL_DEPTH_TEST);
    if (last_enable_scissor_test) glEnable(GL_SCISSOR_TEST); else glDisable(GL_SCISSOR_TEST);
    glPolygonMode(GL_FRONT_AND_BACK, (GLenum)last_polygon_mode[0]);
    glViewport(last_viewport[0], last_viewport[1], (GLsizei)last_viewport[2], (GLsizei)last_viewport[3]);
    glScissor(last_scissor_box[0], last_scissor_box[1], (GLsizei)last_scissor_box[2], (GLsizei)last_scissor_box[3]);
}
예제 #13
0
void Particles::update(int w, int h){
    
    if(w!=lastw||h!=lasth){
        initFbo(w, h);
    }
    
    
    
    glBlendEquation(GL_ADD);
    glBlendFunc(GL_ONE, GL_ZERO);
    
    for(int i = 0 ; i < forces.size();i++){
        if(forces[i]->isActive&&forces[i]->name.find("net")!=string::npos){

            velPingPong.dst->begin();
            forces[i]->shader.begin();
            forces[i]->shader.setUniformTexture("posData",posPingPong.src->getTextureReference(), 1);
            forces[i]->shader.setUniform3f("screen",w,h,dad->zdepth);
            forces[i]->shader.setUniform1i("resolution",textureRes);
            forces[i]->updateShader();
            
            velPingPong.src->draw(0,0);
            
            forces[i]->shader.end();
            
            velPingPong.dst->end();
            velPingPong.swap();
                
                
                
//            }
        }
        else if(forces[i]->isActive ){
            int j = 0;
            vector<ofPoint> curattr = dad->attr->getType(forces[i]->attrFamilly,1,1,forces[i]->attrZone);
            if(map2blob){
//                drawBlob * vvv = (drawBlob *)dad->get("drawBlob");
//                for(int i = 0 ; i< curattr.size();i++){
//                    if(vvv->invertx)curattr[i].x = 1-curattr[i].x;
//                    if(vvv->inverty)curattr[i].y = 1-curattr[i].y;

//                    
//                }
//            dad->sH.mapN2S(curattr,vvv->screenN);
                
                
            }
            if((forces[i]->attrFamilly>-2?curattr.size()>0:1)){
                do{
                    velPingPong.dst->begin();
                    forces[i]->shader.begin();
                    forces[i]->shader.setUniformTexture("posData",posPingPong.src->getTextureReference(), 1);
                    if(forces[i]->name=="origin") 
                        forces[i]->shader.setUniformTexture("originData",origins.getTextureReference(), 2);
                    if(forces[i]->name=="fieldForce"){
                        forces[i]->shader.setUniform2f("inres",dad->inw,dad->inh);
            #ifdef syphon
                        forces[i]->shader.setUniformTexture("fieldData",dad->pipePP.src->getTextureReference(), 2);
            #endif
                            }
                    if(forces[i]->attrFamilly>=0&&curattr.size()>0&&j<curattr.size()){
                        
                        forces[i]->shader.setUniform3f("attr",curattr[j].x,curattr[j].y,curattr[j].z+0.5);
                    }
                    forces[i]->shader.setUniform3f("screen",w,h,dad->zdepth);
                    if(origintype==1)forces[i]->shader.setUniform1i("resolution",textureRes3);
                    else forces[i]->shader.setUniform1i("resolution",textureRes);
                    forces[i]->updateShader();
                    
                    velPingPong.src->draw(0,0);
                    
                    forces[i]->shader.end();
                    
                    velPingPong.dst->end();
                    velPingPong.swap();
                            j++;
                }while( forces[i]->attrFamilly>=0&&j<curattr.size());
            }
        }
//        glEnd();
    }
    
    
    
    
    
    posPingPong.dst->begin();
    updatePos.begin();  // Previus position
    updatePos.setUniformTexture("velData", velPingPong.src->getTextureReference(), 1);      // Velocity
    updatePos.setUniform1f("timestep",timeStep*1.0/FPS );
    updatePos.setUniform1i("resolution",textureRes);
    
    posPingPong.src->draw(0,0);
    
    
    
    updatePos.end();
    posPingPong.dst->end();
    
    
    posPingPong.swap();
    
    lastw = w;
    lasth = h;
    
}
예제 #14
0
// ----------------------------------------------------------------------------
SPShaderManager::SPShaderManager()
{
#ifndef SERVER_ONLY
    m_official_sampler_types =
    {
        { "nearest", ST_NEAREST },
        { "nearest_clamped", ST_NEAREST_CLAMPED },
        { "bilinear", ST_BILINEAR },
        { "bilinear_clamped", ST_BILINEAR_CLAMPED },
        { "trilinear", ST_TRILINEAR },
        { "trilinear_clamped", ST_TRILINEAR_CLAMPED },
        { "semi_trilinear", ST_SEMI_TRILINEAR }
    };

    m_official_uniform_assigner_functions =
    {
        { "shadowCascadeUniformAssigner", [](SPUniformAssigner* ua)
            {
                ua->setValue(sp_cur_shadow_cascade);
            }
        },
        { "windDirectionUniformAssigner", [](SPUniformAssigner* ua)
            {
                ua->setValue(sp_wind_dir);
            }
        },
        { "isDuringDayUniformAssigner", [](SPUniformAssigner* ua)
            {
                int is_during_day = Track::getCurrentTrack() ?
                Track::getCurrentTrack()->getIsDuringDay() ? 1 : 0 : 0;
                ua->setValue(is_during_day);
            }
        },
        { "zeroAlphaUniformAssigner", [](SPUniformAssigner* ua)
            {
                ua->setValue(0.0f);
            }
        },
        { "fogUniformAssigner", [](SPUniformAssigner* ua)
            {
                int fog_enable = Track::getCurrentTrack() ?
                    Track::getCurrentTrack()->isFogEnabled() ? 1 : 0 : 0;
                ua->setValue(fog_enable);
            }
        },
        { "ghostAlphaUniformAssigner", [](SPUniformAssigner* ua)
            {
                float alpha = 1.0f;
                if (Track::getCurrentTrack())
                {
                    const video::SColor& c = Track::getCurrentTrack()
                        ->getSunColor();
                    float y = 0.2126f * c.getRed() + 0.7152f * c.getGreen() +
                        0.0722f * c.getBlue();
                    alpha = y > 128.0f ? 0.5f : 0.35f;
                }
                ua->setValue(alpha);
           }
       }
    };

    m_official_use_functions =
    {
        { "alphaBlendUse", []()
            {
                glEnable(GL_DEPTH_TEST);
                glDepthMask(GL_FALSE);
                glDisable(GL_CULL_FACE);
                glEnable(GL_BLEND);
                glBlendEquation(GL_FUNC_ADD);
                glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
            }
        },
        { "additiveUse", []()
            {
                glEnable(GL_DEPTH_TEST);
                glDepthMask(GL_FALSE);
                glDisable(GL_CULL_FACE);
                glEnable(GL_BLEND);
                glBlendEquation(GL_FUNC_ADD);
                glBlendFunc(GL_ONE, GL_ONE);
            }
        },
        { "ghostUse", []()
            {
                glEnable(GL_DEPTH_TEST);
                glDepthMask(GL_TRUE);
                glEnable(GL_CULL_FACE);
                glEnable(GL_BLEND);
                glBlendEquation(GL_FUNC_ADD);
                glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
            }
        }
    };
#endif
}   // SPShaderManager
void GLWidget::initializeGL()
{
#ifndef __APPLE__
    glewExperimental = GL_TRUE;
    GLenum err = glewInit();
    if (GLEW_OK != err)
        qDebug() << glewGetErrorString(err);
#endif

    glClearColor(0.0, 0.0, 0.0, 0.0);
    glEnable(GL_BLEND);
    glBlendEquation(GL_FUNC_ADD);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glEnable(GL_CULL_FACE);
    glCullFace(GL_FRONT);
    glDisable(GL_DEPTH_TEST);
    glColorMask(true, true, true, true);
    glDepthMask(true);

    // initialize transformation
    rotation = Mat3f::identity();
    translation = Vec3f(0.0f, 0.0f, -2.0f);

    // load sample data volume
    //volumeDim.x = 256;
    //volumeDim.y = 256;
    //volumeDim.z = 178;
    int volumeSize = volumeDim.x * volumeDim.y * volumeDim.z;
    std::vector<unsigned char> volumeData;
//    std::vector<float> volumeData;
    volumeData.resize(volumeSize);
    std::ifstream ifs(datasetName.toStdString(), std::ios::binary);
    if(!ifs.is_open())
    {
        qDebug() << "Failed to open sample volume!";
        close();
    }

    ifs.read(reinterpret_cast<char *>(&volumeData.front()), volumeSize * sizeof(unsigned char));
    ifs.close();

    // prepare transfer function data
    tfdata.clear();
    for(int i = 0; i< 512; i++)
    {
        if(i < 64)
            tfdata.push_back(Vec4f(1.0f, 0.0f, 0.0f, 0.0f));
        else if(i<128)
            tfdata.push_back(Vec4f(1.0f, 1.0f, 0.0f, 0.001f*i));
        else if(i<196)
            tfdata.push_back(Vec4f(0.0f, 1.0f, 0.0f, 0.001f*i));
        else if(i<312)
            tfdata.push_back(Vec4f(0.2f, 1.0f, 1.0f, 0.0001f*i));
        else if(i<400)
            tfdata.push_back(Vec4f(0.1f, 0.3f, 1.0f, 0.0001f*i));
        else
            tfdata.push_back(Vec4f(1.0f, 0.0f, 1.0f, 0.0002f*i));
    }

    std::vector<unsigned char> volumeDataTest;
    volumeDataTest.resize(volumeSize);
    for(int i = 0; i < 5; i++)
        for(int j = 0; j < 5; j++)
            for(int k = 0; k < 5; k++)
    {
        if( i==2 && j ==2 && k==2)
            volumeDataTest[i+5*j+k*25] = 255;
        else
            volumeDataTest[i+5*j+k*25] = 0;

    }
    // create OpenGL textures
    volumeTex = GLTexture::create();
    volumeTex->updateTexImage3D(GL_R8, volumeDim, GL_RED, GL_UNSIGNED_BYTE, &volumeData.front());
    // create OpenGL textures for tricubic interpolation

//    volumeTexTriCubic = GLTexture::create();
//    volumeTexTriCubic->updateTexImage3DNoInterpolation(GL_R8, volumeDim, GL_RED, GL_UNSIGNED_BYTE, &volumeData.front());

    transferFuncTex = GLTexture::create();
    transferFuncTex->updateTexImage2D(GL_RGBA32F, Vec2i(int(tfdata.size()), 1), GL_RGBA, GL_FLOAT, &tfdata.front());

    // create full screen rectangle for volume ray-casting
    std::vector<Vec2f> rectVertices;
    rectVertices.push_back(Vec2f(0.0f, 0.0f));
    rectVertices.push_back(Vec2f(0.0f, 1.0f));
    rectVertices.push_back(Vec2f(1.0f, 1.0f));
    rectVertices.push_back(Vec2f(1.0f, 0.0f));
    rectVertexBuffer = GLArrayBuffer::create(GL_ARRAY_BUFFER);
    rectVertexBuffer->update(rectVertices.size() * sizeof(Vec2f), &rectVertices.front(), GL_STATIC_DRAW);
    rectVertexArray = GLVertexArray::create();

    // create OpenGL shaders
    volumeRayCastingProgram = GLShaderProgram::create("VolumeRayCasting.vert", "VolumeRayCasting.frag");
    if(volumeRayCastingProgram == NULL)
        close();

    // assign vertex buffer to the shader attribute input called "Vertex"
    volumeRayCastingProgram->setVertexAttribute("Vertex", rectVertexArray, rectVertexBuffer, 2, GL_FLOAT, false);

    //Pre-integration
    preIntTex = GLTexture::create();
    preIntTex->updateTexImage2D(GL_RGBA32F, Vec2i(int(tfdata.size()), int(tfdata.size())), GL_RGBA, GL_FLOAT, &tfdata.front());

    preIntFBO = GLFramebuffer::create();
    preIntFBO->bind();
    colAtt = GL_COLOR_ATTACHMENT0;
    glDrawBuffers(1, &colAtt);
    preIntFBO->attachTexture(colAtt,preIntTex);
    preIntFBO->release();

    std::vector<Vec2f> rectVerticesPreint;
    rectVerticesPreint.push_back(Vec2f(-1.0f, -1.0f));
    rectVerticesPreint.push_back(Vec2f(-1.0f, 1.0f));
    rectVerticesPreint.push_back(Vec2f(1.0f, 1.0f));
    rectVerticesPreint.push_back(Vec2f(1.0f, -1.0f));
    preIntArrayBuffer = GLArrayBuffer::create(GL_ARRAY_BUFFER);
    preIntArrayBuffer->update(rectVerticesPreint.size() * sizeof(Vec2f), &rectVerticesPreint.front(), GL_STATIC_DRAW);
    preIntVertexArray = GLVertexArray::create();

    //initial shader
    preIntProgram = GLShaderProgram::create("PreIntegration.vert", "PreIntegration.frag");
    if(preIntProgram == NULL)
        close();
    preIntProgram->setVertexAttribute("V", preIntVertexArray, preIntArrayBuffer, 2, GL_FLOAT, false);

    //draw the pre-integration texture
    int w = width();
    int h = height();
    glViewport(0,0,tfdata.size(),tfdata.size());
    preIntFBO->bind();
//    glClearColor(0.0,0.0,0.0,0.0);
    glDisable(GL_BLEND);
    glClear(GL_DEPTH_BUFFER_BIT|GL_COLOR_BUFFER_BIT);
    preIntProgram->setTexture("TF", transferFuncTex);
    preIntProgram->setUniform("deltastep",deltaStep);
    preIntProgram->setUniform("OCSize", opacityCorrection);
    preIntProgram->begin();
    preIntVertexArray->drawArrays(GL_TRIANGLE_FAN, 4);
    preIntProgram->end();
    preIntFBO->release();
    glEnable(GL_BLEND);
    glViewport(0,0,w ,h);
//    glClearColor(1.0,1.0,1.0,1.0);

    //bounding box shader
    boundBoxProgram = GLShaderProgram::create("BoundingBox.vert", "BoundingBox.frag");
    if(boundBoxProgram == NULL)
        close();

    //local Ambient Occulusion
    //initialize
    LAOTex = GLTexture::create();
    LAOTex->updateTexImage3D(GL_RGBA32F, volumeDim, GL_RGBA, GL_FLOAT,NULL);

    LAOFrameBuffer = GLFramebuffer::create();
    LAOProgram = GLShaderProgram::create("LAO.vert", "LAO.frag");
    if(LAOProgram == NULL)
        close();
    drawLAOTexture();

    //Cubic interpolation precomputation
//    volumeTexCubic = GLTexture::create();
//    volumeTexCubic->updateTexImage3DNoInterpolation(GL_RGBA32F, volumeDim*3, GL_RGBA, GL_FLOAT,NULL);
//    TexCubicFrameBuffer = GLFramebuffer::create();
//    TexCubicProgram = GLShaderProgram::create("TriCubicCof.vert", "TriCubicCof.frag");
//    if(TexCubicProgram == NULL)
//        close();
//    drawCubicTexture();
}
예제 #16
0
void EngineGLFW::glRendererDrawLists(ImDrawData * draw_data)
{
    GLint last_blend_src;
    GLint last_blend_dst;
    GLint last_blend_equation_rgb;
    GLint last_blend_equation_alpha;
    
    glGetIntegerv(GL_BLEND_SRC, &last_blend_src);
    glGetIntegerv(GL_BLEND_DST, &last_blend_dst);
    glGetIntegerv(GL_BLEND_EQUATION_RGB,   &last_blend_equation_rgb);
    glGetIntegerv(GL_BLEND_EQUATION_ALPHA, &last_blend_equation_alpha);
    
    GLboolean last_enable_blend        = glIsEnabled(GL_BLEND);
    GLboolean last_enable_cull_face    = glIsEnabled(GL_CULL_FACE);
    GLboolean last_enable_depth_test   = glIsEnabled(GL_DEPTH_TEST);
    GLboolean last_enable_scissor_test = glIsEnabled(GL_SCISSOR_TEST);
    
    glEnable(GL_BLEND);
    glBlendEquation(GL_FUNC_ADD);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    
    glDisable(GL_CULL_FACE);
    glDisable(GL_DEPTH_TEST);
    glEnable(GL_SCISSOR_TEST);
    
    glEnableClientState(GL_VERTEX_ARRAY);
    glEnableClientState(GL_TEXTURE_COORD_ARRAY);
    glEnableClientState(GL_COLOR_ARRAY);
    
    ImGuiIO * io = &ImGui::GetIO();
    float fb_height = io->DisplaySize.y * io->DisplayFramebufferScale.y;
    draw_data->ScaleClipRects(io->DisplayFramebufferScale);
    
    glMatrixMode(GL_PROJECTION);
    glPushMatrix();
    glLoadIdentity();
    glOrtho(0.0f, io->DisplaySize.x, io->DisplaySize.y, 0.0f, -1.0f, +1.0f);
    glMatrixMode(GL_MODELVIEW);
    glPushMatrix();
    glLoadIdentity();
    
    for(int n = 0; n < draw_data->CmdListsCount; n++)
    {
        const ImDrawList * cmd_list = draw_data->CmdLists[n];
        const unsigned char * vtx_buffer = (const unsigned char *)&cmd_list->VtxBuffer.front();
        const ImDrawIdx * idx_buffer = &cmd_list->IdxBuffer.front();
        
        glVertexPointer(2, GL_FLOAT, sizeof(ImDrawVert), (void *)(vtx_buffer + OFFSETOF(ImDrawVert, pos)));
        glTexCoordPointer(2, GL_FLOAT, sizeof(ImDrawVert), (void *)(vtx_buffer + OFFSETOF(ImDrawVert, uv)));
        glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(ImDrawVert), (void *)(vtx_buffer + OFFSETOF(ImDrawVert, col)));
        
        for(int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.size(); cmd_i++)
        {
            const ImDrawCmd * pcmd = &cmd_list->CmdBuffer[cmd_i];
            if(pcmd->UserCallback)
            {
                pcmd->UserCallback(cmd_list, pcmd);
            } else {
                ofTexture tex;
                tex.texData.textureTarget = GL_TEXTURE_2D;
                tex.setUseExternalTextureID((intptr_t)pcmd->TextureId);
                tex.bind();
                glScissor(
                          (int)pcmd->ClipRect.x,
                          (int)(fb_height - pcmd->ClipRect.w),
                          (int)(pcmd->ClipRect.z - pcmd->ClipRect.x),
                          (int)(pcmd->ClipRect.w - pcmd->ClipRect.y)
                          );
                glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, GL_UNSIGNED_INT, idx_buffer);
                tex.unbind();
            }
            idx_buffer += pcmd->ElemCount;
        }
    }
    
    glDisableClientState(GL_COLOR_ARRAY);
    glDisableClientState(GL_TEXTURE_COORD_ARRAY);
    glDisableClientState(GL_VERTEX_ARRAY);
    
    glBlendEquationSeparate(last_blend_equation_rgb, last_blend_equation_alpha);
    glBlendFunc(last_blend_src, last_blend_dst);
    
    last_enable_blend        ? glEnable(GL_BLEND)        : glDisable(GL_BLEND);
    last_enable_cull_face    ? glEnable(GL_CULL_FACE)    : glDisable(GL_CULL_FACE);
    last_enable_depth_test   ? glEnable(GL_DEPTH_TEST)   : glDisable(GL_DEPTH_TEST);
    last_enable_scissor_test ? glEnable(GL_SCISSOR_TEST) : glDisable(GL_SCISSOR_TEST);
    
    glMatrixMode(GL_MODELVIEW);
    glPopMatrix();
    glMatrixMode(GL_PROJECTION);
    glPopMatrix();
    glPopAttrib();
}
예제 #17
0
void FGLRenderBuffers::RenderEffect(const FString &name)
{
	if (hw_postprocess.Effects[name].Size() == 0)
		return;

	FGLDebug::PushGroup(name.GetChars());

	FGLPostProcessState savedState;

	for (const PPStep &step : hw_postprocess.Effects[name])
	{
		// Bind input textures
		for (unsigned int index = 0; index < step.Textures.Size(); index++)
		{
			savedState.SaveTextureBindings(index + 1);

			const PPTextureInput &input = step.Textures[index];
			int filter = (input.Filter == PPFilterMode::Nearest) ? GL_NEAREST : GL_LINEAR;
			int wrap = (input.Wrap == PPWrapMode::Clamp) ? GL_CLAMP : GL_REPEAT;

			switch (input.Type)
			{
			default:
			case PPTextureType::CurrentPipelineTexture:
				BindCurrentTexture(index, filter, wrap);
				break;

			case PPTextureType::NextPipelineTexture:
				I_FatalError("PPTextureType::NextPipelineTexture not allowed as input\n");
				break;

			case PPTextureType::PPTexture:
				GLTextures[input.Texture].Bind(index, filter, wrap);
				break;

			case PPTextureType::SceneColor:
				BindSceneColorTexture(index);
				break;

			case PPTextureType::SceneFog:
				BindSceneFogTexture(index);
				break;

			case PPTextureType::SceneNormal:
				BindSceneNormalTexture(index);
				break;

			case PPTextureType::SceneDepth:
				BindSceneDepthTexture(index);
				break;
			}
		}

		// Set render target
		switch (step.Output.Type)
		{
		default:
			I_FatalError("Unsupported postprocess output type\n");
			break;

		case PPTextureType::CurrentPipelineTexture:
			BindCurrentFB();
			break;

		case PPTextureType::NextPipelineTexture:
			BindNextFB();
			break;

		case PPTextureType::PPTexture:
			if (GLTextureFBs[step.Output.Texture])
				GLTextureFBs[step.Output.Texture].Bind();
			else
				GLTextureFBs[step.Output.Texture] = CreateFrameBuffer(step.Output.Texture.GetChars(), GLTextures[step.Output.Texture]);
			break;

		case PPTextureType::SceneColor:
			BindSceneFB(false);
			break;
		}

		// Set blend mode
		if (step.BlendMode.BlendOp == STYLEOP_Add && step.BlendMode.SrcAlpha == STYLEALPHA_One && step.BlendMode.DestAlpha == STYLEALPHA_Zero && step.BlendMode.Flags == 0)
		{
			glDisable(GL_BLEND);
		}
		else
		{
			// To do: support all the modes
			glEnable(GL_BLEND);
			glBlendEquation(GL_FUNC_ADD);
			if (step.BlendMode.SrcAlpha == STYLEALPHA_One && step.BlendMode.DestAlpha == STYLEALPHA_One)
				glBlendFunc(GL_ONE, GL_ONE);
			else
				glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
		}

		// Setup viewport
		glViewport(step.Viewport.left, step.Viewport.top, step.Viewport.width, step.Viewport.height);

		auto &shader = GLShaders[step.ShaderName];

		// Set uniforms
		if (step.Uniforms.Data.Size() > 0)
		{
			if (!shader->Uniforms)
				shader->Uniforms.reset(screen->CreateDataBuffer(POSTPROCESS_BINDINGPOINT, false));
			shader->Uniforms->SetData(step.Uniforms.Data.Size(), step.Uniforms.Data.Data());
			shader->Uniforms->BindBase();
		}

		// Set shader
		shader->Bind(NOQUEUE);

		// Draw the screen quad
		GLRenderer->RenderScreenQuad();

		// Advance to next PP texture if our output was sent there
		if (step.Output.Type == PPTextureType::NextPipelineTexture)
			NextTexture();
	}

	glViewport(screen->mScreenViewport.left, screen->mScreenViewport.top, screen->mScreenViewport.width, screen->mScreenViewport.height);

	FGLDebug::PopGroup();
}
예제 #18
0
static void
generate_and_display_drawbuffers(int count)
{
	GLuint tex[16], fb, fs, vs, prog;
	GLenum attachments[16], status;
	int i;
	char fs_output_line[256];
	char fs_full_source[1024];

	glGenFramebuffersEXT(1, &fb);
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fb);

	for (i = 0; i < count; i++) {
		tex[i] = attach_texture(i);
		attachments[i] = GL_COLOR_ATTACHMENT0 + i;
	}

	status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
	if (status != GL_FRAMEBUFFER_COMPLETE_EXT) {
		fprintf(stderr, "fbo incomplete (status = 0x%04x)\n", status);
		piglit_report_result(PIGLIT_SKIP);
	}

	glDrawBuffersARB(count, attachments);

	/* Clear all to 0.25 so we see if the shader rendering happens. */
	glClearColor(clear_value, clear_value, clear_value, clear_value);
	glClear(GL_COLOR_BUFFER_BIT);

	/* Build the shader that spams green to all outputs. */
	vs = piglit_compile_shader_text(GL_VERTEX_SHADER, vs_source);

	strcpy(fs_full_source, fs_source_start);
		
	for (i = 0; i < count; i++) {
		sprintf(fs_output_line, fs_source_output, i, output_values[i * 4], 
				output_values[(i * 4) + 1], output_values[(i * 4) + 2], 
				output_values[(i * 4) + 3]);
		
		strcat(fs_full_source, fs_output_line);
	}
	
	strcat(fs_full_source, fs_source_end);

	assert(strlen(fs_full_source) + 1 < sizeof(fs_full_source) / sizeof(fs_full_source[0]));
	
	fs = piglit_compile_shader_text(GL_FRAGMENT_SHADER, fs_full_source);

	prog = piglit_link_simple_program(vs, fs);
	glUseProgram(prog);

	glEnable(GL_BLEND);
	glBlendFunc(GL_ONE, GL_ONE);
	glBlendEquation(GL_FUNC_ADD);

	/* Now render to all the color buffers. */
	piglit_draw_rect(-1, -1, 2, 2);

	glDisable(GL_BLEND);
	
	/* OK, now draw each of these textures to the winsys framebuffer. */
	glUseProgram(0);
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
	piglit_ortho_projection(piglit_width, piglit_height, GL_FALSE);
	glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
	glEnable(GL_TEXTURE_2D);
	for (i = 0; i < count; i++) {
		glBindTexture(GL_TEXTURE_2D, tex[i]);
		piglit_draw_rect_tex(16 * i, 16 * (count - 1),
					 16, 16,
					 0, 0,
					 1, 1);
	}
	glDisable(GL_TEXTURE_2D);

	for (i = 0; i < count; i++) {
		glDeleteTextures(1, &tex[i]);
	}
	glDeleteFramebuffersEXT(1, &fb);
}
예제 #19
0
파일: HUD.cpp 프로젝트: havess/Asuna
static void RenderDrawLists(ImDrawData* draw_data)
{
  // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
  ImGuiIO& io = ImGui::GetIO();
  int fb_width = (int)(io.DisplaySize.x * io.DisplayFramebufferScale.x);
  int fb_height = (int)(io.DisplaySize.y * io.DisplayFramebufferScale.y);
  if (fb_width == 0 || fb_height == 0)
    return;
  draw_data->ScaleClipRects(io.DisplayFramebufferScale);

  // Backup GL state
  GLint last_program; glGetIntegerv(GL_CURRENT_PROGRAM, &last_program);
  GLint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
  GLint last_active_texture; glGetIntegerv(GL_ACTIVE_TEXTURE, &last_active_texture);
  GLint last_array_buffer; glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer);
  GLint last_element_array_buffer; glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &last_element_array_buffer);
  GLint last_vertex_array; glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array);
  GLint last_blend_src; glGetIntegerv(GL_BLEND_SRC, &last_blend_src);
  GLint last_blend_dst; glGetIntegerv(GL_BLEND_DST, &last_blend_dst);
  GLint last_blend_equation_rgb; glGetIntegerv(GL_BLEND_EQUATION_RGB, &last_blend_equation_rgb);
  GLint last_blend_equation_alpha; glGetIntegerv(GL_BLEND_EQUATION_ALPHA, &last_blend_equation_alpha);
  GLint last_viewport[4]; glGetIntegerv(GL_VIEWPORT, last_viewport);
  GLboolean last_enable_blend = glIsEnabled(GL_BLEND);
  GLboolean last_enable_cull_face = glIsEnabled(GL_CULL_FACE);
  GLboolean last_enable_depth_test = glIsEnabled(GL_DEPTH_TEST);
  GLboolean last_enable_scissor_test = glIsEnabled(GL_SCISSOR_TEST);
  CheckOpenGLError("State backup", 57);

  // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
  glEnable(GL_BLEND);
  glBlendEquation(GL_FUNC_ADD);
  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  glDisable(GL_CULL_FACE);
  glDisable(GL_DEPTH_TEST);
  glEnable(GL_SCISSOR_TEST);
  glActiveTexture(GL_TEXTURE0);
  CheckOpenGLError("State setup", 75);

  // Setup orthographic projection matrix
  glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height);
  CheckOpenGLError("Viewport", 84);
  const float ortho_projection[4][4] =
  {
      { 2.0f/io.DisplaySize.x, 0.0f,                   0.0f, 0.0f },
      { 0.0f,                  2.0f/-io.DisplaySize.y, 0.0f, 0.0f },
      { 0.0f,                  0.0f,                  -1.0f, 0.0f },
      {-1.0f,                  1.0f,                   0.0f, 1.0f },
  };
  glUseProgram(g_shaderHandle);
  CheckOpenGLError("Program", 85);
  glUniform1i(g_attribLocationTex, 0);
  glUniformMatrix4fv(g_attribLocationProjMtx, 1, GL_FALSE, &ortho_projection[0][0]);
    CheckOpenGLError("Program + uniforms", 94);
  GLenum error = GL_NO_ERROR;
    error = glGetError();
    if (GL_NO_ERROR != error) {
        printf("GL Error %x encountered in %s.\n", error);
    }
  glBindVertexArrayAPPLE(g_vaoHandle);

  for (int n = 0; n < draw_data->CmdListsCount; n++)
  {
      const ImDrawList* cmd_list = draw_data->CmdLists[n];
      const ImDrawIdx* idx_buffer_offset = 0;

      glBindBuffer(GL_ARRAY_BUFFER, g_vboHandle);
      glBufferData(GL_ARRAY_BUFFER, (GLsizeiptr)cmd_list->VtxBuffer.size() * sizeof(ImDrawVert), (GLvoid*)&cmd_list->VtxBuffer.front(), GL_STREAM_DRAW);

      glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_elementsHandle);
      glBufferData(GL_ELEMENT_ARRAY_BUFFER, (GLsizeiptr)cmd_list->IdxBuffer.size() * sizeof(ImDrawIdx), (GLvoid*)&cmd_list->IdxBuffer.front(), GL_STREAM_DRAW);
      if(glGetError() != GL_NO_ERROR){std::cout << "houston we have a binding" << std::endl;}


      for (const ImDrawCmd* pcmd = cmd_list->CmdBuffer.begin(); pcmd != cmd_list->CmdBuffer.end(); pcmd++)
      {
          if (pcmd->UserCallback)
          {
              pcmd->UserCallback(cmd_list, pcmd);
          }
          else
          {
              glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->TextureId);
              glScissor((int)pcmd->ClipRect.x, (int)(fb_height - pcmd->ClipRect.w), (int)(pcmd->ClipRect.z - pcmd->ClipRect.x), (int)(pcmd->ClipRect.w - pcmd->ClipRect.y));
              glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer_offset);
          }
          idx_buffer_offset += pcmd->ElemCount;
      }
  }
  if(glGetError() != GL_NO_ERROR){std::cout << "houston we have a drawing" << std::endl;}

  // Restore modified GL state
  glUseProgram(last_program);
  glActiveTexture(last_active_texture);
  glBindTexture(GL_TEXTURE_2D, last_texture);
  glBindVertexArrayAPPLE(last_vertex_array);
  glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer);
  glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, last_element_array_buffer);
  glBlendEquationSeparate(last_blend_equation_rgb, last_blend_equation_alpha);
  glBlendFunc(last_blend_src, last_blend_dst);
  if (last_enable_blend) glEnable(GL_BLEND); else glDisable(GL_BLEND);
  if (last_enable_cull_face) glEnable(GL_CULL_FACE); else glDisable(GL_CULL_FACE);
  if (last_enable_depth_test) glEnable(GL_DEPTH_TEST); else glDisable(GL_DEPTH_TEST);
  if (last_enable_scissor_test) glEnable(GL_SCISSOR_TEST); else glDisable(GL_SCISSOR_TEST);
  glViewport(last_viewport[0], last_viewport[1], (GLsizei)last_viewport[2], (GLsizei)last_viewport[3]);
    if(glGetError() != GL_NO_ERROR){std::cout << "houston we have a reinitializing" << std::endl;}

}
예제 #20
0
파일: ge_context.c 프로젝트: lmorel3/libge
void geBlendEquation(int mode){
	glBlendEquation(mode);
}
예제 #21
0
void BlendEquationProtocol::onBlendEquationBegin(
	const cocos2d::Mat4 &transform, uint32_t flags)
{
	glBlendEquation(m_blendEquation);
}
예제 #22
0
//----------------------------------------------------------------------------------------------------------------------
// The SSAO pass.
// It uses the position and normal texture attachements.
// The result is blended in the texture 7 (COLOR_ATTACHEMENT7) which holds the final image
// The blending is done using the alpha channel since the ssao is outputed in the alpha channel in the shader.
//
void DeferredShading::generateSSAOPass(GLint &_shaderNumber,
                                       ngl::TransformStack &_tx
                                      )
{
    // We attach our SSAO texture.
    glDrawBuffer(GL_COLOR_ATTACHMENT7);

    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, m_posTex);
    glActiveTexture(GL_TEXTURE1);
    glBindTexture(GL_TEXTURE_2D, m_normTex);

    // The sample textures used in SSAO
    glActiveTexture(GL_TEXTURE19);
    // The sample texture loaded in the begining.
    glBindTexture(GL_TEXTURE_2D,11);

    glDisable(GL_DEPTH_TEST);
    glEnable(GL_BLEND);
    glBlendEquation(GL_FUNC_ADD);
    // Blending the final image with the SSAO texture. In the shader we store the SSAO values as alpha.
    glBlendFunc(GL_ONE, GL_SRC_ALPHA);
    //glBlendFunc(GL_ONE, GL_ONE);


    if((_shaderNumber <= m_shaderNumber) && (_shaderNumber >= 0))
    {
        // Set our shader as active
        ngl::ShaderLib *shader=ngl::ShaderLib::instance();
        m_deferredShader[_shaderNumber]->setShaderAsActive();

        // Set the textures to be used.
        shader->setShaderParam1i("PosTex", 0);
        shader->setShaderParam1i("NormalTex", 2);
        shader->setShaderParam1i("SampleTex", 19);

        // Projection matrix
        ngl::Mat3 ProjectionMatrix = m_camera->getProjectionMatrix();
        shader->setShaderParamFromMat3("Projection",ProjectionMatrix);

        // Set the screensize in order to use the correct TexCoords
        shader->setShaderParam2f("gScreenSize", m_renderWidth, m_renderHeight);

        _tx.pushTransform();
        {
            // transformation matrices
            ngl::Mat4 MVP;
            MVP.identity();
            shader->setShaderParamFromMat4("MVP",MVP);

            // Render the quad with the SSAO
            glBindVertexArray(m_quad);
            glDrawArrays(GL_TRIANGLES, 0, 6);
            glDisable(GL_BLEND);
        }
        _tx.popTransform();
    }
    else
    {
        std::cout<<"The shader with number "<< _shaderNumber<<" doesn't exist. Cannot render with an unknown shader! \n";
    }
}
예제 #23
0
JNIEXPORT void JNICALL Java_org_lwjgl_opengl_GL14_nglBlendEquation(JNIEnv *env, jclass clazz, jint mode, jlong function_pointer) {
    glBlendEquationPROC glBlendEquation = (glBlendEquationPROC)((intptr_t)function_pointer);
    glBlendEquation(mode);
}
예제 #24
0
static
void
do_presentation_queue_display(VdpPresentationQueueData *pqData)
{
    pthread_mutex_lock(&pqData->queue_mutex);
    assert(pqData->queue.used > 0);

    const int entry = pqData->queue.head;
    VdpDeviceData *deviceData = pqData->device;
    VdpOutputSurface surface = pqData->queue.item[entry].surface;
    const uint32_t clip_width = pqData->queue.item[entry].clip_width;
    const uint32_t clip_height = pqData->queue.item[entry].clip_height;

    // remove first entry from queue
    pqData->queue.used --;
    pqData->queue.freelist[pqData->queue.head] = pqData->queue.firstfree;
    pqData->queue.firstfree = pqData->queue.head;
    pqData->queue.head = pqData->queue.item[pqData->queue.head].next;
    pthread_mutex_unlock(&pqData->queue_mutex);

    VdpOutputSurfaceData *surfData = handle_acquire(surface, HANDLETYPE_OUTPUT_SURFACE);
    if (surfData == NULL)
        return;

    glx_context_push_global(deviceData->display, pqData->target->drawable, pqData->target->glc);

    const uint32_t target_width  = (clip_width > 0)  ? clip_width  : surfData->width;
    const uint32_t target_height = (clip_height > 0) ? clip_height : surfData->height;

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(0, target_width, target_height, 0, -1.0, 1.0);
    glViewport(0, 0, target_width, target_height);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    glMatrixMode(GL_TEXTURE);
    glLoadIdentity();
    glScalef(1.0f/surfData->width, 1.0f/surfData->height, 1.0f);

    glEnable(GL_TEXTURE_2D);
    glDisable(GL_BLEND);
    glBindTexture(GL_TEXTURE_2D, surfData->tex_id);
    glColor4f(1, 1, 1, 1);
    glBegin(GL_QUADS);
        glTexCoord2i(0, 0);                        glVertex2i(0, 0);
        glTexCoord2i(target_width, 0);             glVertex2i(target_width, 0);
        glTexCoord2i(target_width, target_height); glVertex2i(target_width, target_height);
        glTexCoord2i(0, target_height);            glVertex2i(0, target_height);
    glEnd();

    if (global.quirks.show_watermark) {
        glEnable(GL_BLEND);
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
        glBlendEquation(GL_FUNC_ADD);
        glBindTexture(GL_TEXTURE_2D, deviceData->watermark_tex_id);

        glMatrixMode(GL_TEXTURE);
        glLoadIdentity();

        glColor3f(0.8, 0.08, 0.35);
        glBegin(GL_QUADS);
            glTexCoord2i(0, 0);
            glVertex2i(target_width - watermark_width, target_height - watermark_height);

            glTexCoord2i(1, 0);
            glVertex2i(target_width, target_height - watermark_height);

            glTexCoord2i(1, 1);
            glVertex2i(target_width, target_height);

            glTexCoord2i(0, 1);
            glVertex2i(target_width - watermark_width, target_height);
        glEnd();
    }

    glXSwapBuffers(deviceData->display, pqData->target->drawable);

    struct timespec now;
    clock_gettime(CLOCK_REALTIME, &now);
    surfData->first_presentation_time = timespec2vdptime(now);
    surfData->status = VDP_PRESENTATION_QUEUE_STATUS_IDLE;

    if (global.quirks.log_pq_delay) {
            const int64_t delta = timespec2vdptime(now) - surfData->queued_at;
            const struct timespec delta_ts = vdptime2timespec(delta);
            traceInfo("pqdelay %d.%09d %d.%09d\n", (int)now.tv_sec, (int)now.tv_nsec,
                      delta_ts.tv_sec, delta_ts.tv_nsec);
    }

    GLenum gl_error = glGetError();
    glx_context_pop();
    handle_release(surface);

    if (GL_NO_ERROR != gl_error) {
        traceError("error (VdpPresentationQueueDisplay): gl error %d\n", gl_error);
    }
}
예제 #25
0
/*** Función: configura openGL ***/
void SetOpenGL( int width, int height      ,  // Dimensión del la ventana
		const GLfloat* clearColor  ,  // Color de borrado
		const GLfloat* ambientColor ) // Color de luz ambiente natural
{
  // Habilito el uso de arreglos de vértices, normales y texturas
  glEnableClientState( GL_VERTEX_ARRAY );
  glEnableClientState( GL_NORMAL_ARRAY );
  glEnableClientState( GL_TEXTURE_COORD_ARRAY );
    
  // Sólido
  glPolygonMode( GL_FRONT_AND_BACK, GL_FILL );

  // Habilito back-face culling
  glEnable( GL_CULL_FACE );
  // Descarte los polígonos mirando hacia atrás
  glCullFace( GL_BACK );
  // Cara delantera sentido horario
  glFrontFace( GL_CW );

  // Habilito el Z-buffer
  glEnable( GL_DEPTH_TEST );
  // La función de profundidad
  glDepthFunc( GL_LEQUAL );

  // Habilito luces
  glEnable( GL_LIGHTING );
  // Suavizado para los colores de luz
  glShadeModel( GL_SMOOTH );
  // Normalizar los vértices normales
  glEnable( GL_NORMALIZE );
  // Luz ambiente promedio
  glLightModelfv( GL_LIGHT_MODEL_AMBIENT, ambientColor );
  // Habilito las luces especulares respecto a la cámara
  glLightModeli( GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR );
  glLightModeli( GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE );

  // Habilito texturas
  glEnable( GL_TEXTURE_2D );
  // Filtro de las texturas
  glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
  glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );

  // Especifico la forma de blending(transparencia)
  glBlendEquation( GL_FUNC_ADD );
  glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
  glAlphaFunc( GL_GREATER, 0 );

  // Habilito los puntos con AA
  glEnable( GL_POINT_SMOOTH );
    
  // Mejoras
  glHint( GL_POINT_SMOOTH_HINT          , GL_NICEST );
  glHint( GL_LINE_SMOOTH_HINT           , GL_NICEST );
  glHint( GL_POLYGON_SMOOTH_HINT        , GL_NICEST );
  glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST );
  glHint( GL_GENERATE_MIPMAP_HINT       , GL_NICEST );
  glHint( GL_TEXTURE_COMPRESSION_HINT   , GL_NICEST );
  glHint( GL_FOG_HINT                   , GL_NICEST );

  // Color de limpiado
  glClearColor( clearColor[0], clearColor[1], clearColor[2], clearColor[3] );
  // Limpiado del Z-buffer
  glClearDepth( 1.0f );
  // Limipado del Stencil-buffer
  glClearStencil( 0 );

  // Viewport
  glViewport( 0, 0, width, height );
}
예제 #26
0
void GAFSprite::draw(void)
{
	if (_isLocator)
	{
		return;
	}
    CC_PROFILER_START_CATEGORY(kCCProfilerCategorySprite, "GAFSprite - draw");
	
    CCAssert(!m_pobBatchNode, "If CCSprite is being rendered by CCSpriteBatchNode, CCSprite#draw SHOULD NOT be called");
	
    CC_NODE_DRAW_SETUP();
	
    if (_useSeparateBlendFunc)
    {
        glBlendFuncSeparate(_blendFuncSeparate.src,      _blendFuncSeparate.dst,
                            _blendFuncSeparate.srcAlpha, _blendFuncSeparate.dstAlpha);
    }
    else
    {
        ccGLBlendFunc(m_sBlendFunc.src, m_sBlendFunc.dst);
    }
    
    if (_blendEquation != -1)
    {
        glBlendEquation(_blendEquation);
    }
	
    if (m_pobTexture != NULL)
    {
        ccGLBindTexture2D( m_pobTexture->getName() );
    }
    else
    {
        ccGLBindTexture2D(0);
    }
    
    //
    // Attributes
    //
	
    ccGLEnableVertexAttribs( kCCVertexAttribFlag_PosColorTex );
	setUniformsForFragmentShader();
	CHECK_GL_ERROR_DEBUG();
	
#define kQuadSize sizeof(m_sQuad.bl)
    long offset = (long)&m_sQuad;
	
    // vertex
    int diff = offsetof( ccV3F_C4B_T2F, vertices);
    glVertexAttribPointer(kCCVertexAttrib_Position, 3, GL_FLOAT, GL_FALSE, kQuadSize, (void*) (offset + diff));
	
    // texCoods
    diff = offsetof( ccV3F_C4B_T2F, texCoords);
    glVertexAttribPointer(kCCVertexAttrib_TexCoords, 2, GL_FLOAT, GL_FALSE, kQuadSize, (void*)(offset + diff));
	
    // color
    diff = offsetof( ccV3F_C4B_T2F, colors);
    glVertexAttribPointer(kCCVertexAttrib_Color, 4, GL_UNSIGNED_BYTE, GL_TRUE, kQuadSize, (void*)(offset + diff));
	
    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
	
    CHECK_GL_ERROR_DEBUG();	
	
    CC_INCREMENT_GL_DRAWS(1);
	
    CC_PROFILER_STOP_CATEGORY(kCCProfilerCategorySprite, "GAFSprite - draw");
}
예제 #27
0
/*!****************************************************************************
 @Function		RenderScene
 @Return		bool		true if no error occured
 @Description	Main rendering loop function of the program. The shell will
                call this function every frame.
				eglSwapBuffers() will be performed by PVRShell automatically.
                PVRShell will also manage important OS events.
                Will also manage relevent OS events. The user has access to
                these events through an abstraction layer provided by PVRShell.
 ******************************************************************************/
bool OGLES2MaximumIntensityBlend::RenderScene()
{
	// Clears the color and depth buffer
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	
	// Enable blending
	glEnable(GL_BLEND);
	glBlendEquation(GL_MAX_EXT);
	
	/*
	 Calculates the frame number to animate in a time-based manner.
	 Uses the shell function PVRShellGetTime() to get the time in milliseconds.
	 */
	unsigned long ulTime = PVRShellGetTime();
	unsigned long ulDeltaTime = ulTime - m_ulTimePrev;
	m_ulTimePrev	= ulTime;
	m_fFrame	+= (float)ulDeltaTime * DEMO_FRAME_RATE;
	
	if (m_fFrame > m_Scene.nNumFrame-1)
		m_fFrame = 0;	
	
	// Sets the scene animation to this frame
	m_Scene.SetFrame(m_fFrame);
	PVRTVec3 vLightDir;
	
	{
		PVRTVec3	vFrom, vTo, vUp;
		VERTTYPE	fFOV;
		vUp.x = 0.0f;
		vUp.y = 1.0f;
		vUp.z = 0.0f;
		
		// We can get the camera position, target and field of view (fov) with GetCameraPos()
		fFOV = m_Scene.GetCameraPos(vFrom, vTo, 0) * 0.6;
		
		/*
		 We can build the world view matrix from the camera position, target and an up vector.
		 For this we use PVRTMat4LookAtRH().
		 */
		m_mView = PVRTMat4::LookAtRH(vFrom, vTo, vUp);
		
		vLightDir = vFrom;
		
		// Calculates the projection matrix
		bool bRotate = PVRShellGet(prefIsRotated) && PVRShellGet(prefFullScreen);
		m_mProjection = PVRTMat4::PerspectiveFovRH(fFOV, (float)PVRShellGet(prefWidth)/(float)PVRShellGet(prefHeight), CAM_NEAR, CAM_FAR, PVRTMat4::OGL, bRotate);
	}
	
	/*
	 A scene is composed of nodes. There are 3 types of nodes:
	 - MeshNodes :
	 references a mesh in the pMesh[].
	 These nodes are at the beginning of the pNode[] array.
	 And there are nNumMeshNode number of them.
	 This way the .pod format can instantiate several times the same mesh
	 with different attributes.
	 - lights
	 - cameras
	 To draw a scene, you must go through all the MeshNodes and draw the referenced meshes.
	 */
	
	for (int i=0; i<(int)m_Scene.nNumMeshNode; i++)
	{
		SPODNode* pNode = &m_Scene.pNode[i];
		
		// Gets pMesh referenced by the pNode
		SPODMesh* pMesh = &m_Scene.pMesh[pNode->nIdx];
		
		glBindBuffer(GL_ARRAY_BUFFER, m_aiVboID[i]);
		
		// Gets the node model matrix
		PVRTMat4 mWorld;
		mWorld = m_Scene.GetWorldMatrix(*pNode);
		
		PVRTMat4 mWorldView;
		mWorldView = m_mView * mWorld;
		
		// Retrieve the list of required uniforms
		CPVRTPFXEffect* pEffect;
		
		SPODMaterial* pMat = &m_Scene.pMaterial[pNode->nIdxMaterial];
		if(pMat->nIdxTexDiffuse != -1)
		{
			pEffect = m_pEffectTextured;
		}
		else
		{
			pEffect = m_pEffect;
		}
		
		pEffect->Activate();
		const CPVRTArray<SPVRTPFXUniform>& aUniforms = pEffect->GetUniformArray();
		
		/*
		 Now we loop over the uniforms requested by the PFX file.
		 Using the switch statement allows us to handle all of the required semantics
		 */
		for(unsigned int j = 0; j < aUniforms.GetSize(); ++j)
		{
			switch(aUniforms[j].nSemantic)
			{
				case ePVRTPFX_UsPOSITION:
				{
					glVertexAttribPointer(aUniforms[j].nLocation, 3, GL_FLOAT, GL_FALSE, pMesh->sVertex.nStride, pMesh->sVertex.pData);
					glEnableVertexAttribArray(aUniforms[j].nLocation);
				}
					break;
				case ePVRTPFX_UsNORMAL:
				{
					glVertexAttribPointer(aUniforms[j].nLocation, 3, GL_FLOAT, GL_FALSE, pMesh->sNormals.nStride, pMesh->sNormals.pData);
					glEnableVertexAttribArray(aUniforms[j].nLocation);
				}
					break;
				case ePVRTPFX_UsUV:
				{
					glVertexAttribPointer(aUniforms[j].nLocation, 2, GL_FLOAT, GL_FALSE, pMesh->psUVW[0].nStride, pMesh->psUVW[0].pData);
					glEnableVertexAttribArray(aUniforms[j].nLocation);
				}
					break;
				case ePVRTPFX_UsWORLDVIEWPROJECTION:
				{
					PVRTMat4 mWVP;
					
					// Passes the world-view-projection matrix (WVP) to the shader to transform the vertices
					mWVP = m_mProjection * mWorldView;
					glUniformMatrix4fv(aUniforms[j].nLocation, 1, GL_FALSE, mWVP.f);
				}
					break;
				case eUsINTENSITY:
				{
					int iMat           = pNode->nIdxMaterial;
					SPODMaterial* pMat = &m_Scene.pMaterial[iMat];
					float fIntensity   = pMat->pfMatDiffuse[0];			// Take R value for intensity
					
					glUniform1f(aUniforms[j].nLocation, fIntensity);
				}
					break;
				case ePVRTPFX_UsTEXTURE:
				{
					glUniform1i(aUniforms[j].nLocation, 0);
				}
					break;
				case ePVRTPFX_UsWORLDVIEWIT:
				{
					PVRTMat3 mWorldViewIT3x3(mWorldView.inverse().transpose());
					glUniformMatrix3fv(aUniforms[j].nLocation, 1, GL_FALSE, mWorldViewIT3x3.f);
				}
					break;
				case ePVRTPFX_UsLIGHTDIREYE:
				{
					PVRTVec4 vLightDirView = (m_mView * PVRTVec4(-vLightDir, 1.0f)).normalize();
					glUniform3fv(aUniforms[j].nLocation, 1, vLightDirView.ptr());
				}
					break;
			}
		}
		
		/*
		 Now that the model-view matrix is set and the materials ready,
		 call another function to actually draw the mesh.
		 */
		DrawMesh(pMesh);
		glBindBuffer(GL_ARRAY_BUFFER, 0);
		
		/*
		 Now disable all of the enabled attribute arrays that the PFX requested.
		 */
		for(unsigned int j = 0; j < aUniforms.GetSize(); ++j)
		{
			switch(aUniforms[j].nSemantic)
			{
				case ePVRTPFX_UsNORMAL:
				case ePVRTPFX_UsUV:
				case ePVRTPFX_UsPOSITION:
				{
					glDisableVertexAttribArray(aUniforms[j].nLocation);
				}
					break;
			}
		}
	}
	
	// Reset blending
	// Enable blending
	glBlendEquation(GL_FUNC_ADD);
	glDisable(GL_BLEND);
	
	// Determine which title to show. The default title is quite long, so we display a shortened version if
	// it cannot fit on the screen.
	const char* pszTitle = NULL;
	{
		bool bRotate = PVRShellGet(prefIsRotated) && PVRShellGet(prefFullScreen);
		
		float fW, fH;
		m_Print3D.MeasureText(&fW, &fH, 1.0f, c_pszTitle);
		
		int iScreenW = bRotate ? PVRShellGet(prefHeight) : PVRShellGet(prefWidth);
		if((int)fW >= iScreenW)
		{
			pszTitle = c_pszTitleShort;
		}
		else
		{
			pszTitle = c_pszTitle;
		}
	}
	
	// Displays the demo name using the tools. For a detailed explanation, see the training course IntroducingPVRTools
	m_Print3D.DisplayDefaultTitle(pszTitle, "", ePVRTPrint3DSDKLogo);
	m_Print3D.Flush();
	
	return true;
}
void DeferredShading::deferredDirectionalLight(
																							GLint &_shaderNumber,
																							ngl::TransformStack &_tx,
																							GLint &_lightIndex
																							)
{
	
	glDrawBuffer(GL_COLOR_ATTACHMENT7);
	
	glActiveTexture(GL_TEXTURE0);
	glBindTexture(GL_TEXTURE_2D, m_posTex);
	glActiveTexture(GL_TEXTURE1);
	glBindTexture(GL_TEXTURE_2D, m_normTex);
	glActiveTexture(GL_TEXTURE2);
	glBindTexture(GL_TEXTURE_2D, m_colorTex);
	glActiveTexture(GL_TEXTURE3);	
	glBindTexture(GL_TEXTURE_2D, m_tangentTex);
	glActiveTexture(GL_TEXTURE4);	
	glBindTexture(GL_TEXTURE_2D, m_binormalTex);
	glActiveTexture(GL_TEXTURE5);	
	glBindTexture(GL_TEXTURE_2D, m_normalMapTex);
	glActiveTexture(GL_TEXTURE6);	
	glBindTexture(GL_TEXTURE_2D, m_specularTex);

	glDisable(GL_DEPTH_TEST);
	glEnable(GL_BLEND);
	glBlendEquation(GL_FUNC_ADD);
	glBlendFunc(GL_ONE, GL_ONE);

	if((_shaderNumber <= m_shaderNumber) && (_shaderNumber >= 0))
	{
		// Set our shader as active
		ngl::ShaderLib *shader=ngl::ShaderLib::instance();
		m_deferredShader[_shaderNumber]->setShaderAsActive();
		
		// Making the light stay fixed relative to the world. 
		// This is the only way to make it "stick". Multiplying by the transpose matrix doesn't work for unknown reasons...
		ngl::Vec4 m_currPos = m_deferredShader[_shaderNumber]->m_light[_lightIndex]->getPos();
		ngl::Mat4 globalMV =  _tx.getGlobalTransform().getMatrix() * m_camera->getViewMatrix();
		// For rotation
		m_currPos = m_currPos * globalMV;
		// For position
		m_currPos.m_x = m_currPos.m_x + globalMV.m_30;
		m_currPos.m_y = m_currPos.m_y + globalMV.m_31;
		m_currPos.m_z = m_currPos.m_z + globalMV.m_32;
		ngl::Vec4 result = ngl::Vec4(m_currPos.m_x, m_currPos.m_y, m_currPos.m_z, m_currPos.m_w);
					
		// load these values to the shader as well
		m_deferredShader[_shaderNumber]->m_light[_lightIndex]->loadToShader("light");
		shader->setShaderParam4f("light.position",result.m_x, result.m_y, result.m_z, result.m_w);	

		shader->setShaderParam2f("gScreenSize", m_renderWidth, m_renderHeight);
		_tx.pushTransform();
		{
			// transformation matrices
			ngl::Mat4 MVP;
			MVP.identity();
			shader->setShaderParamFromMat4("MVP",MVP);

			// Render the quad
			glBindVertexArray(m_quad);
			glDrawArrays(GL_TRIANGLES, 0, 6);
			glDisable(GL_BLEND);
		}
		_tx.popTransform();
	}
	else
		{
			std::cout<<"The shader with number "<< _shaderNumber<<" doesn't exist. Cannot render with an unknown shader! \n";
		}
}
예제 #29
0
	void FoamPass::Advance(double _dt)
	{
		for (auto node : m_nodeGroup.Nodes())
		{
			TerrainGeometry& terrainGeom = *node->geom;
			FoamParticleGeom& particleGeom = *node->foamGeom;
			TerrainMaterial& material = *node->material;

			// Update
			{
				glBindProgramPipeline(GL_NONE);

				m_foamParticleUpdateShader.BindPerPass();
			
				if (particleGeom.Switch())
				{
					GL_CHECK(glBindTransformFeedback(GL_TRANSFORM_FEEDBACK, particleGeom.TransformFeedbackObjB()));
					GL_CHECK(glBindVertexArray(particleGeom.VertexArrayA()));
				}
				else
				{
					GL_CHECK(glBindTransformFeedback(GL_TRANSFORM_FEEDBACK, particleGeom.TransformFeedbackObjA()));
					GL_CHECK(glBindVertexArray(particleGeom.VertexArrayB()));
				}

				GL_CHECK(glBeginTransformFeedback(GL_POINTS));
				GL_CHECK(glEnable(GL_RASTERIZER_DISCARD));

				auto& vertexShader = m_foamParticleUpdateShader.VertexShader();

				vertexShader.SetTexture("s_heightData", terrainGeom.HeightData().GetRead());
				vertexShader.SetTexture("s_velocityData", terrainGeom.VelocityData().GetRead());

				GL_CHECK(glDrawArrays(GL_POINTS, 0, particleGeom.NumParticles()));

				GL_CHECK(glDisable(GL_RASTERIZER_DISCARD));
				GL_CHECK(glEndTransformFeedback());
				glUseProgram(GL_NONE);

				particleGeom.Switch(!particleGeom.Switch());
			}

			// Draw
			{
				m_shader.BindPerPass();

				glEnable(GL_BLEND);
				glBlendEquation(GL_FUNC_ADD);
				glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
				glEnable(GL_DEPTH_TEST);
				glDepthMask(GL_FALSE);
				glPointSize(1.0f);

				RenderParams::SetModelMatrix(node->transform->matrix);

				GLuint vertexArray = particleGeom.Switch() ? particleGeom.VertexArrayA() : particleGeom.VertexArrayB();

				GL_CHECK(glBindVertexArray(vertexArray));

				m_shader.BindPerPass();
				m_shader.VertexShader().SetUniform("u_mvpMatrix", RenderParams::ModelViewProjectionMatrix());

				m_shader.VertexShader().SetUniform("u_lightDir", -glm::euclidean(vec2(material.lightAltitude, material.lightAzimuth)));
				m_shader.VertexShader().SetUniform("u_lightIntensity", material.directLightIntensity);
				m_shader.VertexShader().SetUniform("u_ambientLightIntensity", material.ambientLightIntensity);

				//glEnable(GL_PROGRAM_POINT_SIZE);
				GL_CHECK(glDrawArrays(GL_POINTS, 0, particleGeom.NumParticles()));
				//glDisable(GL_PROGRAM_POINT_SIZE);

				glBindVertexArray(GL_NONE);
				glEnable(GL_DEPTH_TEST);
				glDepthMask(GL_TRUE);
				glDisable(GL_BLEND);
			}
		}
	}
예제 #30
0
void CGEDebugger::UpdatePrimPreview(u32 op) {
	const u32 prim_type = (op >> 16) & 0xFF;
	int count = op & 0xFFFF;
	if (prim_type >= 7) {
		ERROR_LOG(COMMON, "Unsupported prim type: %x", op);
		return;
	}
	if (!gpuDebug) {
		ERROR_LOG(COMMON, "Invalid debugging environment, shutting down?");
		return;
	}
	if (count == 0) {
		return;
	}

	const GEPrimitiveType prim = static_cast<GEPrimitiveType>(prim_type);
	static std::vector<GPUDebugVertex> vertices;
	static std::vector<u16> indices;

	if (!gpuDebug->GetCurrentSimpleVertices(count, vertices, indices)) {
		ERROR_LOG(COMMON, "Vertex preview not yet supported");
		return;
	}

	if (prim == GE_PRIM_RECTANGLES) {
		ExpandRectangles(vertices, indices, count, gpuDebug->GetGState().isModeThrough());
	}

	float fw, fh;
	float x, y;

	frameWindow->Begin();
	frameWindow->GetContentSize(x, y, fw, fh);

	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	glBlendEquation(GL_FUNC_ADD);
	glBindTexture(GL_TEXTURE_2D, 0);
	glViewport(x, y, fw, fh);
	glScissor(x, y, fw, fh);
	BindPreviewProgram(previewProgram);

	float scale[] = {
		480.0f / (float)PSP_CoreParameter().renderWidth,
		272.0f / (float)PSP_CoreParameter().renderHeight,
	};

	Matrix4x4 ortho;
	ortho.setOrtho(0, frameWindow->TexWidth() * scale[0], frameWindow->TexHeight() * scale[1], 0, -1, 1);
	glUniformMatrix4fv(previewProgram->u_viewproj, 1, GL_FALSE, ortho.getReadPtr());
	glEnableVertexAttribArray(previewProgram->a_position);
	glVertexAttribPointer(previewProgram->a_position, 3, GL_FLOAT, GL_FALSE, sizeof(GPUDebugVertex), (float *)vertices.data() + 2);

	if (indices.empty()) {
		glDrawArrays(glprim[prim], 0, count);
	} else {
		glDrawElements(glprim[prim], count, GL_UNSIGNED_SHORT, indices.data());
	}

	frameWindow->End();

	texWindow->Begin();
	texWindow->GetContentSize(x, y, fw, fh);

	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	glBlendEquation(GL_FUNC_ADD);
	glBindTexture(GL_TEXTURE_2D, 0);
	glViewport(x, y, fw, fh);
	glScissor(x, y, fw, fh);
	BindPreviewProgram(texPreviewProgram);

	// TODO: Probably there's a better way and place to do this.
	if (indices.empty()) {
		for (int i = 0; i < count; ++i) {
			vertices[i].u -= floor(vertices[i].u);
			vertices[i].v -= floor(vertices[i].v);
		}
	} else {
		for (int i = 0; i < count; ++i) {
			vertices[indices[i]].u -= floor(vertices[indices[i]].u);
			vertices[indices[i]].v -= floor(vertices[indices[i]].v);
		}
	}

	ortho.setOrtho(0.0, 1.0, 1.0, 0.0, -1.0, 1.0);
	glUniformMatrix4fv(texPreviewProgram->u_viewproj, 1, GL_FALSE, ortho.getReadPtr());
	glEnableVertexAttribArray(texPreviewProgram->a_position);
	glVertexAttribPointer(texPreviewProgram->a_position, 2, GL_FLOAT, GL_FALSE, sizeof(GPUDebugVertex), (float *)vertices.data());
	if (indices.empty()) {
		glDrawArrays(glprim[prim], 0, count);
	} else {
		glDrawElements(glprim[prim], count, GL_UNSIGNED_SHORT, indices.data());
	}

	texWindow->End();
}