3D C/C++ tutorials - OpenGL 3.3 - OpenGL 3.3 tutorials Win32 framework
3D C/C++ tutorials -> OpenGL 3.3 -> OpenGL 3.3 tutorials Win32 framework
Use for personal or educational purposes only. Commercial and other profit uses strictly prohibited. Exploitation of content on a website or in a publication prohibited.
To compile and run these tutorials some or all of these libraries are required: FreeImage 3.16.0, GLEW 1.11.0, GLUT 3.7.6 / GLUT for Dev-C++, GLM 0.9.5.4
header.h
// ----------------------------------------------------------------------------------------------------------------------------
//
// Version 1.09b
//
// ----------------------------------------------------------------------------------------------------------------------------

#include <windows.h>

#include "glmath.h"
#include "string.h"

#include <gl/glew.h> // http://glew.sourceforge.net/
#include <gl/wglew.h>

#include <FreeImage.h> // http://freeimage.sourceforge.net/

// ----------------------------------------------------------------------------------------------------------------------------

#pragma comment(lib, "opengl32.lib")
#pragma comment(lib, "glu32.lib")
#pragma comment(lib, "glew32.lib")
#pragma comment(lib, "FreeImage.lib")

// ----------------------------------------------------------------------------------------------------------------------------

extern CString ModuleDirectory, ErrorLog;
buffer.h
#include "header.h"

// ----------------------------------------------------------------------------------------------------------------------------

#define BUFFER_SIZE_INCREMENT 1048576

// ----------------------------------------------------------------------------------------------------------------------------

class CBuffer
{
private:
    BYTE *Buffer;
    int BufferSize, Position;

public:
    CBuffer();
    ~CBuffer();

    void AddData(void *Data, int DataSize);
    void Empty();
    void FreeUnusedMemory();
    BYTE *GetData();
    int GetDataSize();

private:
    void SetDefaults();
};
buffer.cpp
#include "buffer.h"

// ----------------------------------------------------------------------------------------------------------------------------

CBuffer::CBuffer()
{
    SetDefaults();
}

CBuffer::~CBuffer()
{
    Empty();
}

void CBuffer::AddData(void *Data, int DataSize)
{
    int Remaining = BufferSize - Position;

    if(DataSize > Remaining)
    {
        BYTE *OldBuffer = Buffer;
        int OldBufferSize = BufferSize;

        int Needed = DataSize - Remaining;

        BufferSize += Needed > BUFFER_SIZE_INCREMENT ? Needed : BUFFER_SIZE_INCREMENT;

        Buffer = new BYTE[BufferSize];

        memcpy(Buffer, OldBuffer, OldBufferSize);

        delete [] OldBuffer;
    }

    memcpy(Buffer + Position, Data, DataSize);

    Position += DataSize;
}

void CBuffer::Empty()
{
    delete [] Buffer;

    SetDefaults();
}

void CBuffer::FreeUnusedMemory()
{
    BYTE *OldBuffer = Buffer;

    BufferSize = Position;

    Buffer = new BYTE[BufferSize];

    memcpy(Buffer, OldBuffer, BufferSize);

    delete [] OldBuffer;
}

BYTE *CBuffer::GetData()
{
    return Buffer;
}

int CBuffer::GetDataSize()
{
    return Position;
}

void CBuffer::SetDefaults()
{
    Buffer = NULL;

    BufferSize = 0;
    Position = 0;
}
texture.h
#include "buffer.h"

// ----------------------------------------------------------------------------------------------------------------------------

extern int gl_max_texture_size, gl_max_texture_max_anisotropy_ext;

// ----------------------------------------------------------------------------------------------------------------------------

class CTexture
{
private:
    GLuint Texture;

public:
    CTexture();
    ~CTexture();

    operator GLuint ();

    bool LoadTexture2D(char *FileName);
    bool LoadTextureCubeMap(char **FileNames);
    void Destroy();

private:
    FIBITMAP *GetBitmap(char *FileName, int &Width, int &Height, int &BPP);
};
texture.cpp
#include "texture.h"

// ----------------------------------------------------------------------------------------------------------------------------

int gl_max_texture_size = 0, gl_max_texture_max_anisotropy_ext = 0;

// ----------------------------------------------------------------------------------------------------------------------------

CTexture::CTexture()
{
    Texture = 0;
}

CTexture::~CTexture()
{
}

CTexture::operator GLuint ()
{
    return Texture;
}

bool CTexture::LoadTexture2D(char *FileName)
{
    CString DirectoryFileName = ModuleDirectory + "Textures\\" + FileName;

    int Width, Height, BPP;

    FIBITMAP *dib = GetBitmap(DirectoryFileName, Width, Height, BPP);

    if(dib == NULL)
    {
        ErrorLog.Append("Error loading texture " + DirectoryFileName + "!\r\n");
        return false;
    }

    GLenum Format = 0;

    if(BPP == 32) Format = GL_BGRA;
    if(BPP == 24) Format = GL_BGR;

    if(Format == 0)
    {
        ErrorLog.Append("Unsupported texture format (%s)!\r\n", FileName);
        FreeImage_Unload(dib);
        return false;
    }

    Destroy();

    glGenTextures(1, &Texture);

    glBindTexture(GL_TEXTURE_2D, Texture);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

    if(GLEW_EXT_texture_filter_anisotropic)
    {
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, gl_max_texture_max_anisotropy_ext);
    }

    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, Width, Height, 0, Format, GL_UNSIGNED_BYTE, FreeImage_GetBits(dib));

    glGenerateMipmap(GL_TEXTURE_2D);

    glBindTexture(GL_TEXTURE_2D, 0);

    FreeImage_Unload(dib);

    return true;
}

bool CTexture::LoadTextureCubeMap(char **FileNames)
{
    int Width, Height, BPP;

    FIBITMAP *dib[6];

    bool Error = false;
    
    for(int i = 0; i < 6; i++)
    {
        CString DirectoryFileName = ModuleDirectory + "Textures\\" + FileNames[i];

        dib[i] = GetBitmap(DirectoryFileName, Width, Height, BPP);

        if(dib[i] == NULL)
        {
            ErrorLog.Append("Error loading texture " + DirectoryFileName + "!\r\n");
            Error = true;
        }
    }

    if(Error)
    {
        for(int i = 0; i < 6; i++)
        {
            FreeImage_Unload(dib[i]);
        }

        return false;
    }

    GLenum Format = 0;
    
    if(BPP == 32) Format = GL_BGRA;
    if(BPP == 24) Format = GL_BGR;

    if(Format == 0)
    {
        ErrorLog.Append("Unsupported texture format (%s)!\r\n", FileNames[5]);

        for(int i = 0; i < 6; i++)
        {
            FreeImage_Unload(dib[i]);
        }

        return false;
    }

    Destroy();

    glGenTextures(1, &Texture);

    glBindTexture(GL_TEXTURE_CUBE_MAP, Texture);

    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

    if(GLEW_EXT_texture_filter_anisotropic)
    {
        glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAX_ANISOTROPY_EXT, gl_max_texture_max_anisotropy_ext);
    }

    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

    for(int i = 0; i < 6; i++)
    {
        glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGBA8, Width, Height, 0, Format, GL_UNSIGNED_BYTE, FreeImage_GetBits(dib[i]));
    }

    glGenerateMipmap(GL_TEXTURE_CUBE_MAP);

    glBindTexture(GL_TEXTURE_CUBE_MAP, 0);

    for(int i = 0; i < 6; i++)
    {
        FreeImage_Unload(dib[i]);
    }

    return true;
}

void CTexture::Destroy()
{
    glDeleteTextures(1, &Texture);
    Texture = 0;
}

FIBITMAP *CTexture::GetBitmap(char *FileName, int &Width, int &Height, int &BPP)
{
    FREE_IMAGE_FORMAT fif = FreeImage_GetFileType(FileName);

    if(fif == FIF_UNKNOWN)
    {
        fif = FreeImage_GetFIFFromFilename(FileName);
    }

    if(fif == FIF_UNKNOWN)
    {
        return NULL;
    }

    FIBITMAP *dib = NULL;

    if(FreeImage_FIFSupportsReading(fif))
    {
        dib = FreeImage_Load(fif, FileName);
    }

    if(dib != NULL)
    {
        int OriginalWidth = FreeImage_GetWidth(dib);
        int OriginalHeight = FreeImage_GetHeight(dib);

        Width = OriginalWidth;
        Height = OriginalHeight;

        if(Width == 0 || Height == 0)
        {
            FreeImage_Unload(dib);
            return NULL;
        }

        BPP = FreeImage_GetBPP(dib);

        if(Width > gl_max_texture_size) Width = gl_max_texture_size;
        if(Height > gl_max_texture_size) Height = gl_max_texture_size;

        if(!GLEW_ARB_texture_non_power_of_two)
        {
            Width = 1 << (int)floor((log((float)Width) / log(2.0f)) + 0.5f); 
            Height = 1 << (int)floor((log((float)Height) / log(2.0f)) + 0.5f);
        }

        if(Width != OriginalWidth || Height != OriginalHeight)
        {
            FIBITMAP *rdib = FreeImage_Rescale(dib, Width, Height, FILTER_BICUBIC);
            FreeImage_Unload(dib);
            dib = rdib;
        }
    }

    return dib;
}
shaderprogram.h
#include "texture.h"

// ----------------------------------------------------------------------------------------------------------------------------

class CShaderProgram
{
private:
    GLuint VertexShader, FragmentShader, Program;

public:
    GLuint *UniformLocations, *AttribLocations;

public:
    CShaderProgram();
    ~CShaderProgram();

    operator GLuint ();

    bool Load(char *VertexShaderFileName, char *FragmentShaderFileName);
    void Destroy();

private:
    GLuint LoadShader(char *FileName, GLenum Type);
    void SetDefaults();
};
shaderprogram.cpp
#include "shaderprogram.h"

// ----------------------------------------------------------------------------------------------------------------------------

CShaderProgram::CShaderProgram()
{
    SetDefaults();
}

CShaderProgram::~CShaderProgram()
{
}

CShaderProgram::operator GLuint ()
{
    return Program;
}

bool CShaderProgram::Load(char *VertexShaderFileName, char *FragmentShaderFileName)
{
    bool Error = false;

    Destroy();

    Error |= (VertexShader = LoadShader(VertexShaderFileName, GL_VERTEX_SHADER)) == 0;
    Error |= (FragmentShader = LoadShader(FragmentShaderFileName, GL_FRAGMENT_SHADER)) == 0;

    if(Error)
    {
        Destroy();
        return false;
    }

    Program = glCreateProgram();
    glAttachShader(Program, VertexShader);
    glAttachShader(Program, FragmentShader);
    glLinkProgram(Program);

    int LinkStatus;
    glGetProgramiv(Program, GL_LINK_STATUS, &LinkStatus);

    if(LinkStatus == GL_FALSE)
    {
        ErrorLog.Append("Error linking program (%s, %s)!\r\n", VertexShaderFileName, FragmentShaderFileName);

        int InfoLogLength = 0;
        glGetProgramiv(Program, GL_INFO_LOG_LENGTH, &InfoLogLength);
    
        if(InfoLogLength > 0)
        {
            char *InfoLog = new char[InfoLogLength];
            int CharsWritten  = 0;
            glGetProgramInfoLog(Program, InfoLogLength, &CharsWritten, InfoLog);
            ErrorLog.Append(InfoLog);
            delete [] InfoLog;
        }

        Destroy();

        return false;
    }

    return true;
}

void CShaderProgram::Destroy()
{
    glDetachShader(Program, VertexShader);
    glDetachShader(Program, FragmentShader);

    glDeleteShader(VertexShader);
    glDeleteShader(FragmentShader);

    glDeleteProgram(Program);

    delete [] UniformLocations;
    delete [] AttribLocations;

    SetDefaults();
}

GLuint CShaderProgram::LoadShader(char *FileName, GLenum Type)
{
    CString DirectoryFileName = ModuleDirectory + "Shaders\\" + FileName;

    FILE *File;

    if(fopen_s(&File, DirectoryFileName, "rb") != 0)
    {
        ErrorLog.Append("Error loading shader " + DirectoryFileName + "!\r\n");
        return 0;
    }

    fseek(File, 0, SEEK_END);
    long Size = ftell(File);
    fseek(File, 0, SEEK_SET);
    char *Source = new char[Size + 1];
    fread(Source, 1, Size, File);
    fclose(File);
    Source[Size] = 0;

    GLuint Shader = glCreateShader(Type);

    glShaderSource(Shader, 1, (const char**)&Source, NULL);
    delete [] Source;
    glCompileShader(Shader);

    int CompileStatus;
    glGetShaderiv(Shader, GL_COMPILE_STATUS, &CompileStatus);

    if(CompileStatus == GL_FALSE)
    {
        ErrorLog.Append("Error compiling shader %s!\r\n", FileName);

        int InfoLogLength = 0;
        glGetShaderiv(Shader, GL_INFO_LOG_LENGTH, &InfoLogLength);
    
        if(InfoLogLength > 0)
        {
            char *InfoLog = new char[InfoLogLength];
            int CharsWritten  = 0;
            glGetShaderInfoLog(Shader, InfoLogLength, &CharsWritten, InfoLog);
            ErrorLog.Append(InfoLog);
            delete [] InfoLog;
        }

        glDeleteShader(Shader);

        return 0;
    }

    return Shader;
}

void CShaderProgram::SetDefaults()
{
    VertexShader = 0;
    FragmentShader = 0;

    Program = 0;

    UniformLocations = NULL;
    AttribLocations = NULL;
}
camera.h
#include "shaderprogram.h"

// ----------------------------------------------------------------------------------------------------------------------------

#define CAMERA_KEY_W 0x0001
#define CAMERA_KEY_S 0x0002
#define CAMERA_KEY_A 0x0004
#define CAMERA_KEY_D 0x0008
#define CAMERA_KEY_R 0x0010
#define CAMERA_KEY_F 0x0020
#define CAMERA_KEY_Q 0x0040
#define CAMERA_KEY_E 0x0080
#define CAMERA_KEY_C 0x0100
#define CAMERA_KEY_SPACE 0x0200
#define CAMERA_KEY_SHIFT 0x0400
#define CAMERA_KEY_CONTROL 0x0800

// ----------------------------------------------------------------------------------------------------------------------------

class CCamera
{
protected:
    float Speed, Sensitivity;

protected:
    mat4x4 *ViewMatrix, *ViewMatrixInverse;

public:
    vec3 X, Y, Z, Position;

public:
    CCamera();
    ~CCamera();

    virtual void Look(const vec3 &Position, const vec3 &Reference);
    virtual void Move(const vec3 &Movement);
    virtual bool OnKeys(SHORT Keys, float FrameTime, vec3 &Movement) = 0;
    virtual void OnMouseMove(int dx, int dy) = 0;
    virtual void OnMouseWheel(short zDelta);
    virtual void SetViewMatrixPointer(float *ViewMatrix, float *ViewMatrixInverse = NULL);

protected:
    virtual void CalculateViewMatrix();
};

// ----------------------------------------------------------------------------------------------------------------------------

class CUniverseCamera : public CCamera
{
public:
    CUniverseCamera();
    ~CUniverseCamera();

    bool OnKeys(SHORT Keys, float FrameTime, vec3 &Movement);
    void OnMouseMove(int dx, int dy);
};

// ----------------------------------------------------------------------------------------------------------------------------

class CFlyingCamera : public CCamera
{
public:
    CFlyingCamera();
    ~CFlyingCamera();

    bool OnKeys(SHORT Keys, float FrameTime, vec3 &Movement);
    void OnMouseMove(int dx, int dy);
};

// ----------------------------------------------------------------------------------------------------------------------------

class CFirstPersonCamera : public CCamera
{
public:
    CFirstPersonCamera();
    ~CFirstPersonCamera();

    bool OnKeys(SHORT Keys, float FrameTime, vec3 &Movement);
    void OnMouseMove(int dx, int dy);
};

// ----------------------------------------------------------------------------------------------------------------------------

class CThirdPersonCamera : public CCamera
{
public:
    vec3 Reference;

public:
    CThirdPersonCamera();
    ~CThirdPersonCamera();

    void Look(const vec3 &Position, const vec3 &Reference);
    void Move(const vec3 &Movement);
    bool OnKeys(SHORT Keys, float FrameTime, vec3 &Movement);
    void OnMouseMove(int dx, int dy);
    void OnMouseWheel(short zDelta);
};
camera.cpp
#include "camera.h"

// ----------------------------------------------------------------------------------------------------------------------------

CCamera::CCamera()
{
    Speed = 2.5f;
    Sensitivity = 0.25f;

    ViewMatrix = NULL;
    ViewMatrixInverse = NULL;

    X = vec3(1.0f, 0.0f, 0.0f);
    Y = vec3(0.0f, 1.0f, 0.0f);
    Z = vec3(0.0f, 0.0f, 1.0f);

    Position = vec3(0.0f, 0.0f, 0.0f);
}

CCamera::~CCamera()
{
}

void CCamera::Look(const vec3 &Position, const vec3 &Reference)
{
    this->Position = Position;

    Z = normalize(Position - Reference);
    X = normalize(cross(vec3(0.0f, 1.0f, 0.0f), Z));
    Y = cross(Z, X);

    CalculateViewMatrix();
}

void CCamera::Move(const vec3 &Movement)
{
    Position += Movement;

    CalculateViewMatrix();
}

void CCamera::OnMouseWheel(short zDelta)
{
}

void CCamera::SetViewMatrixPointer(float *ViewMatrix, float *ViewMatrixInverse)
{
    this->ViewMatrix = (mat4x4*)ViewMatrix;
    this->ViewMatrixInverse = (mat4x4*)ViewMatrixInverse;

    CalculateViewMatrix();
}

void CCamera::CalculateViewMatrix()
{
    if(ViewMatrix != NULL)
    {
        *ViewMatrix = mat4x4(X.x, Y.x, Z.x, 0.0f, X.y, Y.y, Z.y, 0.0f, X.z, Y.z, Z.z, 0.0f, -dot(X, Position), -dot(Y, Position), -dot(Z, Position), 1.0f);

        if(ViewMatrixInverse != NULL)
        {
            *ViewMatrixInverse = inverse(*ViewMatrix);
        }
    }
}

// ----------------------------------------------------------------------------------------------------------------------------

CUniverseCamera::CUniverseCamera()
{
}

CUniverseCamera::~CUniverseCamera()
{
}

bool CUniverseCamera::OnKeys(SHORT Keys, float FrameTime, vec3 &Movement)
{
    float Speed = this->Speed;

    if(Keys & CAMERA_KEY_SHIFT) Speed *= 2.0f;
    if(Keys & CAMERA_KEY_CONTROL) Speed *= 0.5f;

    float Distance = Speed * FrameTime;

    vec3 Up = Y;
    vec3 Right = X;
    vec3 Forward = -Z;

    Up *= Distance;
    Right *= Distance;
    Forward *= Distance;

    if(Keys & CAMERA_KEY_W) Movement += Forward;
    if(Keys & CAMERA_KEY_S) Movement -= Forward;
    if(Keys & CAMERA_KEY_A) Movement -= Right;
    if(Keys & CAMERA_KEY_D) Movement += Right;
    if(Keys & CAMERA_KEY_R) Movement += Up;
    if(Keys & CAMERA_KEY_F) Movement -= Up;
    
    float AngleSpeed = 45.0f * FrameTime;

    if(Keys & CAMERA_KEY_Q)
    {
        X = rotate(X, AngleSpeed, Z);
        Y = rotate(Y, AngleSpeed, Z);
    }

    AngleSpeed = -AngleSpeed;

    if(Keys & CAMERA_KEY_E)
    {
        X = rotate(X, AngleSpeed, Z);
        Y = rotate(Y, AngleSpeed, Z);
    }

    return Keys & 0xFF ? true : false;
}

void CUniverseCamera::OnMouseMove(int dx, int dy)
{
    if(dx != 0)
    {
        float DeltaX = (float)dx * Sensitivity;

        X = rotate(X, DeltaX, Y);
        Z = rotate(Z, DeltaX, Y);
    }

    if(dy != 0)
    {
        float DeltaY = (float)dy * Sensitivity;

        Y = rotate(Y, DeltaY, X);
        Z = rotate(Z, DeltaY, X);

    }

    CalculateViewMatrix();
}

// ----------------------------------------------------------------------------------------------------------------------------

CFlyingCamera::CFlyingCamera()
{
}

CFlyingCamera::~CFlyingCamera()
{
}

bool CFlyingCamera::OnKeys(SHORT Keys, float FrameTime, vec3 &Movement)
{
    float Speed = this->Speed;

    if(Keys & CAMERA_KEY_SHIFT) Speed *= 2.0f;
    if(Keys & CAMERA_KEY_CONTROL) Speed *= 0.5f;

    float Distance = Speed * FrameTime;

    vec3 Up = Y;
    vec3 Right = X;
    vec3 Forward = -Z;

    Up *= Distance;
    Right *= Distance;
    Forward *= Distance;

    if(Keys & CAMERA_KEY_W) Movement += Forward;
    if(Keys & CAMERA_KEY_S) Movement -= Forward;
    if(Keys & CAMERA_KEY_A) Movement -= Right;
    if(Keys & CAMERA_KEY_D) Movement += Right;
    if(Keys & CAMERA_KEY_R) Movement += Up;
    if(Keys & CAMERA_KEY_F) Movement -= Up;

    return Keys & 0x3F ? true : false;
}

void CFlyingCamera::OnMouseMove(int dx, int dy)
{
    if(dx != 0)
    {
        float DeltaX = (float)dx * Sensitivity;

        X = rotate(X, DeltaX, vec3(0.0f, 1.0f, 0.0f));
        Y = rotate(Y, DeltaX, vec3(0.0f, 1.0f, 0.0f));
        Z = rotate(Z, DeltaX, vec3(0.0f, 1.0f, 0.0f));
    }

    if(dy != 0)
    {
        float DeltaY = (float)dy * Sensitivity;

        Y = rotate(Y, DeltaY, X);
        Z = rotate(Z, DeltaY, X);

        if(Y.y < 0.0f)
        {
            Z = vec3(0.0f, Z.y > 0.0f ? 1.0f : -1.0f, 0.0f);
            Y = cross(Z, X);
        }
    }

    CalculateViewMatrix();
}

// ----------------------------------------------------------------------------------------------------------------------------

CFirstPersonCamera::CFirstPersonCamera()
{
}

CFirstPersonCamera::~CFirstPersonCamera()
{
}

bool CFirstPersonCamera::OnKeys(SHORT Keys, float FrameTime, vec3 &Movement)
{
    float Speed = this->Speed;

    if(Keys & CAMERA_KEY_SHIFT) Speed *= 2.0f;
    if(Keys & CAMERA_KEY_CONTROL) Speed *= 0.5f;

    float Distance = Speed * FrameTime;

    vec3 Up = vec3(0.0f, 1.0f, 0.0f);
    vec3 Right = X;
    vec3 Forward = cross(Up, Right);

    Up *= Distance;
    Right *= Distance;
    Forward *= Distance;

    if(Keys & CAMERA_KEY_W) Movement += Forward;
    if(Keys & CAMERA_KEY_S) Movement -= Forward;
    if(Keys & CAMERA_KEY_A) Movement -= Right;
    if(Keys & CAMERA_KEY_D) Movement += Right;
    if(Keys & CAMERA_KEY_R) Movement += Up;
    if(Keys & CAMERA_KEY_F) Movement -= Up;

    return Keys & 0x3F ? true : false;
}

void CFirstPersonCamera::OnMouseMove(int dx, int dy)
{
    if(dx != 0)
    {
        float DeltaX = (float)dx * Sensitivity;

        X = rotate(X, DeltaX, vec3(0.0f, 1.0f, 0.0f));
        Y = rotate(Y, DeltaX, vec3(0.0f, 1.0f, 0.0f));
        Z = rotate(Z, DeltaX, vec3(0.0f, 1.0f, 0.0f));
    }

    if(dy != 0)
    {
        float DeltaY = (float)dy * Sensitivity;

        Y = rotate(Y, DeltaY, X);
        Z = rotate(Z, DeltaY, X);

        if(Y.y < 0.0f)
        {
            Z = vec3(0.0f, Z.y > 0.0f ? 1.0f : -1.0f, 0.0f);
            Y = cross(Z, X);
        }
    }

    CalculateViewMatrix();
}

// ----------------------------------------------------------------------------------------------------------------------------

CThirdPersonCamera::CThirdPersonCamera()
{
    Position = vec3(0.0f, 0.0f, 5.0f);
    Reference = vec3(0.0f, 0.0f, 0.0f);
}

CThirdPersonCamera::~CThirdPersonCamera()
{
}

void CThirdPersonCamera::Look(const vec3 &Position, const vec3 &Reference)
{
    this->Position = Position;
    this->Reference = Reference;

    Z = normalize(Position - Reference);
    X = normalize(cross(vec3(0.0f, 1.0f, 0.0f), Z));
    Y = cross(Z, X);

    CalculateViewMatrix();
}

void CThirdPersonCamera::Move(const vec3 &Movement)
{
    Position += Movement;
    Reference += Movement;

    CalculateViewMatrix();
}

bool CThirdPersonCamera::OnKeys(SHORT Keys, float FrameTime, vec3 &Movement)
{
    float Speed = this->Speed;

    if(Keys & CAMERA_KEY_SHIFT) Speed *= 2.0f;
    if(Keys & CAMERA_KEY_CONTROL) Speed *= 0.5f;

    float Distance = Speed * FrameTime;

    vec3 Up = vec3(0.0f, 1.0f, 0.0f);
    vec3 Right = X;
    vec3 Forward = cross(Up, Right);

    Up *= Distance;
    Right *= Distance;
    Forward *= Distance;

    if(Keys & CAMERA_KEY_W) Movement += Forward;
    if(Keys & CAMERA_KEY_S) Movement -= Forward;
    if(Keys & CAMERA_KEY_A) Movement -= Right;
    if(Keys & CAMERA_KEY_D) Movement += Right;
    if(Keys & CAMERA_KEY_R) Movement += Up;
    if(Keys & CAMERA_KEY_F) Movement -= Up;

    return Keys & 0x3F ? true : false;
}

void CThirdPersonCamera::OnMouseMove(int dx, int dy)
{
    Position -= Reference;

    if(dx != 0)
    {
        float DeltaX = (float)dx * Sensitivity;

        X = rotate(X, DeltaX, vec3(0.0f, 1.0f, 0.0f));
        Y = rotate(Y, DeltaX, vec3(0.0f, 1.0f, 0.0f));
        Z = rotate(Z, DeltaX, vec3(0.0f, 1.0f, 0.0f));
    }

    if(dy != 0)
    {
        float DeltaY = (float)dy * Sensitivity;

        Y = rotate(Y, DeltaY, X);
        Z = rotate(Z, DeltaY, X);

        if(Y.y < 0.0f)
        {
            Z = vec3(0.0f, Z.y > 0.0f ? 1.0f : -1.0f, 0.0f);
            Y = cross(Z, X);
        }
    }

    Position = Reference + Z * length(Position);

    CalculateViewMatrix();
}

void CThirdPersonCamera::OnMouseWheel(short zDelta)
{
    Position -= Reference;

    if(zDelta < 0 && length(Position) < 500.0f)
    {
        Position += Position * 0.1f;
    }

    if(zDelta > 0 && length(Position) > 0.05f)
    {
        Position -= Position * 0.1f;
    }

    Position += Reference;

    CalculateViewMatrix();
}
opengl33renderer.h
#include "camera.h"

// ----------------------------------------------------------------------------------------------------------------------------

class COpenGL33Renderer
{
protected:
    int LastX, LastY;

protected:
    int Width, Height;

protected:
    mat3x3 NormalMatrix;
    mat4x4 ModelMatrix, ViewMatrix, ProjectionMatrix, ModelViewProjectionMatrix;

protected:
    CCamera *Camera;

public:
    CString Text;

public:
    COpenGL33Renderer();
    ~COpenGL33Renderer();

    virtual bool Init() = 0;
    virtual void Resize(int Width, int Height) = 0;
    virtual void Render() = 0;
    virtual bool Animate(float FrameTime) = 0;
    virtual void Destroy() = 0;

    virtual void MoveCamera(const vec3 &Movement);

    virtual bool OnCameraKeys(SHORT Keys, float FrameTime, vec3 &Movement);
    virtual void OnKeyDown(UINT Key);
    virtual void OnLButtonDown(int X, int Y);
    virtual void OnMouseMove(int X, int Y, bool LButtonDown, bool RButtonDown);
    virtual void OnMouseWheel(short zDelta);
    virtual void OnRButtonDown(int X, int Y);
};
opengl33renderer.cpp
#include "opengl33renderer.h"

// ----------------------------------------------------------------------------------------------------------------------------

COpenGL33Renderer::COpenGL33Renderer()
{
    Camera = NULL;
}

COpenGL33Renderer::~COpenGL33Renderer()
{
}

void COpenGL33Renderer::MoveCamera(const vec3 &Movement)
{
    if(Camera != NULL)
    {
        Camera->Move(Movement);
    }
}

bool COpenGL33Renderer::OnCameraKeys(SHORT Keys, float FrameTime, vec3 &Movement)
{
    if(Camera != NULL)
    {
        return Camera->OnKeys(Keys, FrameTime, Movement);
    }

    return false;
}

void COpenGL33Renderer::OnKeyDown(UINT Key)
{
}

void COpenGL33Renderer::OnLButtonDown(int X, int Y)
{
    LastX = X;
    LastY = Y;
}

void COpenGL33Renderer::OnMouseMove(int X, int Y, bool LButtonDown, bool RButtonDown)
{
    if(RButtonDown)
    {
        if(Camera != NULL)
        {
            Camera->OnMouseMove(LastX - X, LastY - Y);
        }
    }

    LastX = X;
    LastY = Y;
}

void COpenGL33Renderer::OnMouseWheel(short zDelta)
{
    if(Camera != NULL)
    {
        Camera->OnMouseWheel(zDelta);
    }
}

void COpenGL33Renderer::OnRButtonDown(int X, int Y)
{
    LastX = X;
    LastY = Y;
}
opengl33view.h
#include "opengl33renderer.h"

// ----------------------------------------------------------------------------------------------------------------------------

class COpenGL33View
{
private:
    char *Title;
    int Width, Height, Samples;
    HWND hWnd;
    HGLRC hGLRC;

private:
    COpenGL33Renderer *OpenGL33Renderer;

public:
    COpenGL33View(COpenGL33Renderer *OpenGL33Renderer);
    ~COpenGL33View();

    bool Init(HINSTANCE hInstance, char *Title, int Width, int Height, int Samples);
    void Show(bool Maximized = false);
    void MessageLoop();
    void Destroy();
    
    void OnKeyDown(UINT Key);
    void OnLButtonDown(int X, int Y);
    void OnMouseMove(int X, int Y);
    void OnMouseWheel(short zDelta);
    void OnPaint();
    void OnRButtonDown(int X, int Y);
    void OnSize(int Width, int Height);
};
opengl33view.cpp
#include "opengl33view.h"

// ----------------------------------------------------------------------------------------------------------------------------

COpenGL33View *OpenGL33View = NULL;

// ----------------------------------------------------------------------------------------------------------------------------

LRESULT CALLBACK WndProc(HWND hWnd, UINT uiMsg, WPARAM wParam, LPARAM lParam)
{
    switch(uiMsg)
    {
        case WM_CLOSE:
            PostQuitMessage(0);
            break;

        case WM_KEYDOWN:
            if(OpenGL33View != NULL) OpenGL33View->OnKeyDown((UINT)wParam);
            break;

        case WM_LBUTTONDOWN:
            if(OpenGL33View != NULL) OpenGL33View->OnLButtonDown(LOWORD(lParam), HIWORD(lParam));
            break;

        case WM_MOUSEMOVE:
            if(OpenGL33View != NULL) OpenGL33View->OnMouseMove(LOWORD(lParam), HIWORD(lParam));
            break;

        case 0x020A: // WM_MOUSEWHEEL
            if(OpenGL33View != NULL) OpenGL33View->OnMouseWheel(HIWORD(wParam));
            break;

        case WM_PAINT:
            if(OpenGL33View != NULL) OpenGL33View->OnPaint();
            break;

        case WM_RBUTTONDOWN:
            if(OpenGL33View != NULL) OpenGL33View->OnRButtonDown(LOWORD(lParam), HIWORD(lParam));
            break;

        case WM_SIZE:
            if(OpenGL33View != NULL) OpenGL33View->OnSize(LOWORD(lParam), HIWORD(lParam));
            break;

        default:
            return DefWindowProc(hWnd, uiMsg, wParam, lParam);
    }

    return 0;
}

// ----------------------------------------------------------------------------------------------------------------------------

CString ModuleDirectory, ErrorLog;

// ----------------------------------------------------------------------------------------------------------------------------

void GetModuleDirectory()
{
    char *moduledirectory = new char[256];
    GetModuleFileName(GetModuleHandle(NULL), moduledirectory, 256);
    *(strrchr(moduledirectory, '\\') + 1) = 0;
    ModuleDirectory = moduledirectory;
    delete [] moduledirectory;
}

// ----------------------------------------------------------------------------------------------------------------------------

COpenGL33View::COpenGL33View(COpenGL33Renderer *OpenGL33Renderer)
{
    OpenGL33View = this;
    this->OpenGL33Renderer = OpenGL33Renderer;
}

COpenGL33View::~COpenGL33View()
{
}

bool COpenGL33View::Init(HINSTANCE hInstance, char *Title, int Width, int Height, int Samples)
{
    this->Title = Title;
    this->Width = Width;
    this->Height = Height;

    WNDCLASSEX WndClassEx;

    memset(&WndClassEx, 0, sizeof(WNDCLASSEX));

    WndClassEx.cbSize = sizeof(WNDCLASSEX);
    WndClassEx.style = CS_OWNDC | CS_HREDRAW | CS_VREDRAW;
    WndClassEx.lpfnWndProc = WndProc;
    WndClassEx.hInstance = hInstance;
    WndClassEx.hIcon = LoadIcon(NULL, IDI_APPLICATION);
    WndClassEx.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
    WndClassEx.hCursor = LoadCursor(NULL, IDC_ARROW);
    WndClassEx.lpszClassName = "OpenGL33TutorialsWin32Framework";

    if(RegisterClassEx(&WndClassEx) == 0)
    {
        ErrorLog.Set("RegisterClassEx failed!");
        return false;
    }

    DWORD Style = WS_OVERLAPPEDWINDOW | WS_CLIPSIBLINGS | WS_CLIPCHILDREN;

    hWnd = CreateWindowEx(WS_EX_APPWINDOW, WndClassEx.lpszClassName, Title, Style, 0, 0, Width, Height, NULL, NULL, hInstance, NULL);

    if(hWnd == NULL)
    {
        ErrorLog.Set("CreateWindowEx failed!");
        return false;
    }

    HDC hDC = GetDC(hWnd);

    if(hDC == NULL)
    {
        ErrorLog.Set("GetDC failed!");
        return false;
    }

    PIXELFORMATDESCRIPTOR pfd;

    memset(&pfd, 0, sizeof(PIXELFORMATDESCRIPTOR));

    pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR);
    pfd.nVersion = 1;
    pfd.dwFlags = PFD_DOUBLEBUFFER | PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW;
    pfd.iPixelType = PFD_TYPE_RGBA;
    pfd.cColorBits = 32;
    pfd.cDepthBits = 24;
    pfd.iLayerType = PFD_MAIN_PLANE;
 
    int PixelFormat = ChoosePixelFormat(hDC, &pfd);

    if(PixelFormat == 0)
    {
        ErrorLog.Set("ChoosePixelFormat failed!");
        return false;
    }

    static int MSAAPixelFormat = 0;

    if(SetPixelFormat(hDC, MSAAPixelFormat == 0 ? PixelFormat : MSAAPixelFormat, &pfd) == FALSE)
    {
        ErrorLog.Set("SetPixelFormat failed!");
        return false;
    }

    hGLRC = wglCreateContext(hDC);

    if(hGLRC == NULL)
    {
        ErrorLog.Set("wglCreateContext failed!");
        return false;
    }

    if(wglMakeCurrent(hDC, hGLRC) == FALSE)
    {
        ErrorLog.Set("wglMakeCurrent (1) failed!");
        return false;
    }

    if(glewInit() != GLEW_OK)
    {
        ErrorLog.Set("glewInit failed!");
        return false;
    }

    if(MSAAPixelFormat == 0 && Samples > 0)
    {
        if(WGLEW_ARB_pixel_format && GLEW_ARB_multisample)
        {
            while(Samples > 0)
            {
                UINT NumFormats = 0;

                int PFAttribs[] =
                {
                    WGL_DRAW_TO_WINDOW_ARB, GL_TRUE,
                    WGL_SUPPORT_OPENGL_ARB, GL_TRUE,
                    WGL_DOUBLE_BUFFER_ARB, GL_TRUE,
                    WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB,
                    WGL_COLOR_BITS_ARB, 32,
                    WGL_DEPTH_BITS_ARB, 24,
                    WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB,
                    WGL_SAMPLE_BUFFERS_ARB, GL_TRUE,
                    WGL_SAMPLES_ARB, Samples,
                    0
                };

                if(wglChoosePixelFormatARB(hDC, PFAttribs, NULL, 1, &MSAAPixelFormat, &NumFormats) == TRUE && NumFormats > 0) break;

                Samples--;
            }

            wglDeleteContext(hGLRC);
            DestroyWindow(hWnd);
            UnregisterClass(WndClassEx.lpszClassName, hInstance);

            return Init(hInstance, Title, Width, Height, Samples);
        }
        else
        {
            Samples = 0;
        }
    }

    this->Samples = Samples;

    if(WGLEW_ARB_create_context)
    {
        wglDeleteContext(hGLRC);

        int GL33RCAttribs[] =
        {
            WGL_CONTEXT_MAJOR_VERSION_ARB, 3,
            WGL_CONTEXT_MINOR_VERSION_ARB, 3,
            WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB,
            0
        };

        hGLRC = wglCreateContextAttribsARB(hDC, 0, GL33RCAttribs);

        if(hGLRC == NULL)
        {
            ErrorLog.Set("wglCreateContextAttribsARB failed!");
            return false;
        }

        if(wglMakeCurrent(hDC, hGLRC) == FALSE)
        {
            ErrorLog.Set("wglMakeCurrent (2) failed!");
            return false;
        }
    }
    else
    {
        ErrorLog.Set("WGL_ARB_create_context not supported!");
        return false;
    }

    GetModuleDirectory();

    glGetIntegerv(GL_MAX_TEXTURE_SIZE, &gl_max_texture_size);

    if(GLEW_EXT_texture_filter_anisotropic)
    {
        glGetIntegerv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &gl_max_texture_max_anisotropy_ext);
    }

    if(WGLEW_EXT_swap_control)
    {
        wglSwapIntervalEXT(0);
    }

    if(OpenGL33Renderer != NULL)
    {
        return OpenGL33Renderer->Init();
    }

    return true;
}

void COpenGL33View::Show(bool Maximized)
{
    RECT dRect, wRect, cRect;

    GetWindowRect(GetDesktopWindow(), &dRect);
    GetWindowRect(hWnd, &wRect);
    GetClientRect(hWnd, &cRect);

    wRect.right += Width - cRect.right;
    wRect.bottom += Height - cRect.bottom;
    wRect.right -= wRect.left;
    wRect.bottom -= wRect.top;
    wRect.left = dRect.right / 2 - wRect.right / 2;
    wRect.top = dRect.bottom / 2 - wRect.bottom / 2;

    MoveWindow(hWnd, wRect.left, wRect.top, wRect.right, wRect.bottom, FALSE);

    ShowWindow(hWnd, Maximized ? SW_SHOWMAXIMIZED : SW_SHOWNORMAL);
}

void COpenGL33View::MessageLoop()
{
    MSG Msg;

    while(GetMessage(&Msg, NULL, 0, 0) > 0)
    {
        TranslateMessage(&Msg);
        DispatchMessage(&Msg);
    }
}

void COpenGL33View::Destroy()
{
    if(OpenGL33Renderer != NULL && GLEW_VERSION_3_3)
    {
        OpenGL33Renderer->Destroy();
    }

    wglDeleteContext(hGLRC);
    DestroyWindow(hWnd);
}

void COpenGL33View::OnKeyDown(UINT Key)
{
    switch(Key)
    {
        case VK_ESCAPE:
            PostQuitMessage(0);
            break;
    }

    if(OpenGL33Renderer != NULL)
    {
        OpenGL33Renderer->OnKeyDown(Key);
    }
}

void COpenGL33View::OnLButtonDown(int X, int Y)
{
    if(OpenGL33Renderer != NULL)
    {
        OpenGL33Renderer->OnLButtonDown(X, Y);
    }
}

void COpenGL33View::OnMouseMove(int X, int Y)
{
    if(OpenGL33Renderer != NULL)
    {
        OpenGL33Renderer->OnMouseMove(X, Y, GetKeyState(VK_LBUTTON) & 0x80 ? true : false, GetKeyState(VK_RBUTTON) & 0x80 ? true : false);
    }
}

void COpenGL33View::OnMouseWheel(short zDelta)
{
    if(OpenGL33Renderer != NULL)
    {
        OpenGL33Renderer->OnMouseWheel(zDelta);
    }
}

void COpenGL33View::OnPaint()
{
    static DWORD LastFrameTime = GetTickCount(), LastFPSTime = LastFrameTime, FPS = 0;

    PAINTSTRUCT ps;

    HDC hDC = BeginPaint(hWnd, &ps);

    DWORD Time = GetTickCount();

    float FrameTime = float(Time - LastFrameTime) * 0.001f;
    LastFrameTime = Time;

    if(Time - LastFPSTime > 1000)
    {
        CString Text = Title;

        if(OpenGL33Renderer != NULL)
        {
            if(OpenGL33Renderer->Text[0] != 0)
            {
                Text.Append(" - " + OpenGL33Renderer->Text);
            }
        }

        Text.Append(" - %dx%d", Width, Height);
        Text.Append(", ATF %dx", gl_max_texture_max_anisotropy_ext);
        Text.Append(", MSAA %dx", Samples);
        Text.Append(", FPS: %d", FPS);
        Text.Append(" - %s", glGetString(GL_RENDERER));

        SetWindowText(hWnd, Text);
    
        LastFPSTime = Time;
        FPS = 0;
    }
    else
    {
        FPS++;
    }

    if(OpenGL33Renderer != NULL)
    {
        bool Animated = OpenGL33Renderer->Animate(FrameTime);

        SHORT Keys = 0x0000;

        if(GetKeyState('W') & 0x80) Keys |= CAMERA_KEY_W;
        if(GetKeyState('S') & 0x80) Keys |= CAMERA_KEY_S;
        if(GetKeyState('A') & 0x80) Keys |= CAMERA_KEY_A;
        if(GetKeyState('D') & 0x80) Keys |= CAMERA_KEY_D;
        if(GetKeyState('R') & 0x80) Keys |= CAMERA_KEY_R;
        if(GetKeyState('F') & 0x80) Keys |= CAMERA_KEY_F;
        if(GetKeyState('Q') & 0x80) Keys |= CAMERA_KEY_Q;
        if(GetKeyState('E') & 0x80) Keys |= CAMERA_KEY_E;
        if(GetKeyState('C') & 0x80) Keys |= CAMERA_KEY_C;
        if(GetKeyState(VK_SPACE) & 0x80) Keys |= CAMERA_KEY_SPACE;
        if(GetKeyState(VK_SHIFT) & 0x80) Keys |= CAMERA_KEY_SHIFT;
        if(GetKeyState(VK_CONTROL) & 0x80) Keys |= CAMERA_KEY_CONTROL;

        vec3 Movement;

        if(OpenGL33Renderer->OnCameraKeys(Keys, FrameTime, Movement))
        {
            OpenGL33Renderer->MoveCamera(Movement);
        }

        OpenGL33Renderer->Render();
    }

    SwapBuffers(hDC);

    EndPaint(hWnd, &ps);

    InvalidateRect(hWnd, NULL, FALSE);
}

void COpenGL33View::OnRButtonDown(int X, int Y)
{
    if(OpenGL33Renderer != NULL)
    {
        OpenGL33Renderer->OnRButtonDown(X, Y);
    }
}

void COpenGL33View::OnSize(int Width, int Height)
{
    this->Width = Width;
    this->Height = Height;

    if(OpenGL33Renderer != NULL)
    {
        OpenGL33Renderer->Resize(Width, Height);
    }
}
myopengl33renderer.h
#include "opengl33view.h"

// ----------------------------------------------------------------------------------------------------------------------------

class CMyOpenGL33Renderer : public COpenGL33Renderer
{
public:
    CMyOpenGL33Renderer();
    ~CMyOpenGL33Renderer();

    bool Init();
    void Resize(int Width, int Height);
    void Render();
    bool Animate(float FrameTime);
    void Destroy();
};
myopengl33renderer.cpp
#include "myopengl33renderer.h"

// ----------------------------------------------------------------------------------------------------------------------------

CMyOpenGL33Renderer::CMyOpenGL33Renderer()
{
}

CMyOpenGL33Renderer::~CMyOpenGL33Renderer()
{
}

bool CMyOpenGL33Renderer::Init()
{
    return true;
}

void CMyOpenGL33Renderer::Resize(int Width, int Height)
{
    this->Width = Width;
    this->Width = Height;

    glViewport(0 , 0, Width, Height);
}

void CMyOpenGL33Renderer::Render()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}

bool CMyOpenGL33Renderer::Animate(float FrameTime)
{
    return false;
}

void CMyOpenGL33Renderer::Destroy()
{
}
opengl33app.cpp
#include "opengl33renderer.h"
    
// ----------------------------------------------------------------------------------------------------------------------------

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR sCmdLine, int iShow)
{
    CMyOpenGL33Renderer *MyOpenGL33Renderer = new CMyOpenGL33Renderer();
    COpenGL33View *OpenGL33View = new COpenGL33View(MyOpenGL33Renderer);

    char *AppName = "OpenGL 3.3 tutorials Win32 framework";

    if(OpenGL33View->Init(hInstance, AppName, 800, 600, 4))
    {
        OpenGL33View->Show();
        OpenGL33View->MessageLoop();
    }
    else
    {
        MessageBox(NULL, ErrorLog, AppName, MB_OK | MB_ICONERROR);
    }

    OpenGL33View->Destroy();

    delete OpenGL33View;
    delete MyOpenGL33Renderer;

    return 0;
}
Download
opengl_33_tutorials_win32_framework.zip (Visual Studio 2005 Professional)

© 2010 - 2016 Bc. Michal Belanec, michalbelanec@centrum.sk
Last update June 25, 2016
OpenGL® is a registered trademark of Silicon Graphics Inc.