Софт-Архив

Opengl 3.2 img-1

Opengl 3.2

Рейтинг: 4.6/5.0 (1877 проголосовавших)

Описание

OpenGL ES 3

ADVERTISEMENT OpenGL ES 3.2

Starting with the new specification, OpenGL ES 3.2 aims to bring another step forward in mobile graphics capabilities and quality by absorbing Google’s Android Extension Pack (AEP) functionality into the core of OpenGL ES..

If you recall, the AEP was announced with the launch of Android 5.0 Lollipop and brought along a selection of graphical technologies to the mobile OS via extensions to OpenGL ES 3.1. The introduction of OpenGL ES 3.2 builds on the previous release to open up new graphics functionality to make full use of future mobile and automotive hardware.

OpenGL ES 3.2 boasts a small number of improvements over last year’s OpenGL ES 3.1. Both make use of similar features from the AEP.

From the AEP, OpenGL ES 3.2 compliant hardware will support Tessellation for additional geometry detail, new geometry shaders, ASTC texture compression for a smaller memory bandwidth footprint, floating point render targets for high accuracy compute processes, and new debugging features for developers. These high-end features are already found in the group’s full OpenGL 4 specification.

High quality graphics effects are also part of the standard, with Deferred Rendering, physically-based shading, HDR tone mapping, and Global Illumination and reflections made available, bring desktop-class graphics to the core of OpenGL ES and mobile devices.

Jargon aside, this essentially allows for better looking mobile titles on supported hardware, including but not limited to the features seen in the impressive looking Rivalry Demo built in Epic’s Unreal Engine 4 (above).

Vulkan – the cross platform API

By reducing driver overheads and improving multi-threaded CPU usage, Vulkan is promising notable performance improvements alongside the latest graphics features. The growth of multi-core mobile SoC designs could lead to notable performance gains in the mobile market.

A load of companies are actively working within the group, and cross platform support will benefit a great deal of the participants, as well as consumers.

The other part of Vulcan development is to offer a single unified API for desktop, mobile, consoles and other embedded applications. Vulkan supports Windows 7, 8 and 10, SteamOS, Android, Samsung’s Tizen spin-off, and a selection of desktop Linux distributions.

The introduction of Vulcan will do away with ES and desktop versions of the API by unifying the two, simplifying cross platform development and opening up new possibilities for developers and gamers alike. The most recent versions of OpenGL ES are pretty much considered a subset of the main OpenGL API now, making cross compatibility much more feasible.

“Hardware and software companies need an open 3D API to maximize market reach and minimize porting costs, and Vulkan is being forged by a broad consortium of industry leaders to do exactly that,” – Neil Trevett, president of the Khronos Group.

Vulkan will support hardware that is compatible with at least the mobile OpenGL ES 3.1 API through to the desktop OpenGL 4.5 specification and higher. However, hardware across these different platforms have different capabilities and API support levels, so we won’t necessarily see complete feature sets shared across all platforms.

Instead, Vulkan defines and implements features at device creation time, and platform profiles can be specified by Khronos and other parties. This will allow developers to target specific platforms using the same API, with features being split up depending on the hardware. For consumers, this will hopefully increase the availability of cross platform titles, as development costs will fall.

Vulkan open source tools

Along with the new graphics features, Khronos is introducing its SPIR-V intermediate language for shading language flexibility. The key SPIR-V tools are open source, which includes translators for GLSL, OpenCL C and C++ and an SPIR-V assembler/disassembler.

The open source Vulkan test suite is leveraging and merging with the Android Open Source Project (AOSP) drawElements Quality Program (dEQP) framework and is designed to allow developers to offers a greater level of feedback and to be able to make contributions to resolve cross-vendor inconsistencies.

In summary, the introduction of OpenGL ES 3.2 and Vulkan will bring performance and graphical improvements to Android gamers, as well as opening the door for new compute solutions for more complex processing tasks. There’s an equally large focus on making cross-platform development less expensive and less time consuming to implemented too, which also trickles down to benefit us customers.

Unfortunately, we are going to have to wait for new mobile hardware before users and developers can make the most of many of these enhancements. The first specifications and implementations of Vulkan are expected later this year.

Другие статьи, обзоры программ, новости

OpenGL 3

OpenGL 3.2

3 августа 2009 года вышла версия 3.2 графической библеотеки OpenGL.

В последнее время у меня складывается ощущение, что после двухгодовой работы над в итоге бездарно сляпоной OpenGL 3.0, у разработчиков попёрло. И вот уже через несколько недель увидела свет версия 3.1 и вот теперь уже 3.2. Видимо разработчики решили, если изменений за месяц столько же, как за два года, почему бы не выкладывать новые версии по-чаще.

На официальном сайте разработчики написали вот что о своей версии

What's New in OpenGL 3.2

OpenGL version 3.2, released on August 3, 2009, is the tenth revision since the original version 1.0. Despite incrementing the major version number (to indicate support for high-level programmable shaders).

OpenGL 3.2 and the companion OpenGL Shading Language 1.50 add many new features, while simultaneously simplifying the API and shading language by removing legacy fixed-functionality interfaces deprecated in OpenGL 3.0. OpenGL 3.2 defines a lean and mean base to build on for access to future programmable graphics hardware.

OpenGL 3.2 adds features for enhanced performance, increased visual quality, accelerated geometry processing and easier portability of Direct3D applications.

OpenGL 3.2 has been designed to run on a wide range of recent GPU silicon and provides a wide range of significant benefits to application developers, including:

•Increased performance for vertex arrays and fence sync objects to avoid idling while waiting for resources shared between the CPU and GPU, or multiple CPU threads;

•Improved pipeline programmability, including geometry shaders in the OpenGL core;

•Boosted cube map visual quality and multisampling rendering flexibility by enabling shaders to directly process texture samples.

API & GLSL specifications

•OpenGL 3.2 Core Profile Specification

•OpenGL 3.2 Compatibility Profile Specification

•OpenGL Shading Language 1.50 Specification

New ARB extensions

•GL_ARB_draw_buffers_blend

•GL_ARB_sample_shading

•GL_ARB_texture_cube_map_array

•GL_ARB_texture_gather

•GL_ARB_texture_query_lod

•WGL_ARB_create_context

•GLX_ARB_create_context

Особенно стоит осмотреть новые расширения. Ещё не читая спецификацию о последних двух, бересь утверждать, что WGL_ARB_create_context и GLX_ARB_create_context используются для создания контекста OGL (посмотрите тему OpenGL 3.1 на этом сайте в этом же разделе, начиная именно с этой версии контекст получается через расширение. Первое с конца видимо для создания дескриптора с тем или иным задействованием сети, а первое для создание в Windows среде (о чём говорит первая буква)).

Стоит так же отметить выход GLSL 1.50! ВЫпьей же, братья, за него [images.yandex.ru].

Теперь что же разработчики написали в переводе:

OpenGL версии 3.2, выпущенна 3 августа, 2009, является десятым релизом после первоначальной версии 1.0. Несмотря на увеличивающиеся основные версии номера (чтобы указать поддержку на высоком уровне программируемых шейдеров).

OpenGL 3.2 и OpenGL Shading Language 1.50 добавили много новых возможностей, и одновременно упростили API и использование шейдеров, удалив наследие фиксированной функциональности интерфейса, используемового в OpenGL 3.0. OpenGL 3.2 определяет новые стандарты, чтобы в будующем эффективно использовать самые современные программируемые графические устройства.

OpenGL 3.2 добавляет функции для усиления эффективности, повышение визуального качества, ускорение обработки геометрии и более лёгкой переносимости Direct3D приложений.

OpenGL 3.2 была разработана для работы при большом количестве различных GPU, которые сочетают в себе разные возможности. Обновлённый стандарт предоставляет широкий спектр важных преимуществ для разработчиков приложений, в том числе:

• Повышение производительности для вершинных массивов и ограждения синхронизации объектов, чтобы избежать холостого хода в ожидании ресурсов распределяется между процессором и GPU, процессоров или несколько нитей;

• Улучшенная программного конвейера. включая геометрические шейдеры в OpenGL ядре;

• улучшение cube map визуальново качества и гибкости multisampling рендеринга, позволяя шейдерам непосредственно процесс texture samples.

Правка: 5 авг. 2009 7:23

OpenGL 3

OpenGL 3.2 released

The Khronos Group, the industry consortium responsible for the care and feeding of the OpenGL graphics standard, on Monday announced the release of OpenGL 3.2.

The new release adds features to improve performance, quality, accelerated geometry processing and easier portability of applications originally made using Direct3D, the opposing standard included in Windows as part of Microsoft’s DirectX API suite.

OpenGL 3.2 is billed as the third major update to OpenGL in the the past year. In the past, the industry group has been criticized for being slow to react to changes within the graphics industry, particularly compared to Microsoft’s rapid evolution of Direct3D.

The OpenGL Architecture Review Board (ARB) working group at Khronos has also defined an updated version of the OpenGL Shading Language (GLSL 1.5) and two profiles within OpenGL 3.2 for new application development — a streamlined Core profile and a Compatibility profile that provides full backwards compatibility with previous OpenGL versions.

Currently, Mac OS X 10.5 “Leopard” uses the older, more limited OpenGL 2.1 standard, though it’s expected that Mac OS X 10.6 “Snow Leopard,” which comes out in September, will use OpenGL 3.x. OpenGL 3.x supports OpenCL, or Open Computing Language, a framework that lets applications leverage graphics processor technology for faster parallel computing capabilities.

With the new release of OpenGL emerging today, it’ll be up to individual vendors to incorporate the changes and improvements into their own software drivers and hardware in the coming months. Nvidia has already produced beta Windows drivers based on the OpenGL 3.2 spec. Of course, it’s up to Apple to incorporate OpenGL 3.2 changes in its operating system — chances are that such a move is a way off, however.

OpenNews: Вышел финальный вариант спецификации OpenGL 3

04.08.2009 18:00 Вышел финальный вариант спецификации OpenGL 3.2. Планы, касающиеся WebGL

Организация Khronos group представила финальный вариант спецификации OpenGL 3.2 и языка описания шейдеров GLSL 1.5. В новой версии отмечено увеличение производительности, улучшение качества визуализации, добавлены средства для упрощения портирования Direct3D приложений и поддержка акселерации геометрических преобразований.

В GLSL 1.5 представлено два новых профиля: Core profile - для разработки новых приложений и Compatibility profile - для обеспечения обратной совместимости с прошлыми версиями спецификации OpenGL. Кроме того, в состав спецификации включено описание 5 новых наборов ARB (Architecture Review Board) расширений, которые позволяют задействовать возможности новейших GPU. По предварительным оценкам, число GPU, совместимых с OpenGL 3.2, превышает 150 миллионов.

Дополнительно организация Khronos group опубликовала информационное сообщение о развитии WebGL, стандарта для манипулирования 3D графикой в Web-приложениях в рамках которого формируется API, обеспечивающий доступ JavaScript скриптов к базовым функциям OpenGL. Первый публичный выпуск спецификации намечен на первую половину 2010 года. В настоящий момент определен специальный JavaScript биндинг к OpenGL ES 2.0 для создания 3D web-приложений, для работы которых не требуется установка дополнительных плагинов в браузере. WebGL основан на использовании HTML5 элемента Canvas, который поддерживается в браузерах Google Chrome, Firefox и Opera.

OpenGL 3

OpenGL 3.2

Регистрация: 24.06.2008 Сообщения: 254 Одобрения: 61 Репутация: 1

Компания Khronos Group сообщила, что она подготовила OpenGL 3.2 - уже третье за год обновление для широко распространенного API для 2D и 3D графики для ПК и рабочих станций. Новая версия продолжает эволюцию стандарта OpenGL, который облегчает для разработчиков графических решений доступ к функциональности GPU под управлением разных операционных систем и на разных платформах. Полную спецификацию OpenGL 3.2 можно скачать на официальном сайте проекта.

Новый функционал OpenGL 3.2 позволит увеличить производительность, улучшить качество визуализации, ускорить обработку геометрии и повысить переносимость приложений Direct3D. В дополнение к этому дальнейшее развитие как OpenGL, так и других стандартов, над которыми работает Khronos, включая OpenCL для параллельных вычислений, OpenGL ES для мобильной трёхмерной графики и новый стандарт для трёхмерной Интернет-графики WebGL - всё это направлено на создание мощной графической и компьютерной экосистемы, покрывающей множество приложений, рынков и устройств. А на данный момент, по словам компании, парк установленных GPU, совместимых с OpenGL 3.2, превышает 150 миллионов единиц.

В OpenGL 3.2 имеется масса преимуществ для разработчиков приложений, среди которых:

Увеличена производительность для массивов вершин и объектов с синхронизацией поверхности, что позволяет избежать простоя во время ожидания свободных ресурсов, разделённых между CPU и GPU, или между несколькими потоками CPU

Улучшена программируемость конвейеров, включая шейдеры геометрии OpenGL

Увеличено визуальное качество кубических карт (cube map) и гибкость рендеринга методом множественной выборки путём разрешения шейдерам напрямую взаимодействовать с образцами текстур.

Более подробно обо всех усовершенствованиях можно прочитать в официальной спецификации (2,4 Мб) этого стандарта.

В последний раз редактировалось: 11.08.2009

Opengl 3.2

Utility library for "Interactive Computer Graphics - 6th Edition" Description

The book "Interactive Computer Graphics - 6th Edition" by Edward Angel and Dave Shreiner uses a small simple library called "Angel" ( http://www.cs.unm.edu/

angel/BOOK/INTERACTIVE_COMPUTER_GRAPHICS/SIXTH_EDITION/CODE/ " ). This library add some utility functions to this library for some common tasks in OpenGL 3.x. This includes:

  • Wavefront .obj model loader
  • BMP image loader
  • Select buffer (useful for selecting objects in a scene).

Most of these extensions depends on the "Angel.h", however it should be easy to update the code to use other libraries (such as GLM http://glm.g-truc.net/ ) instead.

New BSD License

Copyright (c) 2011, Morten Nobel-Joergensen All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  • Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  • Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

OpenGL 3

OpenGL 3.2 specification released

Posted Monday, 3 August, 2009 - 19:26 by the Fiddler

opengl.org wrote:

The Khronos™ Group, today announced OpenGL® 3.2, the third major update in twelve months to the most widely adopted 2D and 3D graphics API (application programming interface) for personal computers and workstations.

The OpenGL ARB (Architecture Review Board) working group at Khronos has defined GLSL 1.5, an updated version of the OpenGL Shading language, and two profiles within the OpenGL 3.2 specification providing developers the choice of using the streamlined Core profile for new application development or the Compatibility profile which provides full backwards compatibility with previous versions of the OpenGL standard for existing and workstation applications.

OpenGL 3.2 has been designed to run on a wide range of recent GPU silicon and provides a wide range of significant benefits to application developers, including:

  • Increased performance for vertex arrays and fence sync objects to avoid idling while waiting for resources shared between the CPU and GPU, or multiple CPU threads;
  • Improved pipeline programmability, including geometry shaders in the OpenGL core;
  • Boosted cube map visual quality and multisampling rendering flexibility by enabling shaders to directly process texture samples.

In addition, Khronos has defined a set of five new ARB extensions that enable the very latest graphics functionality introduced in the newest GPUs to be accessed through OpenGL – these extensions will be absorbed into the core of a future version of OpenGL when this functionality is proven and widely adopted.

Read the full announcement on opengl.org. The specification is already available for download - expect a new OpenTK release soon.

Opengl 3.2

Introduction

OpenGL has undergone some major changes recently from version 3 and onwards. OpenGL 3 introduced a new way of programming in OpenGL that slightly raises the learning curve, but also does away with the entire Immediate Mode by deprecating a lot of the functions. Now I know I have called this part of the site “OpenGL 4 Tutorials”, and all of a sudden I am talking about OpenGL 3, this is because OpenGL 3 and OpenGL 4 are extremely similar, with OpenGL 4 bringing in some new extensions, and because my graphics card only supports OpenGL 3.x. If you would like to see some OpenGL 4 extensions in use, you can always donate and help me get a new graphics card. In this tutorial, I am going to be simply creating a window with an OpenGL 3.2 context attached, nothing more, nothing less. These tutorials are going to be for Windows only, but if you are keen to get them working on a different OS (My Macbook doesn’t support OpenGL 3.x), please send me the ports and I will post them up.

OpenGL 3+ Key Differences

An OpenGL 3+ and 4 context requires you to create a standard OpenGL context (version 1.x or 2.x) and then get your application to opt-in to using an OpenGL 4 context.

Without the Immediate Mode, OpenGL has gone for an almost entirely shader driven architecture, which gives us control over everything from the word go, and also greatly improves performance.

When it comes to rendering shapes, instead of setting the state and then calling the vertices one by one, OpenGL 3 and upwards wants us to use Vertex Buffer Objects and Vertex Buffer Arrays straight out. Vertex Buffer Objects were available in OpenGL 1.5 and up as an extension, but they are now a part of the core of OpenGL.

Matrices are one of the major things affected by OpenGL 3. To put it simply, OpenGL does no matrix operations for us such as setting the Projection Matrix, setting the Model Matrix and setting the View Matrix. This means calls such as glRotate and glTranslate are now deprecated and not recommended. OpenGL now likes us to handle our own matrices. I will talk about this in a later tutorial, but there is a library called GLM, designed for use with OpenGL and GLSL, which will help us with our matrix operations.

*note* You can jump straight to the bottom of this page to grab the PDF version of this tutorial, or the project files. *note*

Let’s finally get into this tutorial, because it is going to be a long one. I’m also going to be aiming for a more Object Oriented approach to programming in these newer tutorials.

This tutorial is going to be very similar in some ways to most Win32 OpenGL tutorials available, the only difference being that it has an OpenGL 3.2 context instead of a standard context. So open up Visual Studio and create a new Windows Console Application in C++. Make sure it is empty to begin with, and then create 4 files. I am calling them: “main.cpp, main.h, opengl_3.cpp, opengl_3.h”. I am going to go through these files one by one, starting with the header files, so that we don’t get mixed up shuffling between them.

Main.h is going to contain all of our header files for the time being. So open it up and paste the following code. I won’t explain it, as it is pretty straight forward; we are including some header files and linking some libraries, the only tricky part may be “#pragma once”, which isn’t standard but is widely supported, and means to only include the file once during compilation.

As you can see from the above code, we are once again using GLEW. GLEW is up to date with the latest OpenGL 3.x and possibly 4.0 extensions. I highly recommend the use of it as it makes coding in OpenGL so much easier without having to worry about declaring extensions by yourself.

Opengl_3.h

The first thing we want to include here is our main.h file. So add the line:

Once we have included our main header file which contains access to the GLEW and OpenGL commands, we are going to want to create a new class. I am going to call this class OpenGLContext and it is going to be responsible for creating a context, handling setting up of our scene, resizing of our scene, rendering of our scene, and finally, cleaning up of our scene. Start off with an empty class like so:

Next up, we are going to come up with some protected variables that will keep track of our window. When working with the Win32 API, each Window you see has its own HWND which is the identifier for that window. We also have two different contexts we need to work with, the first is the HDC, which is the device context, and the second is the HGLRC which is an OpenGL rendering context. If we create a variable to handle each of these, we get:

Once we have the information we need for a window and a context, we need to keep track of the width and the height of our window. If we don’t keep track of these, then whenever we resize the window, we will find that parts of it are not rendered to, or we render more than we have to, resulting in some of our image being cut off. We are going to add two private variables to keep track of this for us:

Finally we need to come up with some method stubs for controlling our OpenGLContext object. I am going to work with two different constructors and a destructor for some standard methods. Followed by four other methods for working with our context which are going to be called “create30Context(HWND), setupScene(void), reshapeWindow(int, int), renderScene(void)”.

This is all we are going to need for our opengl_3.h header file for now. So let’s go and start on opengl_3.cpp.

Opengl_3.cpp

To give use access to our class methods, you are going to want to include opengl_3.h of course, so that will be line number one for this file.

Now let’s get to building us some methods for our class. I am going to start off with the two constructors and the destructor. Our first constructor, the default one, at the moment does nothing, so you can just create an empty constructor. But the second one will make a call to our create30Context method.

When we get to our destructor, it will handle the removal of our rendering context and our device context. For this, we make use of wglMakeCurrent, wglDeleteContext and ReleaseDC.

Let’s get onto our create30Context method now. This method will take in a HWND value to identify a window, and will create a valid rendering and device context on top of it. Create an empty method for this, and then we will set the HWND for our object, and get a valid HDC. I’ve made this method a Boolean value, so we can return a false value if we are unable to successfully create a context of any kind. However by default, we will fall back to and OpenGL 2.1 context if unable to create an OpenGL 3.x context.

The next thing we need to do, is create a variable called a PIXELFORMATDESCRIPTOR which determines how many bits of colour and depth we get, along with giving us double buffering and support for OpenGL. To do this, we first need to create a new variable, I am going to call it pfd and then we need to allocate some empty memory for it. Here, 32 bits of colour, gives us R, G, B and A channels, while 24 bits gives us only R, G and B (each channel takes 8 bits). After we have set aside some memory for this variable, we need to set the size of it, which will always be sizeof(PIXELFORMATDESCRIPTOR). Next, we will set the flags which allow double buffering, opengl support and drawing to a window. Next up, we set the iPixelType to allow RGBA pixels, before we set how many bits we want in our color and depth buffers. Finally, we need to set the iLayerType. We are going to set this to the Main_Plane for our window.

Next up, we need to choose a pixel format for our device context, based on our pixel format descriptor. To do this, we make a call to ChoosePixelFormat and pass through our hdc and pfd variables, in return we get an integer value that represents our pixel format, which we can then use to set our pixel format for our device context using SetPixelFormat as seen below.

Once we have our pixel format all set up. We need to go ahead and create our OpenGL context. To do this, we need to first create an OpenGL 2.1 compatible context, and then call a new OpenGL 3.x extension called wglCreateContextAttribsARB to create an OpenGL 3.x compatible context. So let’s create our OpenGL 2.1 context as per a standard Win32 OpenGL application.

To create our context correctly, we need to set some attributes. These include the major and minor version of the OpenGL version we wish to use, followed by a flag to set this as a forward compatible context. When I say major and minor version, OpenGL versions come in this naming convention “major.minor”, so in OpenGL 3.2, the major version is 3 and the minor version is 2. This can be change to give OpenGL 3.2, 3.1, 3.0 or even 4.0 contexts.

Now that our attributes are all sorted out, we are going to do a check to see if our OpenGL 3.x context creation extension is available. If it is, we are going to create our OpenGL 3.2 context, if it isn’t, then we are going to stick with the OpenGL 2.1 context we created above. To switch to the new context after it has been created, we need to make sure that no context is current on our window, and then delete the old context, before finally making our new OpenGl 3.2 context current.

Finally, to check that we have created our context correctly, we are just going to pull out the MAJOR and MINOR version numbers for OpenGL and output them to a console.

This will run your application, and save all output to the file temp.txt. Linux programmers may already be familiar with calls like this.

Now we still have three more methods we need to create here before we are done, but luckily for us, they are extremely short. The first I will look at is setupScene, which takes no parameters, and will only set up our OpenGL Clear Color value. I am going to set it to the nice CornFlowerBlue you get when working with XNA. I grew fond of this colour, and it looks nicer than a standard black or white.

Moving on, we now have our reshapeWindow method. This method will take in two integers, one for the width of our window and the other for the height of our window. It will then set our OpenGLContext objects width and height to these values.

And the last method for this file, is our renderScene method, which once again takes no arguments. The first thing we need to do, is set the size of our viewport to the size of our window, which is done with a call to glViewport. Next we will clear our color, depth and stencil buffers, before finally swapping our front and back buffers to draw to the screen.

Now we have everything in place for our basic OpenGL 3.2 context, so let’s go and finish off this tutorial with the main.cpp file, which will handle all of our Window creation.

For the purpose of these tutorials, I am going to assume that we are working with single window applications and am not going to go for a more OO approach to window creation. So let’s get on to creating our window.

The first thing we need to do here is to include our common header files, main.h and opengl_3.h. Followed by declaring some variables. We are going to need an instance of an OpenGLContext object, a boolean value to say as to whether or not we are still running our application and a standard HINSTANCE variable for Win32. We are also going to give a method declaration for WndProc which is also required for a Windows application.

The rest of this tutorial, is made up of three methods. The first one here, is required in any Windows application and is responsible for our windows callbacks. We are going to look for calls to resize the window, and for calls to destroy the window. When we find a call to resize the window, we are going to call our openglContext.reshapeWindow method. Lets take a look at the definition for this method.

In order to look for different window calls, we turn to the message parameter in the method definition. This is a UINT variable, which can be tied to any of the WM_* variables. We are going to need WM_SIZE for window resizing, and WM_DESTROY for calls to destroy the window. I am going to use a simple switch statement to check for these like so:

When it comes to our window resizing, we are going to need to update our OpenGL context so that it knows the new size of the window. To do this, we can pull out the width and height of the window using calls to LOWORD(lParam) and HIWORD(lParam), which makes things fairly simple for us. Our method now becomes:

The only thing left to check for now, is when a window is destroyed. Then we need to send a call to PostQuitMessage so that we can exit our application.

While we now have a method which will handle all of the call backs for our window, we need to actually go ahead and create a window. So I am going to create a new method called createWindow, which will return a boolean value which determines whether or not the window was created successfully. It’s parameters are an LPCWSTR for the title of the window, and two integers, one for the width and one for the height of the window.

Once we have our method skeleton in place, we need to setup some variables for our window. We will need a WNDCLASS, HWND and a DWORD. The WNDCLASS, which I will call windowClass sets all the basic information for a window, such as the icon, cursor, type of redraw, the instance of the owner application, etc. The HWND variable which I will just call hwnd, will hold the unique identifier for the window which we create, and finally the DWORD variable, which I am going to call dwExStyle and that just sets the type of window and that it has an edge.

I’m not going to go into detail about all the settings for this, as it’s not an OpenGL topic, its a Win32 topic, so here’s just the code. I have included a quick error check to make sure the windowClass variable can be registered:

Next up, we are going to create our window using the above window class, and then we are going to create our OpenGL context on the window before showing the window and making a quick call to update it.

This should now give us a window, with an OpenGL 3 context, and it should also be visible. The last thing we need to do is create a WinMain method which will be used to launch our application. Lets create an empty WinMain method, and then we will go ahead and fill this in. Note that I have left in the MSG variable called msg, just because we use it for our return value.

Before we fill this in, I am going to give a brief rundown of what to expect. The first few lines are going to be used to convert the title of the window from a char array to an LPCWSTR, they are just an annoying necessity because the CreateWindowEx method doesn’t support char arrays. The next two lines after this will create our window, and setup our OpenGL context, and we will end with a loop that will continue running for as long as the application does, and will be responsible for rendering and checking for window messages. Lets take a look at the first few lines, which convert our char array.

Now let’s make the calls to create our window and setup our OpenGL scene.

And finally we can set up our infinite loop. We will use the Win32 call to PeekMessage to check for calls to our window. If we get a WM_QUIT message we are going to set our running variable to false. Otherwise we are going to translate and dispatch the message, which is done in our callback. And if we don’t have any messages to process, we are going to call our openglContext.renderScene method before returning.

And wow, if you made it this far, give yourself a well deserved pat on the back! It took me a few days to write this tutorial, which is an initial setup on top of which all our other tutorials will build, so once you get it down you are ready to move onto the next. I am also providing Visual Studio 2010 projects for these tutorials, and PDF versions for download. For those of you who have been waiting, I’m sorry it has taken so long, but this is now a 13 page, 4,500+ word introduction to setting up an OpenGL compatible context on a window.