A Simple C++ OpenGL Shader Loader – Improved

I wrote one back in 2013, but I’ve learnt some things since then, so I’ve re-written it all with some changes. You can still load/compile shaders from strings or files, and then link/validate/use the resulting shader programs, only this time its all a little bit cleaner and more robust.

The main deficiencies of the previous incarnation were:

  • The Shader class wasn’t required for what I was using this stuff for, so I stripped it out – now you just create a ShaderProgram directly,
  • Error logs weren’t shown for any shader or shader program errors,
  • The shader program didn’t get validated,
  • Abuse of exit(-1) rather than throwing unchecked runtime_errors,
  • Inclusion of using clauses in headers, and
  • Possible wonky static declaration and initialisation of const_iterator error in uniform location getter meant that it might have only “got” the uniform location correcty on first run, when the const_iterator was declared – but in practice I haven’t seen any issues, perhaps because I spotted and fixed it but forgot to update article though…

Anyway, below is an improved version that fixes all of the above – here’s how you use it…

Usage

ShaderProgram Class Source Code

Here’s the code for the class itself:

Note: I’m not convinced that the compiler will even consider inlining the use() and disable() methods when the program is built as a hpp – I think I’d have to break it into .h and .cpp files for that… other than that I’m thinking the above code is pretty clean, robust and usable.

GLFW3 Basecode with FPS Camera Controls

Basecode is funny thing – when you start a new project, do you really start from scratch? A complete blank slate? Or do you make a copy of the last project you worked on which is similar and modify it? Often, you’re going to want to start from some pre-existing functional base, but what’s stable and functional enough? Do you really want to go with a framework like Cinder or Processing to hold your code? Or go with a full-on engine like Unity or Unreal Engine 4 or some other engine?

I’m going to write a game at some point in the future, and I want to go it (almost) alone – I don’t want to be locked into someone elses constructs and patterns, or drag-and-drop functionality in which I have absolutely no idea how it works – I want to think for myself and create what’s basically my own engine, where I understand how it fits together and how each piece works. This doesn’t necessarily mean that everything needs to be worked out from first principles, but it should be possible to make all the important architectural decisions. This means that I want precise control over:

  • At least one OpenGL window, with controllable context details (preferably multiple windows with a shared projection)
  • Painless keyboard and mouse handlers
  • File handling of common types (load and use this 3D model/sound file/settings file)
  • Help with prototyping via simple drawing calls

Which brings us back to basecode being a funny thing – you get to make the architectural decisions, and live with the consequences. If you decide to go with an engine, then you’re going to learn the engine – not the fundamental technologies or aspects of the code that make the engine work. So if you grab some fantastic engine and you go:

  1. Load this spaceship model, which is made of these different materials,
  2. There’s a light which is at (1000, 200, 300) in world space (and perhaps a dozen other lights),
  3. Draw the spaceship from my (i.e the camera’s) location.

But what does that actually teach you, as a developer? How do you load the model from file? How is the lighting model applied to the vertices? Where the hell is the spaceship in relation to you, let alone the surface normals of the spaceship with regard to the light-source(s) with regard to the camera? In an engine, you don’t care – you let the engine work it out for you, and you learn nothing. Or maybe you learn the engine – which means you learn to trust someone else to think instead of you having to think for yourself.

Which finally brings us back to basecode being a funny thing… I’ve been thinking about this for weeks, and below is the OpenGL/GLFW3 basecode I’ve written to open a window, draw some grids for orientation, and allow for ‘FPS-esque’ mouse and keyboard controls. The main.cpp is listed below, which shows you how the program itself runs – everything else you’ll need to look at for yourself – but I promise you this:

  • Every single piece of this code is clear in its use and serves a purpose.
  • Every single piece of this code performs its job in the simplest, most straight forward manner possible. If the option is to be clever or readable, then I pick readable every time. Saying that, I think I used an inline if-statement once i.e. “if (raining) ? putUpUmbrella() : keepUmbrellaDown();”. Honestly, when you see it, you’ll be okay.
  • Every single piece of this code is documented to explain not only WHAT the code is doing, but (where appropriate) WHY it is doing it. When I used to work as as Subsystem Integration and Test engineer, we would write software build instructions with the goal that your Mum should be able to build the software image from the simple, accurate, non-ambiguous instructions. If you didn’t think your Mum could build it, then you re-worked the instructions until you thought that she could.

I’ll add some additional utility classes to this over time, but for now, this basecode will get a window with FPS controls up and running and display some grids via shaders for orientation – and everything should be simple, straight-forward and clear. Enjoy!

Code::Blocks projects for both Windows and Linux (libraries included for Windows) can be found here: GLFW3_Basecode_Nov_2014.7z.

Update – Feb 2015: There were issues using this code in Visual Studio 2010 as it doesn’t support strongly typed enums or the R” notation (although VS2012 onwards does), and the libraries packaged were the Code::Blocks versions (which was intended – the above version is specifically for Code::Blocks) – so here’s a modified & fully working Visual Studio 2010 version: GLFW3-Basecode-VS2010.7z.

How To: Load an OpenGL Texture using the FreeImage library (or FreeImagePlus, technically)

I’d been using DevIL (or OpenIL if you prefer) as my image loader library, only it hasn’t been updated in a long time and can be a pain to build properly, so I’ve needed to move onto something else. The DevIL fork, ResIL, isn’t quite ready for prime-time and my attempts to build it have resulted in wasted hours and failure (I’ve fixed multiple build errors on the way – but then I hit stuff I can’t see how to fix without trying to re-package the entire thing).

So, new image library, huh? I had a google and saw the FreeImage library (and it’s FreeImagePlus version for C++ – documentation for which can be found here) – and it just happens to be in the Arch community repos so a quick sudo pacman -S freeimage later and we’re ready to rock… Only it didn’t come with any examples, so I dug around on forums and found some code that just about worked, but I wasn’t a big fan of it – so I thought I’d rewrite it into a nicer, more robust method – and I think I’ve achieved just that.

A textured quad at an angle.

The loadTexture Method

Usage

To use the method, just set up your code something like this – in your main .cpp file at the top have:

In your initialisation/setup method add something like this:

In your main method, once you’ve create an OpenGL context (i.e. window) and called your initialise/setup method, then you can load a texture to use like this:

Finally, on shutdown you may (optionally, as long as you’re not using the Linux/Mac .a version of the library) like to add the following:

Wrap-up

Not a great deal to say – it works, it should be relatively robust, it doesn’t leak memory (or at least none that we control), and the code is commented to the hilt and explains why it’s doing things instead of just what it’s doing (some people don’t like verbose code like this – but I teach a lot of programming so I just try to explain everything as clearly as possible as I go – and find I prefer it to ‘terse’ code that I have no idea WTF it’s up to or why it’s bothering).

Many thanks to the FreeImage devs for the library – it’s rather feature-packed and I quite like it (some good example code wouldn’t go amiss though!) =D

Hope you find the code useful! (Bugs? Comments? Suggestions? Feedback always welcome!).

Bitwise Operators in C++

I’ve been perfectly happy with logical operators since I started programming a long, long time ago. That is, your standard AND (&&), OR (||) and NOT (!) operators perform the relevant logical operations so you can say:

or,

or,

But… my understanding of bitwise operators was sketchier. So let’s take a look at the bitwise operators and give them a runthrough to see what they do.

Bitwise Operator List

Let’s start by listing the available bitwise operators:

Bitwise Operator Symbol
& Bitwise AND
| Bitwise Inclusive OR
^ Bitwise Exclusive OR
~ Bitwise NOT
<< Bitwise Left-shift
>> Bitwise Right-shift

So we have 6 basic operators, but we also have the compound versions of these operators, so instead of saying:

We can say:

And they’ll mean the exact same thing – just for completeness, let’s throw those in a table as well:

Bitwise Operator Symbol
&= Bitwise Compound AND
|= Bitwise Compound Inclusive OR
^= Bitwise Compound Exclusive OR
~= Bitwise Compound NOT
<<= Bitwise Compound Left-shift
>>= Bitwise Compound Right-shift

So now that we have these operators, let’s see what we can do with them…

Continue reading Bitwise Operators in C++

The This Pointer in C++

Still on my fundamentals trip, I’m hitting up the ‘this’ pointer. Every class that you create has a ‘this’ pointer invisibly assigned to it by the compiler. Let’s look at a simple class to see what’s going on:

When you write the above code the compiler does some fun things with it, such as invisibly adding four methods:

  • A default constructor (that takes no parameters) which is automatically executed when you instantiate an object of this type,
  • A destructor (again no parameters) which is automatically executed when an object of this type is deleted or goes out of scope,
  • A copy constructor (that takes another object of this type) and performs a shallow copy from the source object to the (new) destination object, and
  • An assignment operator (that takes another object of this type) and which again performs a shallow copy from that object the the object you’re assigning to.

If we explicitly write these four methods into our class, we end up with our (exactly, exactly equivalent) code now being:

You can substitute either of these classes into a project, compile it (in Release mode if you have both in there and just comment each out in turn!), and you’ll end up with byte-wise identical executables down to the very last bit. Not only are they functionally equivalent, they’re absolutely equivalent – as the compiler sees them, it’s the exact same code. Don’t take my word for it – try it out, if you’d like!

The ‘this’ pointer’s already being used, but what exactly is it doing? Well, let’s drill down into the nuts and bolts of it and take a look…

Continue reading The This Pointer in C++