View more

View more

View more

### Image of the Day Submit

IOTD | Top Screenshots

### The latest, straight to your Inbox.

Subscribe to GameDev.net Direct to receive the latest updates and exclusive content.

# Setup OpenGL like Direct2D

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

9 replies to this topic

### #1Jacob Jingle  Members

Posted 07 July 2011 - 01:03 AM

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

### #2wolfscaptain  Members

Posted 07 July 2011 - 01:23 AM

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

### #3nfries88  Members

Posted 07 July 2011 - 01:54 AM

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/

### #4zacaj  Members

Posted 07 July 2011 - 05:37 AM

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.

### #5Jacob Jingle  Members

Posted 07 July 2011 - 07:22 AM

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;
}


### #6SuperVGA  Members

Posted 07 July 2011 - 08:54 AM

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?

I remember something about deprecation, but now I cannot find anything about it. Can somebody elaborate on it? Thanks.

### #7Jacob Jingle  Members

Posted 08 July 2011 - 02:26 AM

Got it working, thx for help guys. (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);
}

{
public:
{
if(m_ID != 0)
}
{

std::string fileContents;
if(Compile(fileContents))
return true;

return true;
}
{
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();

int 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;
}
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

// VBO

// debug
}
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,
0
};

PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsARB = NULL;
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();

glBindFragDataLocation(m_programID, 0, "out_Color");
::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();
}
{

int 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()
{

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[i], &types[i], &ids[i], &severities[i], &msglog[pos]);
pos += lengths[i];

}
}
}

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;
};


### #8BitMaster  Members

Posted 08 July 2011 - 02:44 AM

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.

### #9Jacob Jingle  Members

Posted 16 July 2011 - 09:00 AM

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.

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?)

### #10wolfscaptain  Members

Posted 16 July 2011 - 11:51 AM

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.

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.