Setup OpenGL like Direct2D

Started by
8 comments, last by wolfscaptain 12 years, 9 months ago
I've just started to learn opengl(version 4.1, GLSL 4.10) and up till now I haven't dealt with transforms/Coordinate systems.

I've just been doing this up till now:

//minimal.vert
#version 150 core

in vec4 in_Position;
in vec3 in_Color;
out vec3 ex_Color;

void main(void)
{
gl_Position = in_Position;
ex_Color = in_Color;
}

Does anybody know a good online resource, or the like, that explains(without deprecated code) how to set up OpenGL(using shaders) to the Direct2D coordinate space? Basically I just want to set up a simple camera system and draw a simple triangle.


-----------
Direct2D uses a left-handed coordinate space; that is, positive x-axis values increase to the right and positive y-axis values increase downward. Everything on the screen is positioned relative to the origin, which is the point where the x-axis and y-axis intersect (0, 0), as shown in the following illustration. Direct2D render targets use this coordinate space.
The Direct2D Coordinate Space
Advertisement
Google "orthogonal projection".

Also, that space is commonly refered to as screen space. Might help you in future searches (orthogoal projection is pretty straightforward though).
glOrtho is what you're looking for.

It's really simple. glOrtho(0, screen_width, 0, screen_height, -1, 1); for the most basic setup.


You should really read the NEHE tutorials if you're learning to use OpenGL. They walk you through all this stuff. Link: http://nehe.gamedev.net/
As to the direct2d part of the question, you should be able to use a different base matrix, right after you set the identity matrix, to do this. In the case of openGL, I think you could just negate the y column of the identitymateix to achieve axes like direct2d, then translate down and left half your screen width so that the origin is in the corner.

glOrtho is what you're looking for.

I believe it has been deprecated, but I see where your going.

Would I do something like this?


// setup code
GLuint projMatrixLoc;

projMatrixLoc = glGetUniformLocation(m_ID, "projMatrix");

std::vector<float> projOrthoMatrix;
OrthoMatrix(rect.right, rect.left, rect.top, rect.bottom, 1, -1, projOrthoMatrix);
glUniformMatrix4fv(projMatrixLoc, 1, false, &projOrthoMatrix.front());

void OrthoMatrix(float winRight, float winLeft, float winTop,
float winBottom, float winFar, float winNear,
std::vector<float> &matrix)
{
float r_l = winRight - winLeft;
float t_b = winTop - winBottom;
float f_n = winFar - winNear;
float tx = - (winRight + winLeft) / (winRight - winLeft);
float ty = - (winTop + winBottom) / (winTop - winBottom);
float tz = - (winFar + winNear) / (winFar - winNear);

matrix.resize(16);
matrix[0] = 2.0f / r_l;
matrix[1] = 0.0f;
matrix[2] = 0.0f;
matrix[3] = tx;

matrix[4] = 0.0f;
matrix[5] = 2.0f / t_b;
matrix[6] = 0.0f;
matrix[7] = ty;

matrix[8] = 0.0f;
matrix[9] = 0.0f;
matrix[10] = 2.0f / f_n;
matrix[11] = tz;

matrix[12] = 0.0f;
matrix[13] = 0.0f;
matrix[14] = 0.0f;
matrix[15] = 1.0f;
}


#version 150 core
uniform mat4 projMatrix;
in vec4 in_Position;
in vec3 in_Color;
out vec3 ex_Color;

void main(void)
{
ex_Color = in_Color;
gl_Position = projMatrix * in_Position;
}

[quote name='nfries88' timestamp='1310025290' post='4832150']
glOrtho is what you're looking for.

I believe it has been deprecated, but I see where your going.

Would I do something like this?
[/quote]
Humm. How about glOrtho2D, then?
I remember something about deprecation, but now I cannot find anything about it. Can somebody elaborate on it? Thanks. :)
Got it working, thx for help guys. :D (Thumbs up for everyone)



My badly written but workable code below. (GLM = OpenGL Mathematics)

#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/ext.hpp>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <iterator>
#include <array>
#include <assert.h>


void FormatOutput(LPTSTR formatstring, ...)
{
TCHAR buff[100000];
memset(buff, 0, sizeof(buff));
va_list args;
va_start(args, formatstring);
_vsntprintf(buff, sizeof(buff), formatstring, args);
OutputDebugString(buff);
}

class CGLShader
{
public:
CGLShader(){}
~CGLShader()
{
if(m_ID != 0)
glDeleteShader(m_ID);
}
bool Load(GLenum shaderType, std::string fileName)
{
m_Type = shaderType;
m_ID = glCreateShader(shaderType);

std::string fileContents;
if(LoadFile(fileName, fileContents))
if(Compile(fileContents))
return true;

return true;
}
bool LoadFile(std::string fileName, std::string &fileContents)
{
typedef std::istream_iterator<GLchar> istream_iterator;
std::ifstream file(fileName);
std::string buff;

if(file)
{
file >> std::noskipws;
std::copy(std::istream_iterator<GLchar>(file), std::istream_iterator<GLchar>(), std::back_inserter(fileContents));
fileContents.push_back('\0');
return true;
}
return false;
}
bool Compile(std::string &fileContents)
{
if(fileContents.empty())
return false;

const GLchar *r = &fileContents.front();
glShaderSource(m_ID, 1, &r, NULL);
glCompileShader(m_ID);

int param;
glGetShaderiv(m_ID, GL_COMPILE_STATUS, &param);
if(param == GL_TRUE) return true;
else
{
::MessageBox(NULL, _T("error"), _T(""), MB_OK);
return false;
}
}
operator GLuint() const
{
assert(m_ID != NULL);
return m_ID;
}
GLenum m_Type; // GL_VERTEX_SHADER or GL_FRAGMENT_SHADER
GLuint m_ID;
};
typedef std::array<GLfloat, 9> Array;
class OpenGLRenderer
{
public:
~OpenGLRenderer() { DestroyScene(); }
static void CALLBACK DebugCallback(unsigned int source, unsigned int type, unsigned int id,
unsigned int severity, int length,
const char* message, void* userParam)
{
FormatOutput(_T("sources = %i, types = %i, ids = %ui, severities = %i, msglog = %S \n"), source, type, id, severity, message);
}
void InitAPI()
{
// Program
glBindFragDataLocation = (PFNGLBINDFRAGDATALOCATIONPROC)wglGetProcAddress("glBindFragDataLocation");
glCreateProgram = (PFNGLCREATEPROGRAMPROC)wglGetProcAddress("glCreateProgram");
glDeleteProgram = (PFNGLDELETEPROGRAMPROC)wglGetProcAddress("glDeleteProgram");
glUseProgram = (PFNGLUSEPROGRAMPROC)wglGetProcAddress("glUseProgram");
glAttachShader = (PFNGLATTACHSHADERPROC)wglGetProcAddress("glAttachShader");
glDetachShader = (PFNGLDETACHSHADERPROC)wglGetProcAddress("glDetachShader");
glLinkProgram = (PFNGLLINKPROGRAMPROC)wglGetProcAddress("glLinkProgram");
glGetProgramiv = (PFNGLGETPROGRAMIVPROC)wglGetProcAddress("glGetProgramiv");
glGetShaderInfoLog = (PFNGLGETSHADERINFOLOGPROC)wglGetProcAddress("glGetShaderInfoLog");
glGetUniformLocation = (PFNGLGETUNIFORMLOCATIONPROC)wglGetProcAddress("glGetUniformLocation");
glUniform1i = (PFNGLUNIFORM1IPROC)wglGetProcAddress("glUniform1i");
glUniform1iv = (PFNGLUNIFORM1IVPROC)wglGetProcAddress("glUniform1iv");
glUniform2iv = (PFNGLUNIFORM2IVPROC)wglGetProcAddress("glUniform2iv");
glUniform3iv = (PFNGLUNIFORM3IVPROC)wglGetProcAddress("glUniform3iv");
glUniform4iv = (PFNGLUNIFORM4IVPROC)wglGetProcAddress("glUniform4iv");
glUniform1f = (PFNGLUNIFORM1FPROC)wglGetProcAddress("glUniform1f");
glUniform1fv = (PFNGLUNIFORM1FVPROC)wglGetProcAddress("glUniform1fv");
glUniform2fv = (PFNGLUNIFORM2FVPROC)wglGetProcAddress("glUniform2fv");
glUniform3fv = (PFNGLUNIFORM3FVPROC)wglGetProcAddress("glUniform3fv");
glUniform4fv = (PFNGLUNIFORM4FVPROC)wglGetProcAddress("glUniform4fv");
glUniformMatrix4fv = (PFNGLUNIFORMMATRIX4FVPROC)wglGetProcAddress("glUniformMatrix4fv");
glGetAttribLocation = (PFNGLGETATTRIBLOCATIONPROC)wglGetProcAddress("glGetAttribLocation");
glVertexAttrib1f = (PFNGLVERTEXATTRIB1FPROC)wglGetProcAddress("glVertexAttrib1f");
glVertexAttrib1fv = (PFNGLVERTEXATTRIB1FVPROC)wglGetProcAddress("glVertexAttrib1fv");
glVertexAttrib2fv = (PFNGLVERTEXATTRIB2FVPROC)wglGetProcAddress("glVertexAttrib2fv");
glVertexAttrib3fv = (PFNGLVERTEXATTRIB3FVPROC)wglGetProcAddress("glVertexAttrib3fv");
glVertexAttrib4fv = (PFNGLVERTEXATTRIB4FVPROC)wglGetProcAddress("glVertexAttrib4fv");
glEnableVertexAttribArray = (PFNGLENABLEVERTEXATTRIBARRAYPROC)wglGetProcAddress("glEnableVertexAttribArray");
glDisableVertexAttribArray = (PFNGLDISABLEVERTEXATTRIBARRAYPROC)wglGetProcAddress("glDisableVertexAttribArray");
glBindAttribLocation = (PFNGLBINDATTRIBLOCATIONPROC)wglGetProcAddress("glBindAttribLocation");
glGetActiveUniform = (PFNGLGETACTIVEUNIFORMPROC)wglGetProcAddress("glGetActiveUniform");

// Shader
glCreateShader = (PFNGLCREATESHADERPROC)wglGetProcAddress("glCreateShader");
glDeleteShader = (PFNGLDELETESHADERPROC)wglGetProcAddress("glDeleteShader");
glShaderSource = (PFNGLSHADERSOURCEPROC)wglGetProcAddress("glShaderSource");
glCompileShader = (PFNGLCOMPILESHADERPROC)wglGetProcAddress("glCompileShader");
glGetShaderiv = (PFNGLGETSHADERIVPROC)wglGetProcAddress("glGetShaderiv");

// VBO
glGenBuffers = (PFNGLGENBUFFERSPROC)wglGetProcAddress("glGenBuffers");
glBindBuffer = (PFNGLBINDBUFFERPROC)wglGetProcAddress("glBindBuffer");
glBufferData = (PFNGLBUFFERDATAPROC)wglGetProcAddress("glBufferData");
glBufferSubData = (PFNGLBUFFERSUBDATAPROC)wglGetProcAddress("glBufferSubData");
glVertexAttribPointer = (PFNGLVERTEXATTRIBPOINTERPROC)wglGetProcAddress("glVertexAttribPointer");

// debug
glDebugMessageControlARB = (PFNGLDEBUGMESSAGECONTROLARBPROC)wglGetProcAddress("glDebugMessageControlARB");
glDebugMessageInsertARB = (PFNGLDEBUGMESSAGEINSERTARBPROC)wglGetProcAddress("glDebugMessageInsertARB");
glDebugMessageCallbackARB = (PFNGLDEBUGMESSAGECALLBACKARBPROC)wglGetProcAddress("glDebugMessageCallbackARB");
glGetDebugMessageLogARB = (PFNGLGETDEBUGMESSAGELOGARBPROC)wglGetProcAddress("glGetDebugMessageLogARB");
}
void GetGLVersion(int* major, int* minor)
{
// for all versions
char* ver = (char*)glGetString(GL_VERSION); // ver = "4.1.0"

*major = ver[0] - '0';
if( *major >= 3)
{
// for GL 4.x
glGetIntegerv(GL_MAJOR_VERSION, major); // major = 3
glGetIntegerv(GL_MINOR_VERSION, minor); // minor = 2
}
else
{
*minor = ver[2] - '0';
}

// GLSL
//ver = (char*)glGetString(GL_SHADING_LANGUAGE_VERSION); // 4.10 NVIDIA via Cg compiler
}
bool CreateGLContext(HWND hWnd)
{
m_hWnd = hWnd;
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 = 32;
pfd.iLayerType = PFD_MAIN_PLANE;

// Note that the handle to the DC can only be used by a single thread at any one time
HDC hdc = ::GetDC(hWnd);

int nPixelFormat = ChoosePixelFormat(hdc, &pfd);

if (nPixelFormat == 0) return false;

BOOL bResult = SetPixelFormat(hdc, nPixelFormat, &pfd);

if (!bResult) return false;

// --- OpenGL 3.x ---
HGLRC tempContext = wglCreateContext(hdc);
wglMakeCurrent(hdc,tempContext);

int major, minor;
GetGLVersion(&major, &minor);

if( major < 3 || ( major == 3 && minor < 2 ) )
::MessageBox(NULL,_T("OpenGL 3.2 is not supported!"), _T(""), MB_OK);

int attribs[] =
{
WGL_CONTEXT_MAJOR_VERSION_ARB, major, WGL_CONTEXT_MINOR_VERSION_ARB, minor,
WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB | WGL_CONTEXT_DEBUG_BIT_ARB,// | WGL_CONTEXT_DEBUG_BIT_ARB,
WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB, //0x9126 , 0x00000001,
0
};

PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsARB = NULL;
wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC) wglGetProcAddress("wglCreateContextAttribsARB");
if(wglCreateContextAttribsARB != NULL)
{
m_hrc = wglCreateContextAttribsARB(hdc,0, attribs);
}

wglMakeCurrent(NULL,NULL);
wglDeleteContext(tempContext);
wglMakeCurrent(hdc,m_hrc);

InitAPI();

if (!m_hrc)
{
::MessageBox(NULL,_T("OpenGL 3.x RC was not created!"), _T(""), MB_OK);
return false;
}

return true;
}
void DestroyGLContext()
{
if(m_hrc != NULL)
{
wglMakeCurrent(GetDC(m_hWnd), m_hrc);
wglDeleteContext(m_hrc);
m_hrc = NULL;
}
}
void PrepareScene()
{
glDebugMessageCallbackARB(&OpenGLRenderer::DebugCallback, NULL);
//---------------------------------
glClearColor (1.0, 1.0, 1.0, 0.0);

m_programID = glCreateProgram();

m_pVertSh.Load(GL_VERTEX_SHADER, std::string("minimal.vert"));
m_pFragSh.Load(GL_FRAGMENT_SHADER, std::string("minimal.frag"));

glAttachShader(m_programID, m_pVertSh);
glAttachShader(m_programID, m_pFragSh);

glBindFragDataLocation(m_programID, 0, "out_Color");
if(!Link())
::MessageBox(NULL, _T("program linking error!"), _T(""), MB_OK);

glBindAttribLocation(m_programID, 0, "in_Position");
glBindAttribLocation(m_programID, 1, "in_Color");

m_MVPMatrixID = glGetUniformLocation(m_programID, "MVP");

glUseProgram(m_programID);
SetData();
SetupMVP();
}
bool Link()
{
glLinkProgram(m_programID);

int param;
glGetProgramiv(m_programID, GL_LINK_STATUS, &param);
if(param == GL_TRUE) return true;
else return false;
}
void SetData()
{
// matrix 3 x 3
m_vert.fill(0.0f);
m_vert.at(3) = 100.0f;
m_vert.at(6) = 100.0f;
m_vert.at(7) = 100.0f;

// matrix 3 x 3
m_col.fill(0.0f);
m_col.at(0) = 1.0f;
m_col.at(4) = 1.0f;
m_col.at(8) = 1.0f;

glGenBuffers(m_vboID.size(), m_vboID.data());

glBindBuffer(GL_ARRAY_BUFFER, m_vboID.at(0));
glBufferData(GL_ARRAY_BUFFER, m_vert.size() * sizeof(Array::value_type), m_vert.data(), GL_DYNAMIC_DRAW);

glBindBuffer(GL_ARRAY_BUFFER, m_vboID.at(1));
glBufferData(GL_ARRAY_BUFFER, m_col.size() * sizeof(Array::value_type), m_col.data(), GL_DYNAMIC_DRAW);

glBindBuffer(GL_ARRAY_BUFFER, 0);
}
void SetupMVP()
{
int vPort[4];
glGetIntegerv(GL_VIEWPORT, vPort); // gets x, y, width, height of window

// glm::mat4 Projection = glm::perspective(45.0f, 4.0f / 3.0f, 0.1f, 100.0f);
glm::mat4 Projection = glm::ortho<float>(vPort[1], vPort[2], vPort[3], vPort[0], -1.0f, 1.0f);
glm::mat4 View = glm::lookAt(glm::vec3(0,0,1), glm::vec3(0,0,0), glm::vec3(0,1,0));
glm::mat4 Model = glm::mat4(1.0f); // set identity
MVP = Projection * View * Model;
}
void Update()
{
SetupMVP();
glUniformMatrix4fv(m_MVPMatrixID, 1, false, glm::value_ptr(MVP));

glBindBuffer(GL_ARRAY_BUFFER, m_vboID[0]);
glVertexAttribPointer((GLuint)0, 3, GL_FLOAT, GL_FALSE, 0, 0);

glBindBuffer(GL_ARRAY_BUFFER, m_vboID[1]);
glVertexAttribPointer((GLuint)1, 3, GL_FLOAT, GL_FALSE, 0, 0);

glBindBuffer(GL_ARRAY_BUFFER, 0); // not needed but good practice to unbind
}
void DrawScene()
{
HDC hDC = GetDC(m_hWnd);
Update();
//--------------------------------
glClear(GL_COLOR_BUFFER_BIT);

glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);

glDrawArrays(GL_TRIANGLES, 0, 3);

glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
//--------------------------------
glFlush ();
SwapBuffers(hDC);
}
void DestroyScene()
{
glDetachShader(m_programID, m_pVertSh);
glDetachShader(m_programID, m_pFragSh);

if(m_hrc)
{
wglDeleteContext(m_hrc);
m_hrc = NULL;
}
CheckDebugLog();
glDeleteProgram(m_programID);

wglMakeCurrent(NULL, NULL);
}
void CheckDebugLog()
{
GLuint count = 10; // max. num. of messages that will be read from the log
GLsizei bufsize = 2048;

std::vector<GLenum> sources(10);
std::vector<GLenum> types(10);
std::vector<GLuint> ids(10);
std::vector<GLenum> severities(10);
std::vector<GLsizei> lengths(10);
std::vector<GLchar> msglog(bufsize);

GLuint retVal = glGetDebugMessageLogARB(count, bufsize, &sources[0], &types[0], &ids[0], &severities[0], &lengths[0], &msglog[0]);

if(retVal > 0)
{
unsigned int pos = 0;

for(unsigned int i=0; i<retVal; i++)
{
FormatOutput(_T("CDL sources = %i, types = %i, ids = %ui, severities = %i, msglog = %S"), &sources, &types, &ids, &severities, &msglog[pos]);
pos += lengths;

}
}
}

CGLShader m_pVertSh; // Vertex shader
CGLShader m_pFragSh; // Fragment shader

std::array<GLuint, 2> m_vboID; // Vertex Buffer Object IDs
GLuint m_programID; // Program id
GLuint m_MVPMatrixID; // MVP ID

glm::mat4 MVP;
Array m_vert;
Array m_col;

HGLRC m_hrc;
HWND m_hWnd;
};


class MWindow
{
public:
void OnCreate(HWND hwnd)
{
m_render.CreateGLContext(hwnd);
m_render.PrepareScene();
}
void OnDraw()
{
m_render.DrawScene();
}
void OnSize(){ }
OpenGLRenderer m_render;
};

Humm. How about glOrtho2D, then?
I remember something about deprecation, but now I cannot find anything about it. Can somebody elaborate on it? Thanks. :)

All of these functions are deprecated. They manipulated the matrix stack and the matrix stack is no longer used in modern OpenGL. You are supposed to do your own matrix calculations now and set them as uniforms as needed for the shaders. You can either set the values for such matrices yourself (not very difficult since any decent documentation of glOrtho and similar functions will also describe exactly how the created matrix looks like) or use a library like for example GLM.

[quote name='SuperVGA' timestamp='1310050475' post='4832287']
Humm. How about glOrtho2D, then?
I remember something about deprecation, but now I cannot find anything about it. Can somebody elaborate on it? Thanks. :)

All of these functions are deprecated. They manipulated the matrix stack and the matrix stack is no longer used in modern OpenGL. You are supposed to do your own matrix calculations now and set them as uniforms as needed for the shaders. You can either set the values for such matrices yourself (not very difficult since any decent documentation of glOrtho and similar functions will also describe exactly how the created matrix looks like) or use a library like for example GLM.
[/quote]
I'm all for low level, but at some point it's like their taking away your car and giving you a flat tire, some scrap metal and a blow torch. (Seriously, why not include things like GLM, directwrite, etc?)
You would probably want to add functions that manipulate a modelview matrix (to "move" your camera). Making them is pretty easy, you can look at how the functions worked in early OpenGL versions (gltranslatef, glrotatef, glscalef).

The end result would be projectionMatrix * modelviewMatrix * vertex in the shader, or you can calculate projectionMatrix * modelviewMatrix on the CPU since it's just extra calculations if you do it for every vertex.

This topic is closed to new replies.

Advertisement