OpenGL Learning Notes: (1) OpenGL environment setup under Mac

Source: Internet
Author: User
Tags sprintf windows support

What is 1,opengl? OpenGL (Full-write open graphics Library) is a professional graphics program interface that defines a cross-programming language, cross-platform programming interface specification. It is used for three-dimensional image (two-dimensional also), is a powerful, easy to call the bottom-level graphics library.
What 2,OPENGL can do OpenGL can be used to develop a cross-platform rendering engine that can use OpenGL (ES) on Android, OSX, IOS, Windows, PS and other platforms.
3,opengl can not do what OpenGL can not do physical simulation, OpenGL can not do network communication, in a word, except rendering things, OpenGL can not do, OpenGL is just a 3D rendering API interface standard.
4,opengl VS DirectX OpenGL and DirectX have the following differences:
    1. OpenGL can only render, DirectX can do a lot of other than rendering, for example, DirectX contains d3dxmath can be used to do 3D mathematical operations, DirectX contains external device interface module can be used to accept external device input.
    2. OpenGL is just a standard that defines some interfaces, so long as these interfaces are implemented, OpenGL is implemented, and instead, DirectX is the only piece of code that Microsoft has implemented, and everyone uses that code from Microsoft.
    3. OpenGL can cross-platform, almost all platforms support OpenGL, from mobile devices to PC products to the host platform, all support OpenGL, and DirectX is only Microsoft's own Xbox and Windows support.
    4. In terms of speed, DirectX bursts OpenGL, and DirectX is twice times more than OpenGL rendering speed for the same hardware.
5,MAC OpenGL Environment SetupWhen I use OpenGL on my Mac, I use some of the following tools and libraries: Mac Ports, GLFW, Glew, XCode.
    1. MacPorts is the software used by the Mac platform to install third-party libraries, which is a bit like the Apt-install on Linux, and you can download them from https://www.macports.org/.
    2. Glfw,opengl extension, because OpenGL is just a rendering interface, if you want to write OpenGL rendering code on a specific platform, you need to use QLFW and other libraries to connect OpenGL and local windows and other environments, install GLFW only use Mac ports ( sudo port install GLFW).
    3. Glew, similar to GLFW, is installed using the sudo port install Glew.
    4. XCODE,MAC platform Development The only artifact, don't tell me on Mac you're still using eclipse to write C + +.
6,demo CodeHere, I only give a demo code, that is, using gourand coloring to draw a square, the code mainly consists of the following parts.
/* * File:shader.h * Author: zhangxiong * date:2016_02_21 * Purpose: Interface for defining OpenGL Shader Operations */#ifndef __zx_nxengine_s Hader_h__#define __zx_nxengine_shader_h__#include ".         /common/nxcore.h "namespace NX {class shader{public:/* * < function function > * constructor * * < function parameters > * Szfilepath: The path of the shader code to use, you need to ensure that only use Szfilepath, in the * program can find SH                  Ader file.         * Ushaertype: The shader type of the shader code to use, this type has gl_vertex_shader, etc. * exactly the same as the value used in OpenGL.        */Shader (const char* Szfilepath, Glenum ushadertype);    Virtual ~shader (); Public:/* * < functions > * compile shader,shader files and types are given by the constructor */virtual Std::st    Ring Compile ();        Public:operator Gluint () {return m_ushaderid;    } private:std::string Readshadersource ();        Private:gluint M_ushaderid; Glenum M_ushadertype;       Std::string M_strshadersourcefilepath; };} #endif

#include <fstream> #include <string> #include "NXShader.h" #include "NXLog.h" Nx::shader::shader (const char    * Szfilepath, Glenum ushadertype) {M_strshadersourcefilepath = (Szfilepath);    M_ushaderid = 0; M_ushadertype = Ushadertype;}        Nx::shader::~shader () {if (M_ushaderid! = 0) {gldeleteshader (M_ushaderid);        M_ushaderid = 0;    M_ushadertype = 0;    }}std::string Nx::shader::compile () {std::string strerr (256 + 1, 0);    M_ushaderid = Glcreateshader (M_ushadertype);    Const std::string STRSHADERSRC = Readshadersource (); if (Strshadersrc.empty ()) {sprintf ((char*) strerr.c_str (), "Shader file [%s] not exist or is empty", M_STRSHADERSOURC        Efilepath.c_str ());        Glb_getlog (). Log ("%s", Strerr.c_str ());    return strerr;    } const char * szshadersrc = STRSHADERSRC.C_STR ();    Glshadersource (M_ushaderid, 1, &AMP;SZSHADERSRC, NULL);    Glcompileshader (M_ushaderid); Glgetshaderinfolog (M_ushaderid, (gluint) streRr.length (), NULL, & (Strerr[0]); Glb_getlog (). log ("Compile shader [%s] with compile msg [%s]", M_strshadersourcefilepath.c_str (), (stre Rr[0] = = 0?    "Compile Succeed": Strerr.c_str ())); return strerr;}    std::string Nx::shader::readshadersource () {std::ifstream in (M_strshadersourcefilepath);    Std::string Line;    Std::string strshadersrc;        while (Std::getline (on, line)) {line + = "\ r \ n";    STRSHADERSRC + = line;    } in.close (); return strshadersrc;;}

/* * File:application.h * Author: zhangxiong * date:2016_02_21 * Purpose: Used to define OpenGL application interface, note that this interface uses GLFW and Glew, you need to first install the work With library, * on Mac can use MacPorts installation, specific operation please Google Macports,linux system use apt-get, * Windows system please directly download library and header file (own compilation estimate a bit pit) */#ifndef __zx_ Nxengine_application_h__#define __zx_nxengine_application_h__#include ".        /common/nxcore.h "namespace NX {class application{public:application ();    Virtual ~application (); Public:/* * < function > * Initialize OpenGL environment with GLFW and Glew libraries, note that this function should be the first class function called after the constructor, * Call this function and No other OpenGL functions should be called until successful.         Other classes If you inherit this class, you need to call the init function of this class first, and then execute the subclass's init code.     * * < function parameters > * vcmdline: Command line string array, similar to C's main function * Icmdcount: Number of command line strings * Iwidth: The width, in pixels, of the window used by OpenGL * Iheight:opengl the height of the window used (in pixels) * < return value > * true: Initial Successful, after Init, you can invoke other OpenGL functions * false: Initialization failed */virtual BOOL Init (__in const char* vcmdline[], __in C ONST int icmdcount, __in const int iwidth, __in const int iheight);         /* * < function function > * tick function in game.                * * < function parameters > * itime: Time, in seconds */virtual void Tick (const double deltatime);                 /* * < function > * The render function in the game, the main completion of the game rendering * * */virtual void render (); /* * < function > * main loop in game, other classes to inherit this class, it's best not to overload the run function to avoid unnecessary trouble * */V            irtual void Run (); Public:/* * < function function > * ERROR handling function * * < function parameter > * with GLFW Error         The parameters of the callback function are exactly the same.                */virtual void OnError (int error, const char* description);         /* * < function function > * ERROR handling Function * < function parameter > * The parameter meaning of the keyboard event callback function in GLFW is exactly the same    */virtual void onkeyevent (int key, int scancode, int action, int mods); };} #endif

#include <cstdio> #include <cstdlib> #include <ctime> #include <GL/glew.h> #include <glfw/ glfw3.h> #include "NXApplication.h" #include ". /math/nxmath.h "#include". /common/nxlog.h "static nx::application* g_pthis = null;static glfwwindow* G_window = null;static void Error_callba  CK (int error, const char* description), static void Key_callback (glfwwindow* window, int key, int scancode, int action, int Mods);    Nx::application::application () {g_pthis = NULL; G_window = NULL;}    Nx::application::~application () {g_pthis = NULL; G_window = NULL;}  BOOL Nx::application::init (const char* vcmdline[], const int icmdcount, const int iwidth, const int iheight) {g_pthis =    This    Nx::initnxmath ();        if (!glfwinit ()) {fprintf (stderr, "Failed initialize GLFW.");        Exit (Exit_failure);    return false;        } {Glfwseterrorcallback (error_callback);        Glfwwindowhint (Glfw_context_version_major, 3); Glfwwindowhint (Glfw_coNtext_version_minor, 3);        Glfwwindowhint (Glfw_opengl_forward_compat, gl_true);        Glfwwindowhint (Glfw_opengl_profile, glfw_opengl_core_profile);    Glfwwindowhint (glfw_resizable, gl_true);        } {glfwwindow* window = Glfwcreatewindow (iwidth, iheight, "OpenGL", NULL, NULL);            if (!window) {std::fprintf (stderr, "Failed to create GLFW window.");            Glfwterminate ();            Exit (Exit_failure);        return false;        } G_window = window;        Glfwmakecontextcurrent (window);    Glfwsetkeycallback (window, key_callback);    } glb_getlog (). LogtoConsole ("OpenGL version supported by this platform (%s)", Glgetstring (gl_version));    Glb_getlog (). Log ("OpenGL version supported by this platform (%s)", Glgetstring (Gl_vendor));    Glewexperimental = Gl_true;    Glewinit (); return true;}    void Nx::application::tick (const double deltatime) {static Double itotaltime = 0;    Itotaltime + = Deltatime;   static Char title[32]; static int iframecount = 0;    ++iframecount;        if (Itotaltime >= 1.0) {sprintf (Title, "FPS:%.2f", (Iframecount/itotaltime));        Iframecount = 0;        Itotaltime = 0;    Glfwsetwindowtitle (G_window, Title);    }}void Nx::application::render () {static const glfloat green[] = {0.0f, 0.25f, 0.0f, 1.0f}; GLCLEARBUFFERFV (gl_color, 0, green);} void Nx::application::onerror (int error, const char* description) {std::fputs (description, stderr);}    void nx::application::onkeyevent (int key, int scancode, int action, int mods) {if (G_window = = NULL) {return;    } if (key = = Glfw_key_escape && action = = glfw_press) {glfwsetwindowshouldclose (G_window, gl_true);    }}void Nx::application::run () {static Double pretime = Glfwgettime ();    static Double nowtime = Glfwgettime ();        while (!glfwwindowshouldclose (G_window)) {nowtime = Glfwgettime ();        Tick (Nowtime-pretime);        Render ();        Glflush (); Glfwswapbuffers (g_window);        Glfwpollevents ();    Pretime = Nowtime;    }}static void Error_callback (int error, const char* description) {if (!g_pthis) {return; } g_pthis->onerror (Error, description);} static void Key_callback (glfwwindow* window, int key, int scancode, int action, int mods) {if (!g_window) {retur    N } g_pthis->onkeyevent (Key, Scancode, action, mods);}

#ifndef __zx_opengl_application_chap1_1_h__#define __zx_opengl_application_chap1_1_h__#include <GL/glew.h># Include <GLFW/glfw3.h> #include ". /engine/render/nxapplication.h "#include". /engine/common/nxlog.h "#include".        /engine/render/nxprogram.h "class appchap1_1:public nx::application{public:typedef struct vertex{GLfloat x;        Glfloat y;        Glfloat R;        Glfloat G;        Glfloat b;    Glfloat A;    }vertex;public:appchap1_1 (); Virtual ~appchap1_1 ();p ublic:virtual bool Init (const char* vcmdline[], const int icmdcount, const int iwidth, const in    T iheight);    virtual void Tick (const double deltatime);    virtual void Render ();    virtual void onkeyevent (int key, int scancode, int action, int mods);p rivate:gluint M_uvbo1;    Gluint M_uvbo2;    Gluint M_uvao1;    Gluint M_uvao2;    Gluint M_usedvbo;    Gluint M_usedvao; NX::P rogram* m_pg;}; #endif

#include <iostream> #include "appchap1_1.h" #include "NXShader.h" Appchap1_1::appchap1_1 () {m_uvao1 = 0;    M_uvao2 = 0;    M_uvbo1 = 0;    M_uvbo2 = 0; M_usedvbo = 0;} Appchap1_1::~appchap1_1 () {}bool appchap1_1::init (const char* vcmdline[], const int icmdcount, const int iwidth, const int iheight) {if (!    Nx::application::init (Vcmdline, Icmdcount, iwidth, iheight)) {return false;        } {//vao1 glgenvertexarrays (1, &AMP;M_UVAO1);    Glbindvertexarray (M_UVAO1);        } {//vbo1 glgenbuffers (1, &AMP;M_UVBO1);        Glbindbuffer (Gl_array_buffer, M_uvbo1);            Vertex V[4] = {{ -1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f}, {1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f},        { -1.0f, -1.0f, 0.0f, 0.0f, 1.0f, 1.0f}, {1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f}};        Glbufferdata (Gl_array_buffer, sizeof (v), V, Gl_static_draw);    Glbindbuffer (gl_array_buffer, 0); } {//vao2 GlgenverTexarrays (1, &AMP;M_UVAO2);    Glbindvertexarray (M_UVAO2);        } {//vbo2 glgenbuffers (1, &m_uvbo2);        Glbindbuffer (Gl_array_buffer, M_uvbo2);            Vertex V[4] = {{ -0.8f, 0.8f, 0.0f, 1.0f, 1.0f, 1.0f}, {0.8f, 0.8f, 1.0f, 0.0f, 1.0f, 1.0f},        { -0.8f, -0.8f, 1.0f, 1.0f, 0.0f, 1.0f}, {0.8f, -0.8f, 0.0f, 0.0f, 0.0f, 1.0f}};        Glbufferdata (Gl_array_buffer, sizeof (v), V, Gl_static_draw);    Glbindbuffer (gl_array_buffer, 0);    } M_usedvao = M_uvao1;        M_usedvbo = M_uvbo1;        {//program M_pg = new NX::P Rogram ();        M_pg->addshader ("./REDBOOK/CHAP1/VS1_1.GLSL", Gl_vertex_shader);        M_pg->addshader ("./REDBOOK/CHAP1/FS1_1.GLSL", Gl_fragment_shader);        M_pg->linkprogram ();    M_pg->useprogram (); } return true;    void Appchap1_1::tick (const double deltatime) {}void appchap1_1::render () {M_pg->useprogram ();    Glclearcolor (0.0f, 0.25f, 0.0f, 1.0f);Glclear (Gl_color_buffer_bit |    Gl_depth_buffer_bit);    Glbindvertexarray (M_usedvao);    Glbindbuffer (Gl_array_buffer, M_usedvbo);    Glvertexattribpointer (0, 2, gl_float, Gl_false, sizeof (vertex), (void*) 0);    Glvertexattribpointer (1, 4, gl_float, Gl_false, sizeof (vertex), (void*) 8);    Glenablevertexattribarray (0);    Glenablevertexattribarray (1);    Glviewport (100, 100, 400, 100); Gldrawarrays (Gl_triangle_strip, 0, 4);} void appchap1_1::onkeyevent (int key, int scancode, int action, int mods) {application::onkeyevent (key, Scancode, action        , mods);    if (action = = glfw_press) {return;    } std::cout << "Change buffer ..." << Std::endl;    if (M_usedvbo = = M_uvbo1) {M_usedvbo = M_uvbo2;    }else{M_usedvbo = M_uvbo1;    } if (M_usedvao = = m_uvao1) {M_usedvao = M_uvao2;    }else{M_usedvao = m_uvao1; }}

#include <iostream> #include <memory> #include "NXShader.h" #include "NXLog.h" #include "NXVector.h" # Include "NXMatrix.h" #include "DemoHeader.h" int main (int argc, const char* argv[]) {    nx::glb_getlog (). LogtoConsole ( "Begin main");    Std::auto_ptr<nx::application> app (new Appchap1_1 ());    if (!app->init (argv, argc, +)) {        std::cout << "failed Init application ..." << Std::endl;        return 1;    }    Nx::glb_getlog (). LogtoConsole ("Begin Application");    App->run ();    Nx::glb_getlog (). LogtoConsole ("End Main");    return 0;}

#version 410 Corein  vec4 color;out vec4 vfinalcolor;void Main (void) {    vfinalcolor = Color;}

#version corelayout (location = 0) in vec2 vposition;layout (location = 1) in VEC4 vcolor;out vec4 color;void Main () {
   gl_position = VEC4 (vposition, -0.5f, 1.0f);    Color       = Vcolor;}


My entire development environment is as follows: (Download the code from the back to git to open it directly)


The results of the program are as follows:



After pressing any key on the keyboard (ESC exits the renderer), change to the following:


While learning OpenGL, I encapsulated some basic classes myself, such as program, shader, texture, etc., which I put on GitHub, which contains the code I listed above, the first one is simpler, and I don't want to spend more time talking about things, All we need to do is compile from git to get the same results, as for OpenGL's post-order learning and the code I've written, I'm going to send it slowly, and the code part will be sent to git, interested in the Welcome review.

OpenGL Learning Note: (1) OpenGL environment setup under Mac

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.