OpenGL Learning (iii) the first triangle __opengl

Source: Internet
Author: User
Preface

Learn OPENCV English web site:https://learnopengl.com/#!Getting-started/Hello-Triangle

Chinese translation: https://learnopengl-cn.github.io/01%20Getting%20started/04%20Hello%20Triangle/

Related code: Https://github.com/JoeyDeVries/LearnOpenGL

This article uses the code to have the related modification, is easier to understand the learning noun term

OpenGL Pipeline

opengl3.0 the difference is no longer the use of fixed pipeline programming, but the use of programmable pipelines, giving developers more freedom, but also because of this reason, OpenGL learning threshold has become higher.

The following is a diagram of a fixed pipeline in Little Red Book

This diagram is mainly about the inclusion of the shader in the specific pipeline of OpenGL. It would be nice to have this concept first. OpenGL programs can be seen as such a process. We have water piped into different pools from the most primitive pool, and the last water from that pool is what we need, and the different pools are the same as the shaders, and the pool may perform different chemical physical treatment (eg: filtration) equivalent to the different operation of the shader.

Here's an OpenGL 4.5 official manual.

And this cover diagram is mainly about the data flow between the various shaders. Detailed parsing is required later

core mode and compatibility mode

OpenGL discards programming based on fixed pipelines, starting with version 3.1. At the beginning of the GLSL you need to specify whether the core or compatibility mode is used, the core mode only supports shader based programming, and the compatibility mode includes a fixed pipeline.

vertex objects and cached objects
The vertex object holds the address of the cached object, while the cached object holds the true data content. Look at the picture specifically.
Code Analysis

code Download

http://download.csdn.net/detail/zhouyelihua/9885329

Critical Code Snippet Analysis

   unsigned int vbo, Vao;
    Glgenvertexarrays (1, &vao);//Create a top point group
    glgenbuffers (1, &VBO);//Create a Cache object
    Glbindvertexarray (VAO); Bind the vertex array, remembering that the binding operation is a bit like a valve, all subsequent operations will be based on this bound object
    glbindbuffer (Gl_array_buffer, VBO); Specifies the type of the current cache object
    Glbufferdata ( Gl_array_buffer, sizeof (vertices), vertices, gl_static_draw);//used to bind data to the specified BUFFER, and if the object that is bound has previously been associated with the object, the associated object will be deleted first
    glvertexattribpointer (0, 3, Gl_float, Gl_false, 3 * sizeof (FLOAT), (void*) 0);
    Glenablevertexattribarray (0);
    Glbindbuffer (gl_array_buffer, 0);
    Glbindvertexarray (0);

  

Code

#include <iostream> #include <glad/glad.h> #include <GLFW/glfw3.h> void Framebuffer_size_callback ( glfwwindow* window, int width, int height)//This is a callback function that changes windows. Note Input parameters//is a GLFW window, a width and height of {glviewport (0, 0
                                    , width, height);//This is the content within the callback function//This is to change the viewport to a changed window size
                                    Note that the required registration of the callback function//glfwsetframebuffersizecallback (window, framebuffer_size_callback); Two parameters are, GLFW windows and callback functions} void ProcessInput (Glfwwindow *window) {if Glfwgetkey (win Dow, Glfw_key_escape) = = glfw_press)//Get key, if equal to ESC glfwsetwindowshouldclose (window, true);//Use force window should close} gluint l
    Oadshader (glenum type, const char *SHADERSRC) {//load shader gluint shader;
    Glint complied;
    Shader = Glcreateshader (type);//Create shader if (shader = 0)//create failure return 0; Glshadersource (shader, 1, &sHADERSRC, NULL)//Load shader program, first parameter is created shader number,//The second program is the number of shaders, this                    The default is 1//The third is the shader input glcompileshader (shader);                                    Compile shader Glgetshaderiv (shader, Gl_compile_status, &complied);//Get the compiler state of the shader if (!complied) {
        View error message Glint Infolen = 0;
        Glgetshaderiv (shader, Gl_info_log_length, &infolen);
            if (Infolen > 1) {char* Infolog = (char*) (malloc (sizeof (sizeof (char) *infolen)));
            Std::cout << "Error compling shader:\n" << infolog << "\ n";
        Free (infolog);
        } gldeleteshader (shader);
    return 0;
return shader;
    }/* Vertex shader handles vertex-related anything, or it may be simple to do fixed-point data delivery a complex application may contain a lot of vertex shaders, but at the same time there can only be one at work. * unsigned int vertexshader () {//Vertex shader                          Char vertexshadersource[] = "#version 450 core            \ r/* Version number/* Layout (location = 0) in VEC3 APos;                                                      \ n "" void main () \ n "" {    \ n "" "Gl_position = Vec4 (apos.x, Apos.y, Apos.z, 1.0);
    \ n ' "} \ n";
    unsigned int vertexshader;
    VertexShader = Loadshader (Gl_vertex_shader, Vertexshadersource);
    Std::cout << vertexshader << Std::endl;
return vertexshader;
        The/* Chip shader programmatically controls the stage of the display color on the screen, called the chip coloring phase * * unsigned int fragmentshader () {//Chip shader char fragmentshadersource[] =                                "#version 450 core \ n" "Out VEC4 Fragcolor;                                                  \ n "" void main () \ n "" {       \ n "" "Fragcolor = Vec4 (1.0f, 0.5f, 0.2f, 1.0f);
       \ n " "} \ n";
    unsigned int fragmentshader;
    Fragmentshader = Loadshader (Gl_fragment_shader, Fragmentshadersource);
    Std::cout << fragmentshader << Std::endl;
return fragmentshader; int main () {glfwinit ();//similar to previous Gluinit general libraries are required to initialize//version number is opengl4.5 Glfwwindowhint (glfw_context _version_major, 4)//Set major version number Glfwwindowhint (Glfw_context_version_minor, 5);//Set minor version number Glfwwindowhint (glfw_opengl_prof
    ILE, Glfw_opengl_core_profile); Glfwwindowhint (Glfw_opengl_forward_compat, gl_true);//on the MAC system you need to set the statement glfwwindow* window = Glfwcreatewindow (800,
                                                                               , "Learnopengl", NULL, NULL);//The following two parameters are set to display and share, 
    General library functions related definitions,//can be configured to directly view all have a detailed definition if (window = = NULL) {std::cout << "Failed to create GLFW window" << Std::endl;
        Glfwterminate ();
    return-1;
    } glfwmakecontextcurrent (window);
                                                            if (!gladloadglloader (GLADLOADPROC) glfwgetprocaddress)//Initializes glad before calling the OpenGL function,  The role of glad is to quickly map OpenGL functions to related graphics functions {std::cout << "Failed to initialize glad" <<
        Std::endl;
    return-1; Glviewport (0, 0, 800, 600);/Set viewport size glfwsetframebuffersizecallback (window, framebuffer_size_callback);//register function, this function
    You can also register callback functions//unsigned int shaderprogram for other related hardware;
    Shaderprogram = Glcreateprogram ();
    Glattachshader (Shaderprogram, VertexShader ());
    Glattachshader (Shaderprogram, Fragmentshader ());
    Gllinkprogram (Shaderprogram);
    int success;
    Char infolog[512];
    GLGETPROGRAMIV (Shaderprogram, Gl_link_status, &success);
        if (!success) {Glgetprograminfolog (Shaderprogram, A, NULL, Infolog); Std::cout <&Lt
    "Error::shader::P rogram::linking_failed\n" << Infolog << Std::endl;
    } gldeleteshader (VertexShader ());
    Gldeleteshader (Fragmentshader ());
    Float vertices[] = { -0.5f, -0.5f, 0.0f, 0.5f, -0.5f, 0.0f, 0.0f, 0.5f, 0.0f};
    unsigned int vbo, VAO;
    Glgenvertexarrays (1, &vao);
    Glgenbuffers (1, &AMP;VBO);
    Bind the Vertex Array Object-then bind and set Vertex buffer (s), and then configure Vertex attributes (s).

    Glbindvertexarray (VAO);
    Glbindbuffer (Gl_array_buffer, VBO);

    Glbufferdata (Gl_array_buffer, sizeof (vertices), vertices, gl_static_draw);
    Glvertexattribpointer (0, 3, Gl_float, Gl_false, 3 * sizeof (FLOAT), (void*) 0);

    Glenablevertexattribarray (0); The "is" allowed, the call to Glvertexattribpointer registered VBO as the vertex attribute ' s bound vertex

    Er object So afterwards we can safely unbind Glbindbuffer (gl_array_buffer, 0); You can unbind the Vao aftErwards so-Vao calls won ' t accidentally modify this Vao, but this rarely happens.  modifying other//Vaos requires a call to glbindvertexarray anyways so we generally don ' t unbind Vaos (nor VBOs) when
    It ' s not directly necessary.


    Glbindvertexarray (0);
    Uncomment this call to draw in wireframe polygons.

    Glpolygonmode (Gl_front_and_back, gl_line); Render loop//render process while (!glfwwindowshouldclose (window))//detects whether the GLFW window is ordered to be closed and, if so, exits the loop {//input
        Related Operations ProcessInput (window)///rendering related Operations Glclearcolor (0.0f, 0.3f, 0.3f, 1.0f);
        Glclear (Gl_color_buffer_bit);
        Draw our triangle Gluseprogram (Shaderprogram); Glbindvertexarray (VAO); Seeing as we only have a single Vao there's no need to bind it every time, but we ' ll do so to keep things a bit more or
        Ganized gldrawarrays (gl_triangles, 0, 3); View all events, and Swap memory glfwswapbuffers (window),//Swap color cache, that is, the contents of the GLFW window ... AttentionThe difference between the opening of the GLFW and the beginning of the rear GL glfwpollevents ();//detect if there are other triggering times, such as the above window size changes, need to invoke the relevant callback function} glfwterminate ();//Clear Exit R
Eturn 0;

 }

Experimental Results


If you feel that this blog is useful to you, welcome to my small sponsorship.




A programmer who does not raise money to marry a daughter-in-law is not a good programmer.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.