Visual Studio Code Opengl



This exercise requires Visual Studio 2012 Professional Edition.

  • GLUT Installation (only needs to be done once) back to top. Windows comes with OpenGL,.
  • Visual Studio Code is a code editor redefined and optimized for building and debugging modern web and cloud applications. Visual Studio Code is free and available on your favorite platform.

Compiler: After you have installed VSCode, the first thing to do is install the GCC compiler and GDB. Visual StudioでOpenGLを使うための準備.

Before you begin this exercise, be sure you have installed freeGLUT and GLEW.

Building a Core Profile OpenGL View Class with MFC Framework

When Visual C++ has started, you will see a Start Screen similar to this one:

2. Create a New Project

The following show you how to create a framework for theOpenGL viewing class. You will need to perform the following steps.

  • Create a new project:
    • Select the 'File' menu
    • Select 'New | Project'. A dialogue box will appear as shown below.
    • Under the project types section on the left, expand 'Installed | Templates' and locate the 'Visual C++' language templates. It might be under 'Other Languages' if you did not select C++ as your development environment when you first installed Visual Studio.
    • Select the MFC template category on the left, and choose 'MFC Application' to the right.
    • In the 'Name:' field, type OpenGL.
    • Leave the 'Location:' field at the default. Note the path for future reference.
      (*note, it is not recommended to work off of network drives; youmay get strange messages and inconsistencies when you build yourproject over a network).
    • Click the 'OK' button.

    You should now see a dialogue box as below:

    You will notice that on the left hand side are seven project setting options.The three that you will modify are circled in red.For thoroughness, we will go through all seven options.

  • In 'Application Type'
    • Select 'Single document'
    • Select 'Document/View architecture support'
    • Un-select 'Security Development Lifecycle (SDL) checks' - the security checks deprecate some insecure C routines that Dr. Angel's library uses.
    • Un-select 'Use Unicode libraries
    • Select 'MFC standard' - this will adjust some settings for you.
    • Select 'Use MFC in a shared DLL'
  • In 'Compound Document Support'
    • Make sure 'None' is selected
  • In 'Document Template Properties'
    • You do not have to worry about any of these settings
  • In 'Database Support'
    • Make sure 'None' is selected
  • In 'User Interface Features', the following setting are needed
    • 'Thick frame'
    • 'Minimize box'
    • 'Maximize box'
    • Under 'Command bars (menu/toolbar/ribbon):', select 'Use a classic menu' and uncheck the toolbar options
    • You can ignore all other settings
  • In 'Advanced Features'
    • Clear all the options (keep things simple for now)
  • In 'Generated Classes'
    • Should see four: COpenGLView, COpenGLApp, COpenGLDoc, and CMainFrame
  • Click the 'Finish' button
At this point, we have created a framework for the OpenGL program we areto develop. Your main window has changed. It now has three main regions.
  • Right Top: Code Editor where you can write and edit your programs.When you first start Visual Studio, this is the 'Start Page'.
  • Right Bottom: Feedback Area. Depending on your current activity this area might show code definitions, compiler output, or debug information.
  • Left: Project Management Panel: contains Solution Explorer (default), Class View, Property Manager, and Team Explorer. Choose the one you want with tabs at the bottom.
    • Solution Explorer shows you the files in the project or solution that you are working on.
    • Class View enables you to see the class hierarchies in your project.
    • Property Manager can be ignored for now.
    • Team Explorer can be ignored for now.

If your window differs from the one pictured, you can still probably find the same elements. Most likely the Solution Explorer and Property manager will be on the left. The exact layout does not matter much.

In the next section we will use the Class View tab in the Project Management Panel show the project's class hierarchy.There should be five classes (CAboutDlg, CMainFrame, COpenGLApp, COpenGLDoc, and COpenGLView) automatically created for the OpenGL project.One of them, called 'COpenGLView', will be particularly interesting toyou because the main task of this lab is to add message handling functions into this class to allow OpenGL to set up and render the view at the appropriate times.

At this point, you might want to build and run the application (which ofcourse does nothing yet) just to make sure your the wizard gave you a working project.

It should look something like this:

3. Add Necessary Member Functions to the COpenGLViewClass

The MFC Project Wizard creates the minimum number of memberfunctions for each class being generated. We may take a look at themby looking at the Class View:

Opengl C++ Visual Studio

  • Click on the 'Class View' tab underneath the 'Solution Explorer' on the right-hand side.
    OR
  • Choose 'View | Class View' from the menu
To examine COpenGLView class:
  • Expand the 'OpenGL' project by clicking on the arrow to the left of 'OpenGL'.
    You will now see the five classes that have been automatically created.
  • Click on 'COpenGLView'. There is no need to expand it.
  • If you examine the bottom panel of the Class view, you will see some member functions that have been automatically created including OnDraw and PreCreateWindow.
Now, with COpenGLView selected, we can add functions for the following additional messages:
  • WM_CREATE (for OnCreate)
  • WM_DESTROY (for OnDestroy)
  • WM_SIZE (for OnSize)

To add functions for these messages, first ensure that you have selected 'COpenGLView' in the 'Class View', then press Alt + Enter to open the Properties window. It will open on the right of the screen. You will notice that in the Properties window, some properties of 'COpenGLView' are listed. The icons along the top allow you to select other property types. We want to see and edit the message mapping list. Follow the example below to see how this is done, then add message handler functions for all the messages listed above.


  • Click on the messages icon (circled in red in the diagram to the left)
    You will see a listing of messages.
  • Scroll down in the 'Messages' window
  • Click on message 'WM_CREATE'
  • Notice that a drop-down arrow appears.
  • Click on the arrow and select ' OnCreate'.
  • You may notice that the OnCreate is added into the 'Class View' window. Visual Studio has created the member function for you. Remember that the system can only create a skeletonfor the member function. It is your responsibility to insert computationsinto the relevent member functions.

Click on COpenGLView again to add the next function and repeat as needed.

4. Compile Your Application

  • Choose 'Build' from the menu options
  • Select 'Build OpenGL'
It will take a little while to compile and link theprogram. You may look at the output from the compiling process being displayedin the Output region at the bottom.If the project has compiled successfully,you will see a message like this:

It is very exciting to run this little window's programif it is your first Windows program.

  • Choose 'Debug' from the menu options
  • Select 'Start Without Debugging'

A new window should be displayed in a few seconds.There are three menus: 'File', 'Edit', and 'Help'.These are the minimum options automatically created by your VC++ system.Don't be surprised; the inside window is totally blank, because we haven'twritten any functions yet.

NOTE: On Alex Clarke's VS2012 Professional install the OnCreate has several lines of garbage code that did not appear in previous versions. If your code does not compile try using this version of OnCreate instead:

5. Linking OpenGL Libraries

So far what we have created is all standard MFC stuff.It has nothing to do with OpenGL yet. To connect to OpenGL, we have doa few things first. Then we may use functions from OpenGL library.

First, we need to insert the following lines intoOpenGLView.h header file:

To add the above contents, you have to firstfind the desired header file. This is a good time to learn how to navigatearound the files of the project.

  • Click the 'Solution Explorer' tab (in the lower left), the 'root' folder should be displayed.
  • Click the '+' node, and subfolders should be displayed. Two of them are of interest to you at the moment. They are 'Source Files' and 'Header Files'.
  • Click the '+' node to the left of the 'Header Files' folder, you will see a number of header files are listed. One of them is 'OpenGLView.h'
  • Double click on this filename. The contents of the 'Editing Window' change to the contents in this file.

Now, you may add the above contents atthe very beginning of this header file. Remember to save the document beforeyou close this Editing window.

The next step is to add the OpenGL libraries to thelink line:

  • Choose the 'Project' menu option
  • Select 'OpenGL Properties'
    A dialogue box will appear similar to below.
  • Click on the 'Linker' folder to the left side of the dialogue
  • In the sub sections of 'Linker', click 'Input'.
    You should now see 'Additional Dependencies' on the top right-hand side.
  • Select the 'Additional Dependencies', click the arrow that appears to the right and select ''
  • att the following content to the top box:
    • opengl32.lib;glu32.lib;freeglut.lib;glew32.lib
  • Click 'OK', then 'OK' again.

Last, but not least, add support code from Lab 1 to your project by:

  • Downloading Angel.zip, uofrGraphics.zip
  • Extracting the files into your project folder next to the .cpp files that were generated by the Visual Studio wizard.
  • Downloading the shaders vshader.glsl and fshader.glsl to the project folder.
  • Adding all the new files (Angel.h, CheckErrors.h, fshader.glsl, InitShaders.cpp, mat.h, uofrGraphics.cpp uofrGraphics.h, vec.h, and vshader.glsli) to your project with the 'Project | Add Existing Item...' menu item.
  • Adding the line #include 'stdafx.h' as the very first line in InitShader.cpp and uofrGraphics.h
  • Adding the line #include <wglew.h> immediately after the line #include <glew.h>.

At this point, you might want compile your applicationagain to make sure that everything is right so far.

D. Editing Member Functions

Now that the OpenGL libraries have been added to our project, weare ready add some real OpenGL code. For this lab, you are concernedwith the COpenGLView class only. Therefore, you will workwith two files:

  • OpenGLView.h
  • OpenGLView.cpp

The code you will add will:

Opengl In Visual Studio

  1. Create and set up a Device Context
  2. Establish a Rendering Context
  3. Handle window events
  4. Draw a scene
  5. Clean up after itself

For now here are thechanges you need to make to the two files. The parts you will workwith are highlighted in red.

......class COpenGLView : public CView{protected: // create from serialization only .....// Attributespublic: ......// Operationspublic:// Overridespublic: ......// Implementationpublic: ......protected:// Generated message map functionsprotected: DECLARE_MESSAGE_MAP()public: afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); afx_msg void OnDestroy(); afx_msg void OnSize(UINT nType, int cx, int cy);};......
......// COpenGLViewIMPLEMENT_DYNCREATE(COpenGLView, CView)BEGIN_MESSAGE_MAP(COpenGLView, CView) ......END_MESSAGE_MAP()// COpenGLView construction/destructionCOpenGLView::COpenGLView(){ ......}......BOOL COpenGLView::PreCreateWindow(CREATESTRUCT& cs){ // TODO: Modify the Window class or styles here by modifying // the CREATESTRUCT cs return CView::PreCreateWindow(cs);}// COpenGLView drawingvoid COpenGLView::OnDraw(CDC* pDC){ COpenGLDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); // TODO: add draw code for native data here}......// COpenGLView message handlersint COpenGLView::OnCreate(LPCREATESTRUCT lpCreateStruct){ if (CView::OnCreate(lpCreateStruct) -1) return -1; // TODO: Add your specialized creation code here return 0;}void COpenGLView::OnDestroy(){ CView::OnDestroy(); // TODO: Add your message handler code here}void COpenGLView::OnSize(UINT nType, int cx, int cy){ CView::OnSize(nType, cx, cy); // TODO: Add your message handler code here}

Once you have modified the above two files, you can compile and run the program.

If you got errors, you might have forgotten to add the OpenGL code from the lab notes to the OpenGLView.h and OpenGLView.cpp! You will also need the correct shaders, or the program will appear not to start. If you get a warning that says 'GL 3.2 Context not possible', you have a graphics card that doesn't support OpenGL 3.2 Core Profile and you will have to either update your drivers, or try again with a newer card. I suggest any nVidia or AMD card produced in the last couple years.

E. Clean Your Project Before You Submit It

To clean up your project for submission delete all Debug folders in the projectand delete all sdf files. They are rather large (in some cases > 30 MB) andthe .exe file in the Debug folder will be rejected by many spam filteringsystems. Besides, you will get them back the next time you compile yourprogram.

This post walks you through setting up OpenGL, GLEW, and FreeGLUT support in Visual C++ in order to compile the samples properly. My original thought was to put this in an appendix after all of the chapters were completed, but there's need for it now, so here's the extremely verbose step-by-step explanation:

I'm assuming that you have Visual Studio installed or at least Visual C++ Express, which you can get for free right here, and and install the Windows SDK as well if you get the Visual C++ Express version, which you can get here.

Step 1: Get the Libraries

1.) Download the binary version of FreeGLUT from this website, make sure the version you get it 2.6.0 or higher.
2.) Download the latest binary version of GLEW from their site, make sure to download the one labeled Windows 32-bit.

Step 2: Copy the Libraries

Decompress the files you just downloaded and open up the folder for FreeGLUT:

Open up another explorer window, and type %PROGRAMFILES% in the address bar, or %PROGRAMFILES(X86)% only if you're on a 64-bit system. Find the sub folder Microsoft SDKsWindows(highest version):

Copy the contents from FreeGLUT's lib folder into the Windows SDK's Lib folder.
Copy the contents from FreeGLUT's includeGL folder into the Windows SDK's Includegl folder.

Now, in the Explorer window currently pointed to FreeGLUT's location, navigate to the location where you extracted GLEW:

Copy the contents from GLEW's lib folder into the Windows SDK's Lib folder.
Copy the contents from GLEW's includeGL folder into the Windows SDK's Includegl folder.

Step 3: Creating the Project

The next step is to set up the Visual C++ project, so start up Visual C++ Express or Visual Studio and in the menu bar, go to File -> New -> Project..., and click on the Visual C++ heading:

Make sure you have the Win32 Console Application option selected, type in a name for the project, and click on the OK button, and the following screen should appear:

Click on next, but do not click the Finish button until you have checked the Empty Project check-box and your options look exactly like this:

Step 4: Adding a Source File

Now that you have an empty project set up, we need to add a source file, which we'll name main.c for this tutorial. Right-click on the project, navigate to Add and click on New Item...:

From the list, pick the option C++ File (.cpp), and change its Name to main.c (notice the change from .cpp to c):

It's important to have this file in your project before you enter the settings screen since certain settings would not appear on the screen without at least one source file available. After you click the Add button, the new file should show up in your Solution Explorer and open up in the text editor:

Visual Studio Opengl Tutorial

Step 5: Project Settings (Compiler)

Right click on your project in the solution explorer again, and click on Properties in the context menu:

IMPORTANT: Make sure that before setting any settings to set the Configuration drop-down to All Configurations:

The first change we're going to make is in the General property page under the Configuration Properties heading. in the property page, change the Character Set option under Project Defaults to Not Set (see highlighted screenshot):

Next, go to the C/C++ property page, click on the General sub-page and change the Warning Level setting to Level4 (/W4), and the Treat Warnings As Errors setting to Yes (/WX) (see highlighted screenshot):

Next, go to the Preprocessor sub-page, expand the drop-down list next to the Preprocessor Definitions option, and click on Edit.... In the screen that comes up, insert a new line at the top of the options list, and add _CRT_SECURE_NO_WARNINGS so that your list looks like this:

IMPORTANT: Click on the OK button, and go to the Advanced sub-page. Change the Compile As option to Compile as C Code (/TC) (see highlighted screenshot):

Step 6: Project Settings (Linker)

Go to the Linker property page, and click on the Input sub-page. Expand the drop-down list next to the Additional Dependencies option and click on Edit.... In the window, add glew32.lib followed by a newline, and freeglut.lib so that your list looks like this:

Click on the OK button, and when you're back at the settings screen, click on the OK button as well to save your settings.

Step 7: Compiling/Running the Project

Now it's time to test your setup, so grab some source code from one of the chapters (I suggest chapter 1 for simplicity) and paste it into main.c:

Go to the main menu, click on Build, click on Build Solution and your build should succeed without any warnings or errors:

The next step is not to debug, but to copy some extra files into your project's output folder. So open up an explorer window, and point it to the location of your project output, which at this point should be the Debug folder in the solution's root folder. You should see something similar to this:

Visual Studio Code Opengl

Open another Explorer window to the location where you extracted GLEW, and copy glew32.dll from the bin folder into the output folder of your project. Now, navigate the explorer window to the location where you extracted FreeGLUT, and copy freeglut.dll from that folder to the output folder of your project, which should now look like this:

You should now be able to compile, debug, and run your program without warnings and errors:

Vs Code Opengl

Final Thoughts

This is of course one of many ways of setting up a project, but should point you in the right direction.

One thing that I like to do for certain projects is include the DLLs as part of my solution in a Solution Folder, and copy them after a successful build with a custom Post-Build step.

A cleaner way that doesn't require copying the libraries is to compile the libraries yourself and include them in your Solution as a Visual C++ static library project and set your OpenGL projects to depend on the output (build order). It increases the size of your solution, but being able to tweak source code and control what's inside a compiled binary is priceless.

Visual Studio Code Opengl

If you have remarks, questions, or concerns, post them in the comment section below.