MFC MDI splitter with two OpenGL graphics views are not working - c++

I want to create an application where application View will be divided with OpenGL 3d models in two different views attached to the Childframe using splitter. For this purpose i made a parent class extended from a view class , and inside this class i have initialize all the opengl required code.
for e.g.
#pragma once
#include <gl/gl.h>
#include <gl/glu.h>
#define IL //when you dont want to use image library and you want to load everything by your self then remove this
// COpenGlView view
class COpenGlView : public CView
{
DECLARE_DYNCREATE(COpenGlView)
protected:
void oglBeginRendering();
COpenGlView(); // protected constructor used by dynamic creation
virtual ~COpenGlView();
/*******************/
/* Private Members */
/*******************/
// Window information
CWnd *hWnd;
HDC hdc;
HGLRC hrc;
int m_nPixelFormat;
CRect m_rect;
CRect m_oldWindow;
CRect m_originalRect;
public:
/******************/
/* Public Members */
/******************/
UINT_PTR m_unpTimer;
// View information variables
float m_fLastX;
float m_fLastY;
float m_fPosX;
float m_fPosY;
float m_fZoom;
float m_fRotX;
float m_fRotY;
bool m_bIsMaximized;
float m_fZoomSpeed;
float m_fRotateSpeed;
GLuint texture[1];
void oglCreate(CRect rect, CWnd *parent,CString strWindowName=L"OpenGl");
virtual void oglInitialize(void);
virtual void oglDrawScene(void);
float randFloat(const float& min, const float& max);
int randInt(const int& min, const int& max);
void Reset();
virtual void OnDraw(CDC* pDC); // overridden to draw this view
#ifdef _DEBUG
virtual void AssertValid() const;
#ifndef _WIN32_WCE
virtual void Dump(CDumpContext& dc) const;
#endif
#endif
protected:
DECLARE_MESSAGE_MAP()
public:
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
afx_msg void OnPaint();
afx_msg void OnMouseMove(UINT nFlags, CPoint point);
afx_msg void OnSize(UINT nType, int cx, int cy);
afx_msg void OnTimer(UINT_PTR nIDEvent);
virtual void OnInitialUpdate();
};
here is the cpp
// OpenGlView.cpp : implementation file
//
#include "stdafx.h"
#include "OpenGlView.h"
// COpenGlView
IMPLEMENT_DYNCREATE(COpenGlView, CView)
COpenGlView::COpenGlView()
{
m_fPosX = 0.0f; // X position of model in camera view
m_fPosY = 0.0f; // Y position of model in camera view
m_fZoom = 5.0f; // Zoom on model in camera view
m_fRotX = 0.0f; // Rotation on model in camera view
m_fRotY = 0.0f; // Rotation on model in camera view
m_fZoomSpeed=0.05f;
m_fRotateSpeed = 0.05f;
m_bIsMaximized = false;
}
COpenGlView::~COpenGlView()
{
}
void COpenGlView::Reset()
{
m_fPosX = 0.0f; // X position of model in camera view
m_fPosY = 0.0f; // Y position of model in camera view
m_fZoom = 5.0f; // Zoom on model in camera view
m_fRotX = 0.0f; // Rotation on model in camera view
m_fRotY = 0.0f; // Rotation on model in camera view
m_fZoomSpeed=0.05f;
m_fRotateSpeed = 0.05f;
m_bIsMaximized = false;
}
BEGIN_MESSAGE_MAP(COpenGlView, CView)
ON_WM_CREATE()
ON_WM_PAINT()
ON_WM_MOUSEMOVE()
ON_WM_SIZE()
ON_WM_TIMER()
END_MESSAGE_MAP()
// COpenGlView drawing
void COpenGlView::OnDraw(CDC* pDC)
{
CDocument* pDoc = GetDocument();
// TODO: add draw code here
}
// COpenGlView diagnostics
#ifdef _DEBUG
void COpenGlView::AssertValid() const
{
CView::AssertValid();
}
#ifndef _WIN32_WCE
void COpenGlView::Dump(CDumpContext& dc) const
{
CView::Dump(dc);
}
#endif
#endif //_DEBUG
// COpenGlView message handlers
int COpenGlView::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CView::OnCreate(lpCreateStruct) == -1)
return -1;
return 0;
}
void COpenGlView::OnPaint()
{
//CPaintDC dc(this); // device context for painting
// TODO: Add your message handler code here
// Do not call CView::OnPaint() for painting messages
ValidateRect(NULL);
}
void COpenGlView::OnMouseMove(UINT nFlags, CPoint point)
{
int diffX = (int)(point.x - m_fLastX);
int diffY = (int)(point.y - m_fLastY);
m_fLastX = (float)point.x;
m_fLastY = (float)point.y;
// Left mouse button
if (nFlags & MK_LBUTTON)
{
m_fRotX += (float)m_fRotateSpeed * diffY;
if ((m_fRotX > 360.0f) || (m_fRotX < -360.0f))
{
m_fRotX = 0.0f;
}
m_fRotY += (float)0.5f * diffX;
if ((m_fRotY > 360.0f) || (m_fRotY < -360.0f))
{
m_fRotY = 0.0f;
}
}
// Right mouse button
else if (nFlags & MK_RBUTTON)
{
m_fZoom -= (float)m_fZoomSpeed * diffY;
}
// Middle mouse button
else if (nFlags & MK_MBUTTON)
{
m_fPosX += (float)0.05f * diffX;
m_fPosY -= (float)0.05f * diffY;
}
OnDraw(NULL);
CView::OnMouseMove(nFlags, point);
}
void COpenGlView::OnSize(UINT nType, int cx, int cy)
{
CView::OnSize(nType, cx, cy);
if (0 >= cx || 0 >= cy || nType == SIZE_MINIMIZED) return;
// Map the OpenGL coordinates.
glViewport(0, 0, cx, cy);
// Projection view
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
// Set our current view perspective
gluPerspective(35.0f, (float)cx / (float)cy, 0.01f, 2000.0f);
// Model view
glMatrixMode(GL_MODELVIEW);
switch (nType)
{
// If window resize token is "maximize"
case SIZE_MAXIMIZED:
{
// Get the current window rect
GetWindowRect(m_rect);
// Move the window accordingly
MoveWindow(6, 6, cx - 14, cy - 14);
// Get the new window rect
GetWindowRect(m_rect);
// Store our old window as the new rect
m_oldWindow = m_rect;
break;
}
// If window resize token is "restore"
case SIZE_RESTORED:
{
// If the window is currently maximized
if (m_bIsMaximized)
{
// Get the current window rect
GetWindowRect(m_rect);
// Move the window accordingly (to our stored old window)
MoveWindow(m_oldWindow.left, m_oldWindow.top - 18, m_originalRect.Width() - 4, m_originalRect.Height() - 4);
// Get the new window rect
GetWindowRect(m_rect);
// Store our old window as the new rect
m_oldWindow = m_rect;
}
break;
}
}
}
void COpenGlView::oglBeginRendering()
{
SetTimer(1, 1, 0);
}
void COpenGlView::OnTimer(UINT_PTR nIDEvent)
{
switch (nIDEvent)
{
case 1:
{
// Clear color and depth buffer bits
wglMakeCurrent(hdc, hrc);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Draw OpenGL scene
oglDrawScene();
// Swap buffers
SwapBuffers(hdc);
glFlush();
wglMakeCurrent(NULL, NULL);
break;
}
default:
break;
}
CView::OnTimer(nIDEvent);
}
void COpenGlView::OnInitialUpdate()
{
CView::OnInitialUpdate();
COpenGlView::oglInitialize();
// TODO: Add your specialized code here and/or call the base class
}
void COpenGlView::oglCreate(CRect rect, CWnd *parent,CString strWindowName)
{
CString className = AfxRegisterWndClass(CS_HREDRAW | CS_VREDRAW | CS_OWNDC, NULL, (HBRUSH)GetStockObject(BLACK_BRUSH), NULL);
CreateEx(0, className,strWindowName, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, rect, parent, 0);
// Set initial variables' values
m_oldWindow = rect;
m_originalRect = rect;
hWnd = parent;
GLenum s = glGetError();
}
void COpenGlView::oglInitialize(void)
{
// Initial Setup:
//
static PIXELFORMATDESCRIPTOR pfd =
{
sizeof(PIXELFORMATDESCRIPTOR),
1,
PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER,
PFD_TYPE_RGBA,
32, // bit depth
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
16, // z-buffer depth
0, 0, 0, 0, 0, 0, 0,
};
// Get device context only once.
//hdc = GetDC()->m_hDC;
// Pixel format.
m_nPixelFormat = ChoosePixelFormat(hdc, &pfd);
SetPixelFormat(hdc, m_nPixelFormat, &pfd);
// Create the OpenGL Rendering Context.
hrc = wglCreateContext(hdc);
wglMakeCurrent(hdc, hrc);
// Basic Setup:
//
// Set color to use when clearing the background.
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClearDepth(1.0f);
// Turn on backface culling
glFrontFace(GL_CCW);
glCullFace(GL_BACK);
// Turn on depth testing
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
GLenum a = glGetError();
OnDraw(NULL);
//wglMakeCurrent(NULL, NULL);
}
void COpenGlView::oglDrawScene(void)
{
// Wireframe Mode
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glBegin(GL_QUADS);
// Front Side
glVertex3f( 1.0f, 1.0f, 1.0f);
glVertex3f(-1.0f, 1.0f, 1.0f);
glVertex3f(-1.0f, -1.0f, 1.0f);
glVertex3f( 1.0f, -1.0f, 1.0f);
// Back Side
glVertex3f(-1.0f, -1.0f, -1.0f);
glVertex3f(-1.0f, 1.0f, -1.0f);
glVertex3f( 1.0f, 1.0f, -1.0f);
glVertex3f( 1.0f, -1.0f, -1.0f);
// Top Side
glVertex3f( 1.0f, 1.0f, 1.0f);
glVertex3f( 1.0f, 1.0f, -1.0f);
glVertex3f(-1.0f, 1.0f, -1.0f);
glVertex3f(-1.0f, 1.0f, 1.0f);
// Bottom Side
glVertex3f(-1.0f, -1.0f, -1.0f);
glVertex3f( 1.0f, -1.0f, -1.0f);
glVertex3f( 1.0f, -1.0f, 1.0f);
glVertex3f(-1.0f, -1.0f, 1.0f);
// Right Side
glVertex3f( 1.0f, 1.0f, 1.0f);
glVertex3f( 1.0f, -1.0f, 1.0f);
glVertex3f( 1.0f, -1.0f, -1.0f);
glVertex3f( 1.0f, 1.0f, -1.0f);
// Left Side
glVertex3f(-1.0f, -1.0f, -1.0f);
glVertex3f(-1.0f, -1.0f, 1.0f);
glVertex3f(-1.0f, 1.0f, 1.0f);
glVertex3f(-1.0f, 1.0f, -1.0f);
glEnd();
glLoadIdentity();
glTranslatef(0.0f, 0.0f, -m_fZoom);
glTranslatef(m_fPosX, m_fPosY, 0.0f);
glRotatef(m_fRotX, 1.0f, 0.0f, 0.0f);
glRotatef(m_fRotY, 0.0f, 1.0f, 0.0f);
GLenum a = glGetError();
}
//--------------------------------------------------------
// Get an random integer within a specified range
//--------------------------------------------------------
int COpenGlView::randInt(const int& min, const int& max) {
return ((rand()%(int)(((max) + 1)-(min)))+ (min));
}
//--------------------------------------------------------
// Get a random float within a specified range
//--------------------------------------------------------
float COpenGlView::randFloat(const float& min, const float& max) {
float range = max - min;
float num = range * rand() / RAND_MAX;
return (num + min);
}
then i extended two more view classes from the same class class
C3dRightView : public COpenGlView
and
C3dRightView : public COpenGlView
then in childframe class i added splitter code and called these two classes in the splitter window. The problem is both opengl view code works fine but if i stop one of the initialization of opengl then the other one display. I tried everything and i cant display two different graphical opengl animation in both of these two different views. I have checked the HDC memory map and it seems like both classes are using parent with respect to their dynamic hdc object but if i stop ones code then other view display properly.
detail classes are below
class C3dRightView : public COpenGlView
{
DECLARE_DYNCREATE(C3dRightView)
protected:
GLuint m_left_texture[53];
C3dRightView(); // protected constructor used by dynamic creation
virtual ~C3dRightView();
public:
virtual void OnDraw(CDC* pDC); // overridden to draw this view
#ifdef _DEBUG
virtual void AssertValid() const;
#ifndef _WIN32_WCE
virtual void Dump(CDumpContext& dc) const;
#endif
#endif
protected:
DECLARE_MESSAGE_MAP()
public:
afx_msg void OnPaint();
virtual void OnInitialUpdate();
void oglDrawScene(void);
void oglInitialize(void);
afx_msg void OnTimer(UINT_PTR nIDEvent);
};
void C3dRightView::OnPaint()
{
CPaintDC dc(this); // device context for painting
// TODO: Add your message handler code here
// Do not call CView::OnPaint() for painting messages
}
void C3dRightView::OnInitialUpdate()
{
hdc = C3dRightView::GetDC()->m_hDC;
/** If i open below code then left view stop displaying model **/
COpenGlView::OnInitialUpdate();
oglInitialize();
//-=-=-=-=-=-=-==--=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
oglBeginRendering();
// TODO: Add your specialized code here and/or call the base class
}
void C3dRightView::oglInitialize(void)
{
COpenGlView::oglInitialize();
}
void C3dRightView::oglDrawScene(void)
{
// Wireframe Mode
glShadeModel(GL_SMOOTH);
glClearColor(0.0f, 1.0f, 1.0f, 0.0f);
glLoadIdentity();
//glTranslatef(0.0f, 0.0f, -m_fZoom);//this is for zoom using left mouse click but no placing
glTranslatef(m_fPosX, m_fPosY,-m_fZoom); // this is for placing + zooming using middle scroll button mouse click
glRotatef(m_fRotX, 1.0f, 0.0f, 0.0f);//these two for mouse movement
glRotatef(m_fRotY, 0.0f, 1.0f, 0.0f);
glRotated(90,0.0f, 0.0f, -1.0f);
glRotatef(180,1.0f,0,0.0f);
GLenum a = glGetError();
glBegin(GL_TRIANGLES); // Start Drawing A Triangle
glColor3f(1.0f,0.0f,0.0f); // Red
glVertex3f( 0.0f, 1.0f, 0.0f); // Top Of Triangle (Front)
glColor3f(0.0f,1.0f,0.0f); // Green
glVertex3f(-1.0f,-1.0f, 1.0f); // Left Of Triangle (Front)
glColor3f(0.0f,0.0f,1.0f); // Blue
glVertex3f( 1.0f,-1.0f, 1.0f); // Right Of Triangle (Front)
glColor3f(1.0f,0.0f,0.0f); // Red
glVertex3f( 0.0f, 1.0f, 0.0f); // Top Of Triangle (Right)
glColor3f(0.0f,0.0f,1.0f); // Blue
glVertex3f( 1.0f,-1.0f, 1.0f); // Left Of Triangle (Right)
glColor3f(0.0f,1.0f,0.0f); // Green
glVertex3f( 1.0f,-1.0f, -1.0f); // Right Of Triangle (Right)
glColor3f(1.0f,0.0f,0.0f); // Red
glVertex3f( 0.0f, 1.0f, 0.0f); // Top Of Triangle (Back)
glColor3f(0.0f,1.0f,0.0f); // Green
glVertex3f( 1.0f,-1.0f, -1.0f); // Left Of Triangle (Back)
glColor3f(0.0f,0.0f,1.0f); // Blue
glVertex3f(-1.0f,-1.0f, -1.0f); // Right Of Triangle (Back)
glColor3f(1.0f,0.0f,0.0f); // Red
glVertex3f( 0.0f, 1.0f, 0.0f); // Top Of Triangle (Left)
glColor3f(0.0f,0.0f,1.0f); // Blue
glVertex3f(-1.0f,-1.0f,-1.0f); // Left Of Triangle (Left)
glColor3f(0.0f,1.0f,0.0f); // Green
glVertex3f(-1.0f,-1.0f, 1.0f); // Right Of Triangle (Left)
glEnd();
}
the second view file is like this
class C3dLeftView : public COpenGlView
{
DECLARE_DYNCREATE(C3dLeftView)
protected:
GLuint m_left_texture[53];
C3dLeftView(); // protected constructor used by dynamic creation
virtual ~C3dLeftView();
public:
virtual void OnDraw(CDC* pDC); // overridden to draw this view
#ifdef _DEBUG
virtual void AssertValid() const;
#ifndef _WIN32_WCE
virtual void Dump(CDumpContext& dc) const;
#endif
#endif
protected:
DECLARE_MESSAGE_MAP()
public:
afx_msg void OnPaint();
virtual void OnInitialUpdate();
void oglDrawScene(void);
void oglInitialize(void);
afx_msg void OnTimer(UINT_PTR nIDEvent);
};
void C3dLeftView::OnPaint()
{
CPaintDC dc(this); // device context for painting
// TODO: Add your message handler code here
// Do not call CView::OnPaint() for painting messages
}
void C3dLeftView::OnInitialUpdate()
{
hdc = C3dLeftView::GetDC()->m_hDC;
COpenGlView::OnInitialUpdate();
oglInitialize();
oglBeginRendering();
// TODO: Add your specialized code here and/or call the base class
}
void C3dLeftView::oglInitialize(void)
{
COpenGlView::oglInitialize();
}
void C3dLeftView::oglDrawScene(void)
{
glShadeModel(GL_SMOOTH);
glClearColor(0.0f, 1.0f, 0.0f, 1.0f);
glLoadIdentity();
//glTranslatef(0.0f, 0.0f, -m_fZoom);//this is for zoom using left mouse click but no placing
glTranslatef(m_fPosX, m_fPosY,-m_fZoom); // this is for placing + zooming using middle scroll button mouse click
glRotatef(m_fRotX, 1.0f, 0.0f, 0.0f);//these two for mouse movement
glRotatef(m_fRotY, 0.0f, 1.0f, 0.0f);
glRotated(90,0.0f, 0.0f, -1.0f);
glRotatef(180,1.0f,0,0.0f);
GLenum a = glGetError();
glBegin(GL_TRIANGLES); // Start Drawing A Triangle
glColor3f(1.0f,0.0f,0.0f); // Red
glVertex3f( 0.0f, 1.0f, 0.0f); // Top Of Triangle (Front)
glColor3f(0.0f,1.0f,0.0f); // Green
glVertex3f(-1.0f,-1.0f, 1.0f); // Left Of Triangle (Front)
glColor3f(0.0f,0.0f,1.0f); // Blue
glVertex3f( 1.0f,-1.0f, 1.0f); // Right Of Triangle (Front)
glColor3f(1.0f,0.0f,0.0f); // Red
glVertex3f( 0.0f, 1.0f, 0.0f); // Top Of Triangle (Right)
glColor3f(0.0f,0.0f,1.0f); // Blue
glVertex3f( 1.0f,-1.0f, 1.0f); // Left Of Triangle (Right)
glColor3f(0.0f,1.0f,0.0f); // Green
glVertex3f( 1.0f,-1.0f, -1.0f); // Right Of Triangle (Right)
glColor3f(1.0f,0.0f,0.0f); // Red
glVertex3f( 0.0f, 1.0f, 0.0f); // Top Of Triangle (Back)
glColor3f(0.0f,1.0f,0.0f); // Green
glVertex3f( 1.0f,-1.0f, -1.0f); // Left Of Triangle (Back)
glColor3f(0.0f,0.0f,1.0f); // Blue
glVertex3f(-1.0f,-1.0f, -1.0f); // Right Of Triangle (Back)
glColor3f(1.0f,0.0f,0.0f); // Red
glVertex3f( 0.0f, 1.0f, 0.0f); // Top Of Triangle (Left)
glColor3f(0.0f,0.0f,1.0f); // Blue
glVertex3f(-1.0f,-1.0f,-1.0f); // Left Of Triangle (Left)
glColor3f(0.0f,1.0f,0.0f); // Green
glVertex3f(-1.0f,-1.0f, 1.0f); // Right Of Triangle (Left)
glEnd();
/*************************************************************************************/
}
if comment below code inside initialupdate function of the view then other view codes works fine.
COpenGlView::OnInitialUpdate();
oglInitialize();
some how the initialupdate code of the parent code works for its one child rather than two of them.

Edit: no the reason can not be wglMakeCurrent() like I initially thought, you seem to call it enough.
The reason may be that you call your oglInitialize() too lot of times however. It depends how you create your views and splitters, but that code you did not post. One way to fix it is to limit how lot of times your views will actually "initially update".
Initialize your hdc member to 0 in constructor (actually always initialize all members in constructors):
COpenGlView::COpenGlView()
{
hdc = 0;
// ... etc your stuff
}
Do your ogl initialization only once when hdc is 0:
void C3dRightView::OnInitialUpdate()
{
if ( hdc == 0 )
{
hdc = GetDC()->m_hDC;
COpenGlView::OnInitialUpdate();
oglBeginRendering();
}
}
Here too:
void C3dLeftView::OnInitialUpdate()
{
if ( hdc == 0 )
{
hdc = GetDC()->m_hDC;
COpenGlView::OnInitialUpdate();
oglBeginRendering();
}
}
That should work I trust.
Edit2: Tried your code. C3dRightView::OnInitialUpdate was not like I posted above. I am not exactly sure what messes up the initialization. For example following fix to CChildFrame::OnCreateClient seems to work:
if (!m_wndSplitter.CreateView( 0, 1, RUNTIME_CLASS(C3dRightView), CSize(cr.Width()/2, cr.Height()), pContext))
{
MessageBox(L"Error setting up splitter frames!", L"Init Error!", MB_OK | MB_ICONERROR);
return FALSE;
}
// had to add this line here:
m_wndSplitter.GetPane( 0, 1 )->SendMessage(WM_INITIALUPDATE);
return TRUE;

Even though it might be late, but here is my answer which can help you in future :)
in Ontimer function call pdoc->UpdateAll(NULL,NULL,NULL) function. pdoc is pointer to your documents class. It will request all views to update, and you will get both windows working :).

Related

Why multiple function call not working in Opengl?

I'm try to use different function to make various object and call by one function like display() in my Opengl project. But It's not working, when I called two function then show me a function another one is not showing, I don't know why,
I have tried this way:
#include <windows.h> // for MS Windows
#include <GL/glut.h> // GLUT, include glu.h and gl.h
#include <math.h>
void box() {
glClearColor(1.0f, 1.0f, 1.0f, 1.0f); // Set background color to black and opaque
glClear(GL_COLOR_BUFFER_BIT); // Clear the color buffer (background)
// Draw a Red 1x1 Square centered at origin
glBegin(GL_POLYGON); // Each set of 4 vertices form a quad
glColor3f(1.0f, 0.0f, 0.0f); // Red
glVertex2f(-0.9f, -0.7f);
glVertex2f(-0.9f, 0.7f);
glVertex2f(0.9f, 0.7f);
glVertex2f(0.9f, -0.7f); // x, y
glEnd();
glFlush(); // Render now
}
void triangle()
{
glClearColor(1.0f, 1.0f, 1.0f, 1.0f); // Set background color to black and opaque
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_POLYGON); // Each set of 4 vertices form a quad
glColor3f(0.0f, 1.0f, 0.0f); // green
glVertex2f(-0.9f, -0.7f);
glVertex2f(-0.4f, 0.7f);
glVertex2f(0.1f, -0.7f); // x, y
glEnd();
glFlush(); // Render now
}
void display()
{
box();
triangle();
}
/* Main function: GLUT runs as a console application starting at main() */
int main(int argc, char** argv) {
glutInit(&argc, argv);
glutInitWindowSize(1000, 600);// Set the window's initial width & height
glutCreateWindow("OpenGL Setup Test");
//gluOrtho2D(-0.1,0.7,-0.1,0.3); // Create a window with the given title
//glutInitWindowSize(500, 500);// Set the window's initial width & height
glutDisplayFunc(display);// Register display callback handler for window re-paint
glutMainLoop(); // Enter the event-processing loop
return 0;
}
Any suggestion please.
You are clearing the buffer before rendering each of the shapes, thus erasing the previous shape you just drew. Instead you should clear it only once per display. Same goes with glFlush:
void box() {
// Draw a Red 1x1 Square centered at origin
glBegin(GL_POLYGON);
glColor3f(1.0f, 0.0f, 0.0f); // Red
glVertex2f(-0.9f, -0.7f);
glVertex2f(-0.9f, 0.7f);
glVertex2f(0.9f, 0.7f);
glVertex2f(0.9f, -0.7f); // x, y
glEnd();
}
void triangle()
{
glBegin(GL_POLYGON);
glColor3f(0.0f, 1.0f, 0.0f); // green
glVertex2f(-0.9f, -0.7f);
glVertex2f(-0.4f, 0.7f);
glVertex2f(0.1f, -0.7f); // x, y
glEnd();
}
void display()
{
glClearColor(1.0f, 1.0f, 1.0f, 1.0f); // Set background color to white and opaque
glClear(GL_COLOR_BUFFER_BIT); // Clear the color buffer (background)
box();
triangle();
glFlush(); // Render now
}

OpenGL and Multithreading

I'm having some troubles with OpenGL and multithreading. The thing is I cannot understand why I have this issue.
I'm using MACOS (the includes are therefore going to be different if you try my code).
Here the simple program that I manage to run without any problem.
char title[] = "3D Shapes with animation";
GLfloat anglePyramid = 0.0f; // Rotational angle for pyramid [NEW]
GLfloat angleCube = 0.0f; // Rotational angle for cube [NEW]
int refreshMills = 15; // refresh interval in milliseconds [NEW]
bool serverHasInput = false ;
float matrix[16] = {0.7599139,0.0,-0.65002376,0.0,-0.45789394,0.709777,-0.5353035,0.0,0.4613719,0.70442647,0.5393694,0.0,0.0,0.0,0.0,1.0};
float moveX = 0;
float moveY = 0;
pthread_mutex_t mymutex ;
pthread_cond_t mycondition ;
/* Initialize OpenGL Graphics */
void initGL() {
glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Set background color to black and opaque
glClearDepth(1.0f); // Set background depth to farthest
glEnable(GL_DEPTH_TEST); // Enable depth testing for z-culling
glDepthFunc(GL_LEQUAL); // Set the type of depth-test
glShadeModel(GL_SMOOTH); // Enable smooth shading
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // Nice perspective corrections
}
/* Handler for window-repaint event. Called back when the window first appears and
whenever the window needs to be re-painted. */
void display() {
//while(matrixSet == true){
// sleep(0.01);
//}
pthread_mutex_lock(&mymutex);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear color and depth buffers
glMatrixMode(GL_MODELVIEW); // To operate on model-view matrix
// Render a color-cube consisting of 6 quads with different colors
glLoadIdentity(); // Reset the model-view matrix
glTranslatef(1.5f, 0.0f, -7.0f); // Move right and into the screen
glRotatef(angleCube, 1.0f, 1.0f, 1.0f); // Rotate about (1,1,1)-axis [NEW]
glMultMatrixf(matrix);
pthread_mutex_unlock(&mymutex);
glBegin(GL_QUADS); // Begin drawing the color cube with 6 quads
// Top face (y = 1.0f)
// Define vertices in counter-clockwise (CCW) order with normal pointing out
glColor3f(0.0f, 1.0f, 0.0f); // Green
glVertex3f( 1.0f, 1.0f, -1.0f);
glVertex3f(-1.0f, 1.0f, -1.0f);
glVertex3f(-1.0f, 1.0f, 1.0f);
glVertex3f( 1.0f, 1.0f, 1.0f);
// Bottom face (y = -1.0f)
glColor3f(1.0f, 0.5f, 0.0f); // Orange
glVertex3f( 1.0f, -1.0f, 1.0f);
glVertex3f(-1.0f, -1.0f, 1.0f);
glVertex3f(-1.0f, -1.0f, -1.0f);
glVertex3f( 1.0f, -1.0f, -1.0f);
// Front face (z = 1.0f)
glColor3f(1.0f, 0.0f, 0.0f); // Red
glVertex3f( 1.0f, 1.0f, 1.0f);
glVertex3f(-1.0f, 1.0f, 1.0f);
glVertex3f(-1.0f, -1.0f, 1.0f);
glVertex3f( 1.0f, -1.0f, 1.0f);
// Back face (z = -1.0f)
glColor3f(1.0f, 1.0f, 0.0f); // Yellow
glVertex3f( 1.0f, -1.0f, -1.0f);
glVertex3f(-1.0f, -1.0f, -1.0f);
glVertex3f(-1.0f, 1.0f, -1.0f);
glVertex3f( 1.0f, 1.0f, -1.0f);
// Left face (x = -1.0f)
glColor3f(0.0f, 0.0f, 1.0f); // Blue
glVertex3f(-1.0f, 1.0f, 1.0f);
glVertex3f(-1.0f, 1.0f, -1.0f);
glVertex3f(-1.0f, -1.0f, -1.0f);
glVertex3f(-1.0f, -1.0f, 1.0f);
// Right face (x = 1.0f)
glColor3f(1.0f, 0.0f, 1.0f); // Magenta
glVertex3f(1.0f, 1.0f, -1.0f);
glVertex3f(1.0f, 1.0f, 1.0f);
glVertex3f(1.0f, -1.0f, 1.0f);
glVertex3f(1.0f, -1.0f, -1.0f);
glEnd(); // End of drawing color-cube
glutSwapBuffers(); // Swap the front and back frame buffers (double buffering)
// Update the rotational angle after each refresh [NEW]
//anglePyramid += 1.2f;
//angleCube -= 0.15f;
pthread_cond_signal(&mycondition);
pthread_mutex_unlock(&mymutex);
}
/* Called back when timer expired [NEW] */
void timer(int value) {
glutPostRedisplay(); // Post re-paint request to activate display()
glutTimerFunc(refreshMills, timer, 0); // next timer call milliseconds later
}
/* Handler for window re-size event. Called back when the window first appears and
whenever the window is re-sized with its new width and height */
void reshape(GLsizei width, GLsizei height) { // GLsizei for non-negative integer
// Compute aspect ratio of the new window
if (height == 0) height = 1; // To prevent divide by 0
GLfloat aspect = (GLfloat)width / (GLfloat)height;
// Set the viewport to cover the new window
glViewport(0, 0, width, height);
// Set the aspect ratio of the clipping volume to match the viewport
glMatrixMode(GL_PROJECTION); // To operate on the Projection matrix
glLoadIdentity(); // Reset
// Enable perspective projection with fovy, aspect, zNear and zFar
gluPerspective(45.0f, aspect, 0.1f, 100.0f);
}
void keyPressed (unsigned char key, int x, int y) {
if (key == 'y'){
moveY += 0.5;
cout << "y" << endl ;
}
}
/* Main function: GLUT runs as a console application starting at main() */
int main(int argc, char* argv[]) {
glutInit(&argc, argv); // Initialize GLUT
glutInitDisplayMode(GLUT_DOUBLE); // Enable double buffered mode
glutInitWindowSize(640, 480); // Set the window's initial width & height
glutInitWindowPosition(50, 50); // Position the window's initial top-left corner
glutCreateWindow(title); // Create window with the given title
glutDisplayFunc(display); // Register callback handler for window re-paint event
glutReshapeFunc(reshape); // Register callback handler for window re-size event
initGL(); // Our own OpenGL initialization
glutTimerFunc(0, timer, 0); // First timer call immediately [NEW]
glutKeyboardFunc(keyPressed); // Tell GLUT to use the method "keyPressed" for key presses
glutMainLoop(); // Enter the infinite event-processing loop
}
So this is my basic code that works like a charm.
However, when I'm trying to create a thread to make it run I cannot get theKeyboardInput anymmore as well as some other aspects that are wrong (cannot clic on the X to exit the window for instace).
Here is my code:
My OpenGL functions are all the same except for this part:
/* Main function: GLUT runs as a console application starting at main() */
void* launch(void* args) {
mainArg* arg = (mainArg*) args ;
glutInit(arg->argc, &arg->argv); // Initialize GLUT
And here is how I create the threads:
//the thread function
void *connection_handler(void *);
void * connection_thread(void *);
void * input_thread(void *);
void test();
int main(int argc , char *argv[])
{
//Draw* d = new Draw() ;
pthread_t server_thread ;
pthread_t drawing_thread ;
pthread_t input_thread ;
mainArg args ;
args.argc = &argc ;
args.argv = *argv ;
pthread_mutex_init (&mymutex, NULL);
pthread_cond_init (&mycondition, NULL);
cout << "Begin" << endl ;
if( pthread_create( &server_thread , NULL , &connection_thread , NULL) != 0)
{
cout << "could not create Connection thread" << endl ;
return 1;
}
/*if( pthread_create( &input_thread , NULL , &connection_thread , NULL) != 0)
{
cout << "could not create input thread" << endl ;
return 1;
}*/
if( pthread_create( &drawing_thread , NULL , &launch , &args) != 0)
{
perror("could not create Drawing thread");
return 1;
}
//while(1);
pthread_join(server_thread, NULL);
pthread_join(drawing_thread,NULL);
Would you happen to know what's wrong here? Cause I've been looking at it for days now and I can't seem to find an answer.
EDIT: I am not sharing the OpenGL context or anything that has to be a part of the OGL rendering on an other thread. My other thread is only a server communication with other devices.
EDIT2: I saw here a while ago that not having OGL rendering on the main thread should not be an issue OpenGL Rendering in a secondary thread
So #user1118321 was correct.
There are absolutely no problem to try and do the rendering on a background thread.
However, GLUT will not be able to access the information of the OS window (i.e keyboard press, exit window ... ) if it is done that way. Still, if the purpose of the rendering thread is just to render, no problem at all to put it on a background thread.
Hope it helps other people too.

Understanding GL coordinates - setting perspective and using gluLookAt

I'm using QGlWidget to draw a couple of points. The problems I'm having is that I seem to fail to set up the perspective properly and establish correct view on the points. I must be misunderstanding the coordinates somewhere or doing something else stupid, but after reading a bunch of guides and tutotrials I'm still stuck. The screen is black, no points. Here's the code:
void CGLWidget::initializeGL()
{
glEnable(GL_DEPTH_TEST);
glDisable(GL_ALPHA_TEST);
glDisable(GL_BLEND);
glEnable(GL_POINT_SPRITE);
glClearColor(0, 0, 0, 1);
assert (glGetError() == GL_NO_ERROR);
}
void CGLWidget::resizeGL(int w, int h)
{
glViewport(-w/2, -h/2, w/2, h <= 0 ? 1 : h/2);
glMatrixMode(GL_PROJECTION); //Switch to setting the camera perspective
//Set the camera perspective
glLoadIdentity(); //Reset the camera
gluPerspective(80.0, //The camera FoV
w/(double)h, //The width-to-height ratio
1, //The near z clipping coordinate
100); //The far z clipping coordinate
}
void CGLWidget::paintGL()
{
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(0, 0, 5, 0, 0, 0, 0, 1, 0);
glLoadIdentity();
glColor3i(255, 255, 255);
glBegin(GL_POINTS);
glVertex3d(0,0, -2);
glVertex3d(0,0, -3);
glVertex3d(0,0, +3);
glVertex3d(0,0, 0);
glVertex3f(-0.75f, -0.25f, -5.0f);
glEnd();
assert (glGetError() == GL_NO_ERROR);
}
I've tried manipulating z coordinate of the "eye" in gluLookAt to no avail, so I must be getting something else wrong.
To develop a more clear understanding of how gluPerspective() and gluLookAt() works, I recommend playing with the tutorials from Nate Robins, more specifically the projection demo.
Trust me, this is the droid you are looking for!
Anyway, a few days ago I wrote a spiced up version of Nehe lesson 5 (3D Shapes) in Qt:
GLWidget.cpp:
#include "GLWidget.h"
#include <iostream>
#include <QKeyEvent>
#include <QTimer>
GLWidget::GLWidget(QWidget *parent)
: QGLWidget(parent)
{
angle_tri = 0.f;
angle_quad = 0.f;
_eye_x = 0.f;
_eye_y = 0.f;
_mouse_is_moving = false;
_width = 0;
_height = 0;
}
GLWidget::~GLWidget()
{
}
void GLWidget::_tick()
{
update(); // triggers paintGL()
QTimer::singleShot(33, this, SLOT(_tick()));
}
void GLWidget::initializeGL()
{
// glShadeModel(GL_SMOOTH); // Enable Smooth Shading
glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Black Background
// glClearDepth(1.0f); // Depth Buffer Setup
// glEnable(GL_DEPTH_TEST); // Enables Depth Testing
// glDepthFunc(GL_LEQUAL); // The Type Of Depth Testing To Do
// glEnable ( GL_COLOR_MATERIAL );
// glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
_tick();
}
void GLWidget::paintGL()
{
if (_mouse_is_moving)
{
glMatrixMode ( GL_PROJECTION ); // Select The Projection Matrix
glLoadIdentity ( ); // Reset The Projection Matrix
gluPerspective ( 60, ( float ) _width / ( float ) _height, 1.0, 50.0 );
gluLookAt(0.0, 0.0, 2.0, // eye
_eye_x, _eye_y, 0.0, // center
0.0, 1.0, 0.0); // up
std::cout << "paintGL: eye " << _eye_x << "," << _eye_y << std::endl;
}
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear Screen And Depth Buffer
glMatrixMode ( GL_MODELVIEW ); // Select The Model View Matrix
glLoadIdentity(); // Reset The Current Modelview Matrix
glPushMatrix();
glTranslatef(-1.5f,0.0f,-6.0f); // Move Left 1.5 Units And Into The Screen 6.0
glRotatef(angle_tri,0.0f,1.0f,0.0f); // Rotate The Triangle On The Y axis
glBegin(GL_TRIANGLES); // Drawing Using Triangles
glColor3f(1.0f,0.0f,0.0f); // Red
glVertex3f( 0.0f, 1.0f, 0.0f); // Top Of Triangle (Front)
glColor3f(0.0f,1.0f,0.0f); // Green
glVertex3f(-1.0f,-1.0f, 1.0f); // Left Of Triangle (Front)
glColor3f(0.0f,0.0f,1.0f); // Blue
glVertex3f( 1.0f,-1.0f, 1.0f); // Right Of Triangle (Front)
glColor3f(1.0f,0.0f,0.0f); // Red
glVertex3f( 0.0f, 1.0f, 0.0f); // Top Of Triangle (Right)
glColor3f(0.0f,0.0f,1.0f); // Blue
glVertex3f( 1.0f,-1.0f, 1.0f); // Left Of Triangle (Right)
glColor3f(0.0f,1.0f,0.0f); // Green
glVertex3f( 1.0f,-1.0f, -1.0f); // Right Of Triangle (Right)
glColor3f(1.0f,0.0f,0.0f); // Red
glVertex3f( 0.0f, 1.0f, 0.0f); // Top Of Triangle (Back)
glColor3f(0.0f,1.0f,0.0f); // Green
glVertex3f( 1.0f,-1.0f, -1.0f); // Left Of Triangle (Back)
glColor3f(0.0f,0.0f,1.0f); // Blue
glVertex3f(-1.0f,-1.0f, -1.0f); // Right Of Triangle (Back)
glColor3f(1.0f,0.0f,0.0f); // Red
glVertex3f( 0.0f, 1.0f, 0.0f); // Top Of Triangle (Left)
glColor3f(0.0f,0.0f,1.0f); // Blue
glVertex3f(-1.0f,-1.0f,-1.0f); // Left Of Triangle (Left)
glColor3f(0.0f,1.0f,0.0f); // Green
glVertex3f(-1.0f,-1.0f, 1.0f); // Right Of Triangle (Left)
glEnd(); // Finished Drawing The Triangle
glLoadIdentity(); // Reset The Current Modelview Matrix
glTranslatef(1.5f,0.0f,-9.0f); // Move Right 1.5 Units And Into The Screen 6.0
glRotatef(angle_quad,1.0f,0.0f,0.0f); // Rotate The Quad On The X axis
glBegin(GL_QUADS); // Draw A Quad
glColor3f(0.0f,1.0f,0.0f); // Set The Color To Green
glVertex3f( 1.0f, 1.0f,-1.0f); // Top Right Of The Quad (Top)
glVertex3f(-1.0f, 1.0f,-1.0f); // Top Left Of The Quad (Top)
glVertex3f(-1.0f, 1.0f, 1.0f); // Bottom Left Of The Quad (Top)
glVertex3f( 1.0f, 1.0f, 1.0f); // Bottom Right Of The Quad (Top)
glColor3f(1.0f,0.5f,0.0f); // Set The Color To Orange
glVertex3f( 1.0f,-1.0f, 1.0f); // Top Right Of The Quad (Bottom)
glVertex3f(-1.0f,-1.0f, 1.0f); // Top Left Of The Quad (Bottom)
glVertex3f(-1.0f,-1.0f,-1.0f); // Bottom Left Of The Quad (Bottom)
glVertex3f( 1.0f,-1.0f,-1.0f); // Bottom Right Of The Quad (Bottom)
glColor3f(1.0f,0.0f,0.0f); // Set The Color To Red
glVertex3f( 1.0f, 1.0f, 1.0f); // Top Right Of The Quad (Front)
glVertex3f(-1.0f, 1.0f, 1.0f); // Top Left Of The Quad (Front)
glVertex3f(-1.0f,-1.0f, 1.0f); // Bottom Left Of The Quad (Front)
glVertex3f( 1.0f,-1.0f, 1.0f); // Bottom Right Of The Quad (Front)
glColor3f(1.0f,1.0f,0.0f); // Set The Color To Yellow
glVertex3f( 1.0f,-1.0f,-1.0f); // Bottom Left Of The Quad (Back)
glVertex3f(-1.0f,-1.0f,-1.0f); // Bottom Right Of The Quad (Back)
glVertex3f(-1.0f, 1.0f,-1.0f); // Top Right Of The Quad (Back)
glVertex3f( 1.0f, 1.0f,-1.0f); // Top Left Of The Quad (Back)
glColor3f(0.0f,0.0f,1.0f); // Set The Color To Blue
glVertex3f(-1.0f, 1.0f, 1.0f); // Top Right Of The Quad (Left)
glVertex3f(-1.0f, 1.0f,-1.0f); // Top Left Of The Quad (Left)
glVertex3f(-1.0f,-1.0f,-1.0f); // Bottom Left Of The Quad (Left)
glVertex3f(-1.0f,-1.0f, 1.0f); // Bottom Right Of The Quad (Left)
glColor3f(1.0f,0.0f,1.0f); // Set The Color To Violet
glVertex3f( 1.0f, 1.0f,-1.0f); // Top Right Of The Quad (Right)
glVertex3f( 1.0f, 1.0f, 1.0f); // Top Left Of The Quad (Right)
glVertex3f( 1.0f,-1.0f, 1.0f); // Bottom Left Of The Quad (Right)
glVertex3f( 1.0f,-1.0f,-1.0f); // Bottom Right Of The Quad (Right)
glEnd(); // Done Drawing The Quad
glPopMatrix();
angle_tri += 3.2f; // Increase The Rotation Variable For The Triangle ( NEW )
angle_quad -= 3.15f; // Decrease The Rotation Variable For The Quad ( NEW )
}
void GLWidget::resizeGL( int w, int h)
{
_width = w;
_height = h;
glViewport ( 0, 0, w, h );
glMatrixMode ( GL_PROJECTION ); // Select The Projection Matrix
glLoadIdentity ( ); // Reset The Projection Matrix
if ( h==0 ) // Calculate The Aspect Ratio Of The Window
gluPerspective ( 60, ( float ) w, 1.0, 50.0 );
else
gluPerspective ( 60, ( float ) w / ( float ) h, 1.0, 50.0 );
gluLookAt(0.0, 0.0, 2.0, // eye
0.0, 0.0, 0.0, // center
0.0, 1.0, 0.0); // up
glMatrixMode ( GL_MODELVIEW ); // Select The Model View Matrix
glLoadIdentity ( ); // Reset The Model View Matrix
}
void GLWidget::mousePressEvent(QMouseEvent *event)
{
std::cout << "mousePressEvent:" << std::endl;
_mouse_is_moving = true;
}
void GLWidget::mouseReleaseEvent(QMouseEvent *event)
{
std::cout << "mouseReleaseEvent:" << std::endl;
_mouse_is_moving = false;
}
void GLWidget::mouseMoveEvent(QMouseEvent *event)
{
if (_mouse_x == 0)
_mouse_x = event->pos().x();
if (_mouse_y == 0)
_mouse_y = event->pos().y();
std::cout << "mouseMoveEvent: " << event->pos().x() << "," << event->pos().y() << std::endl;
if (event->pos().x() > _mouse_x)
{
_eye_x += 0.10;
}
else if (event->pos().x() < _mouse_x)
{
_eye_x -= 0.10;
}
if (event->pos().y() > _mouse_y)
{
_eye_y += 0.10;
}
else if (event->pos().y() < _mouse_y)
{
_eye_y -= 0.10;
}
_mouse_x = event->pos().x();
_mouse_y = event->pos().y();
}
GLWidget.h:
#include <QGLWidget>
class GLWidget : public QGLWidget
{
Q_OBJECT
public:
explicit GLWidget(QWidget* parent = 0);
virtual ~GLWidget();
/* OpenGL initialization, viewport resizing, and painting */
void initializeGL();
void paintGL();
void resizeGL( int width, int height);
/* enable the user to interact directly with the scene using the mouse */
void mousePressEvent(QMouseEvent *event);
void mouseReleaseEvent(QMouseEvent *event);
void mouseMoveEvent(QMouseEvent *event);
private:
float angle_tri; // Angle For The Triangle
float angle_quad; // Angle For The Quad
float _eye_x;
float _eye_y;
bool _mouse_is_moving;
int _mouse_x;
int _mouse_y;
int _width;
int _height;
protected slots:
void _tick();
};
main.cpp:
#include <QApplication>
#include "glwidget.h"
int main(int argc, char* argv[])
{
QApplication app(argc, argv);
GLWidget gl_widget;
gl_widget.show();
return app.exec();
}
I think what you've got there looks mostly correct, though your glViewport parameters look wrong. glViewport is supposed to be (left, bottom, width, height), but you're using something else.
Set glViewport to glViewport(0,0,width,height);.
For more explanation:
After transformation by modelViewProjection matrix (and perspective divide), all coordinates lie in what's known as Normalized Device Coordinates (abbreviated as NDC). NDC ranges from -1 to 1 on each axis, which puts (0,0,0) right in the center of the viewing region.
When your point lies directly in front of the camera, this gets transformed to xy (0,0) in normalized device coordinates.
If you look at the formulas on glViewport, these map NDC to the actual pixels on the screen.
So if you supply (0,0,1024,768) as the parameters, it gets mapped as the following:
screen X = ( Xnd + 1 ) ( width / 2) + x;
screen Y = ( Ynd + 1 ) ( height / 2) + y;
Substituting our glViewport values:
screen X = ( 0 + 1 ) ( 1024 / 2) + 0;
screen Y = ( 0 + 1 ) ( 768 / 2) + 0;
screen X = ( 1 ) ( 1024 / 2) ;
screen Y = ( 1 ) ( 768 / 2) ;
screen X = ( 1 ) ( 512 ) ;
screen Y = ( 1 ) ( 384 ) ;
screen X = 512 ; //center of screen X
screen Y = 384 ; //center of screen Y
Your near value is quite large to be honest, usually this has to be a low value so that if you have a 2D environment as your example you can still render objects. I would say a 0.1(0.5) for the near value of the perspective should go nicely.
Note: If you set the near value to be a big number your geometry will be clipped by the camera (perspective frustum).

D3D Text uses up too much RAM..?

I have a VC++ DirectX application that renders a 3D cube, with the camera that can be moved around with W,A,S,D keys and mouse. In the top-left corner, a text shows the current camera coordinates; however, after 10-15 seconds, the allocated RAM and CPU increase to 1.6Gb and almost 50% of the total.. This happens only if I enable the text (even if the movement is still "FLOPS-based", so it's anyway a little "rusty" sometimes, with or without text print).
I guess having the text to be rendered over and over again causes the RAM to fill up because it won't "release" the previously written one..?
Here's my code (a bit long, I included everything 'cuz maybe is something else - however, I don't recommend you to run it since it could, in the worst case, freeze all the RAM up!):
#include <windows.h> // form header
#include <windowsx.h> // form header 2
#include <d3d9.h> // Direct3D9 header
#include <d3dx9.h> // DirectX9 header
#include <conio.h>
#include <dinput.h> // DirectInput header
#include <math.h>
#include <string>
using namespace std;
const double PI = 3.1415926;
// include the Direct3D Library file
#pragma comment (lib, "d3d9.lib")
#pragma comment (lib, "d3dx9.lib")
// include the DirectInput8 Library file
#pragma comment (lib, "dinput8.lib")
#pragma comment (lib, "dxguid.lib")
// define the screen resolution
#define SCREEN_WIDTH 1024
#define SCREEN_HEIGHT 768
// global declarations
LPDIRECT3D9 d3d; // the pointer to our Direct3D interface
LPDIRECT3DDEVICE9 d3ddev; // the pointer to the device class
LPDIRECT3DVERTEXBUFFER9 v_buffer = NULL; // the pointer to the vertex buffer
LPDIRECT3DINDEXBUFFER9 i_buffer; // the pointer to an index buffer
LPDIRECT3DTEXTURE9 texture; // declare a texture
LPDIRECT3DTEXTURE9 bump;
LPDIRECTINPUT8 din; // the pointer to our DirectInput interface
LPDIRECTINPUTDEVICE8 dinkeyboard; // the pointer to the keyboard device
LPDIRECTINPUTDEVICE8 dinmouse; // the pointer to the mouse device
BYTE keystate[256]; // the storage for the key-information
DIMOUSESTATE mousestate; // the storage for the mouse-information
ID3DXFont *dxfont;
VOID* pVoid; // a void pointer
// function prototypes
void initD3D(HWND hWnd); // sets up and initializes Direct3D
void render_frame(void); // renders a single frame
void cleanD3D(void); // closes Direct3D and releases memory
void init_graphics(void); // 3D declarations
void init_light(void); // sets up the light and the material
void initDInput(HINSTANCE hInstance, HWND hWnd); // sets up and initializes DirectInput
void detect_input(void); // gets the current input state
void cleanDInput(void); // closes DirectInput and releases memory
void PrintText(char* str, int size, int x, int y, DWORD color);
inline DWORD F2DW( FLOAT f ) { return *((DWORD*)&f); }
struct CUSTOMVERTEX {FLOAT X, Y, Z; D3DVECTOR NORMAL; FLOAT U,V;};
#define CUSTOMFVF (D3DFVF_XYZ | D3DFVF_NORMAL | D3DFVF_TEX1)
// the WindowProc function prototype
LRESULT CALLBACK WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
// the entry point for any Windows program
int WINAPI WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
HWND hWnd;
WNDCLASSEX wc;
ZeroMemory(&wc, sizeof(WNDCLASSEX));
wc.cbSize = sizeof(WNDCLASSEX);
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = WindowProc;
wc.hInstance = hInstance;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)COLOR_WINDOW;
wc.lpszClassName = L"WindowClass";
RegisterClassEx(&wc);
hWnd = CreateWindowEx(NULL,
L"WindowClass",
L"Our First Direct3D Program",
WS_OVERLAPPEDWINDOW, // non-fullscreen values
0, 0, // the starting x and y positions should be 0
SCREEN_WIDTH, SCREEN_HEIGHT, // set window to new resolution
NULL,
NULL,
hInstance,
NULL);
ShowWindow(hWnd, nCmdShow);
// set up and initialize Direct3D
initD3D(hWnd);
initDInput(hInstance, hWnd); // initialize DirectInput
// enter the main loop:
MSG msg;
while(TRUE)
{
while(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
if(msg.message == WM_QUIT)
break;
detect_input(); // update the input data before rendering
render_frame();
if(keystate[DIK_ESCAPE] & 0x80)
PostMessage(hWnd, WM_DESTROY, 0, 0);
}
// clean up DirectX and COM
cleanD3D();
cleanDInput(); // release DirectInput
return msg.wParam;
}
// this is the main message handler for the program
LRESULT CALLBACK WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch(message)
{
case WM_DESTROY:
{
PostQuitMessage(0);
return 0;
} break;
}
return DefWindowProc (hWnd, message, wParam, lParam);
}
// this function initializes and prepares Direct3D for use
void initD3D(HWND hWnd)
{
d3d = Direct3DCreate9(D3D_SDK_VERSION); // create the Direct3D interface
D3DPRESENT_PARAMETERS d3dpp; // create a struct to hold various device information
ZeroMemory(&d3dpp, sizeof(d3dpp)); // clear out the struct for use
d3dpp.Windowed = TRUE; // program fullscreen, not windowed
d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; // discard old frames
d3dpp.hDeviceWindow = hWnd; // set the window to be used by Direct3D
d3dpp.BackBufferFormat = D3DFMT_X8R8G8B8; // set the back buffer format to 32-bit
d3dpp.BackBufferWidth = SCREEN_WIDTH; // set the width of the buffer
d3dpp.BackBufferHeight = SCREEN_HEIGHT; // set the height of the buffer
d3dpp.EnableAutoDepthStencil = TRUE;
d3dpp.AutoDepthStencilFormat = D3DFMT_D16;
// create a device class using this information and the info from the d3dpp stuct
d3d->CreateDevice(D3DADAPTER_DEFAULT,
D3DDEVTYPE_HAL,
hWnd,
D3DCREATE_SOFTWARE_VERTEXPROCESSING,
&d3dpp,
&d3ddev);
d3ddev->SetRenderState(D3DRS_LIGHTING, TRUE); // turn off the 3D lighting
d3ddev->SetRenderState(D3DRS_ZENABLE, TRUE); // turn on the z-buffer
d3ddev->SetRenderState(D3DRS_AMBIENT, D3DCOLOR_XRGB(50, 50, 50)); // ambient light
init_graphics(); // call the function to initialize the triangle
init_light(); // call the function to initialize the light and material
d3ddev->SetRenderState(D3DRS_LIGHTING, TRUE); // turn on the 3D lighting
d3ddev->SetRenderState(D3DRS_ZENABLE, TRUE); // turn on the z-buffer
d3ddev->SetRenderState(D3DRS_AMBIENT, D3DCOLOR_XRGB(50, 50, 50)); // ambient light
d3ddev->SetRenderState(D3DRS_NORMALIZENORMALS, TRUE); // handle the normal lenght
d3ddev->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE); // turn color blending on
// set filters and samples
d3ddev->SetSamplerState(0, D3DSAMP_MAXANISOTROPY, 8);
d3ddev->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_ANISOTROPIC);
d3ddev->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
d3ddev->SetSamplerState(0, D3DSAMP_MIPFILTER, D3DTEXF_LINEAR);
//d3ddev->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD); // set the blending operation
//d3ddev->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA); // set the source blending
//d3ddev->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA); // set the destination blending
D3DXCreateTextureFromFile(d3ddev, // the Direct3D device
L"brick.bmp", // the filename of the texture
&texture); // the address of the texture storage
D3DXCreateTextureFromFile(d3ddev,
L"bump.bmp",
&bump);
//d3ddev->SetRenderState(D3DRS_TEXTUREFACTOR, D3DCOLOR_XRGB(200, 200, 200));
//d3ddev->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_DOTPRODUCT3);
//d3ddev->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
//d3ddev->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_TFACTOR);
//d3ddev->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
//d3ddev->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_DIFFUSE);
//d3ddev->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_MODULATE);
//d3ddev->SetTextureStageState(1, D3DTSS_COLORARG1, D3DTA_CURRENT);
//d3ddev->SetTextureStageState(1, D3DTSS_COLORARG2, D3DTA_TEXTURE);
//d3ddev->SetTextureStageState(1, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
//d3ddev->SetTextureStageState(1, D3DTSS_ALPHAARG1, D3DTA_DIFFUSE);
d3ddev->SetTextureStageState(2, D3DTSS_COLOROP, D3DTOP_DISABLE);
d3ddev->SetTextureStageState(2, D3DTSS_ALPHAOP, D3DTOP_DISABLE);
//D3DXAssembleShaderFromFile("shader1.fx", 0 , NULL, &pCode, NULL );
}
// Hypotenuse function
float hypo(float x,float y)
{
float hypo=sqrt(x*x+y*y);
return hypo;
}
// this is the function used to render a single frame
void render_frame(void)
{
// clear the window to a specified color
d3ddev->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0, 0, 0), 1.0f, 0);
d3ddev->Clear(0, NULL, D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(0, 0, 0), 1.0f, 0);
d3ddev->BeginScene(); // begins the 3D scene
d3ddev->SetFVF(CUSTOMFVF); // tells Direct3D what FVF code we are using currently
// set the texture
d3ddev->SetTexture(1, bump);
d3ddev->SetTexture(0, texture);
///////
D3DXMATRIX matTranslateA; // a matrix to store the translation for triangle A
D3DXMATRIX matTranslateB; // a matrix to store the translation for triangle B
D3DXMATRIX matRotate; // a matrix to store the rotation for each triangle
D3DXMATRIX matRotate2;
D3DXMATRIX matScale;
static float index = 0.0f; // left movement (A)
static float index2 = 10.0f; // upward movement (PRIOR)
static float index3 = 18.0f; // backward movement (S) -- 1.0f
static float index4 = 0.0f; // left lookAt
static float index5 = 10.0f; // upward lookAt
static float index6 = 18.0f; // backward lookAt
// camera variables
static float radius = 30.00f;
static float theta = (3.0f * D3DX_PI) / 2.0f;
static float phi = D3DX_PI/2;
float Cx, Cy, Cz;
static int field = 45;
float slide = 0.001f;
static float dist1 = fabs(index-index4);
static float dist2 = fabs(index2-index5);
static float dist3 = fabs(index3-index6);
// player movements
// mouse movements
field -= 0.01 * mousestate.lZ;
theta += slide * mousestate.lX;
phi -= slide * mousestate.lY;
if(phi >= (D3DX_PI/9) * 8)
{
phi = (D3DX_PI/9) * 8;
}
if(phi <= (D3DX_PI/9))
{
phi = (D3DX_PI/9);
}
Cx = radius * cosf(theta) * sinf(phi);
Cy = radius * cosf(phi);
Cz = radius * sinf(theta) * sinf(phi);
float mov = radius*0.012;
float mov1 = Cz*0.012;
float mov2 = -Cx*0.012;
// previous index. values
float indexb = index;
float index3b = index3;
//if (GetAsyncKeyState(VK_SHIFT)) // --- 0.06f/0.03f
//{
if (keystate[DIK_A] & 0x80)
{
index=index-mov1;
index3=index3+mov2;
}
if (keystate[DIK_D] & 0x80)
{
index=index+mov1;
index3=index3-mov2;
}
if (keystate[DIK_PRIOR] & 0x80) // up +
{
index2+=0.22f;
}
if (keystate[DIK_NEXT] & 0x80) // down -
{
index2-=0.22f;
}
if (keystate[DIK_W] & 0x80) // prior
{
index3=index3+mov1;
index=index+mov2;
}
if (keystate[DIK_S] & 0x80) // next
{
index3=index3-mov1;
index=index-mov2;
}
if (keystate[DIK_SPACE] & 0x80) // next
{
// JUMP!!!!!!!!!!!!
}
if (hypo(index-indexb,index3-index3b)>mov)
{
index=indexb+0.7071*(index-indexb);
index3=index3b+0.7071*(index3-index3b);
}
// print a text
char msg1[64], msg2[64], msg3[64];
sprintf (msg1, "X axis: %f", index);
sprintf (msg2, "Z axis: %f", index3);
PrintText(msg1, 20, 30, 30, D3DCOLOR_XRGB(255,255,255));
PrintText(msg2, 20, 30, 60, D3DCOLOR_XRGB(255,255,255));
//}
/*else
if (GetAsyncKeyState(VK_LEFT))
{
index+=0.06f;
index4+=0.06f;
}
if (GetAsyncKeyState(VK_RIGHT))
{
index-=0.06f;
index4-=0.06f;
}
if (GetAsyncKeyState(VK_PRIOR))
{
index2-=0.06f;
index5-=0.06f;
}
if (GetAsyncKeyState(VK_NEXT))
{
index2+=0.06f;
index5+=0.06f;
}
if (GetAsyncKeyState(VK_UP))
{
index3-=0.03f;
index6-=0.06f;
}
if (GetAsyncKeyState(VK_DOWN))
{
index3+=0.03f;
index6+=0.06f;
}*/
// build MULTIPLE matrices to translate the model and one to rotate
D3DXMatrixTranslation(&matTranslateA, 0.0f, 0.0f, 0.0f);
//D3DXMatrixTranslation(&matTranslateB, 0.0f, 0.0f, -3.0f);
D3DXMatrixRotationY(&matRotate, 0.0f); // the front side --- index
D3DXMatrixRotationX(&matRotate2, 0.0f); // index2
D3DXMatrixScaling(&matScale, 1.0f, 1.0f, 1.0f); // index3
///////
D3DXMATRIX matView; // the view transform matrix
D3DXMatrixLookAtLH(&matView,
&D3DXVECTOR3 (index, index2, index3), // the camera position --- (0.0f, 10.0f, 18.0f)
&D3DXVECTOR3 (index-Cx, index2-Cy, index3+Cz), // the look-at position --- (0.0f, 0.0f, 0.0f)
&D3DXVECTOR3 (0.0f, 1.0f, 0.0f)); // the up direction
d3ddev->SetTransform(D3DTS_VIEW, &matView); // set the view transform to matView
D3DXMATRIX matProjection; // the projection transform matrix
D3DXMatrixPerspectiveFovLH(&matProjection,
D3DXToRadian(field), // the horizontal field of view
(FLOAT)SCREEN_WIDTH / (FLOAT)SCREEN_HEIGHT, // aspect ratio
1.0f, // the near view-plane
100.0f); // the far view-plane
d3ddev->SetTransform(D3DTS_PROJECTION, &matProjection); // set the projection
// tell Direct3D about each world transform, and then draw another triangle
d3ddev->SetTransform(D3DTS_WORLD, &(matTranslateA * matRotate * matRotate2 * matScale));
///////
/// select the vertex and index buffers to use
d3ddev->SetStreamSource(0, v_buffer, 0, sizeof(CUSTOMVERTEX));
d3ddev->SetIndices(i_buffer);
// draw the cube
d3ddev->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, 24, 0, 12);
d3ddev->EndScene(); // ends the 3D scene
d3ddev->Present(NULL, NULL, NULL, NULL); // displays the created frame on the screen
}
// this is the function that cleans up Direct3D and COM
void cleanD3D(void)
{
v_buffer->Release(); // close and release the vertex buffer
//i_buffer->Release(); // close and release the index buffer
texture->Release(); // close and release the texture
d3ddev->Release(); // close and release the 3D device
d3d->Release(); // close and release Direct3D
}
// this is the function that puts the 3D models into video RAM
void init_graphics(void)
{
// create the vertices using the CUSTOMVERTEX struct
CUSTOMVERTEX vertices[] =
{
{ -3.0f, -3.0f, 3.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f }, // side 1
{ 3.0f, -3.0f, 3.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f },
{ -3.0f, 3.0f, 3.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f },
{ 3.0f, 3.0f, 3.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f },
{ 3.0f, -3.0f, -3.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f }, // side 2
{ -3.0f, -3.0f, -3.0f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f },
{ 3.0f, 3.0f, -3.0f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f },
{ -3.0f, 3.0f, -3.0f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f },
{ -3.0f, 3.0f, -3.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f }, // side 3
{ -3.0f, 3.0f, 3.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f },
{ 3.0f, 3.0f, -3.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f },
{ 3.0f, 3.0f, 3.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f },
{ -3.0f, -3.0f, -3.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f }, // side 4
{ 3.0f, -3.0f, -3.0f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f },
{ -3.0f, -3.0f, 3.0f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f },
{ 3.0f, -3.0f, 3.0f, 0.0f, -1.0f, 0.0f, 1.0f, 1.0f },
{ 3.0f, -3.0f, 3.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f }, // side 5
{ 3.0f, -3.0f, -3.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f },
{ 3.0f, 3.0f, 3.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f },
{ 3.0f, 3.0f, -3.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f },
{ -3.0f, -3.0f, -3.0f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f }, // side 6
{ -3.0f, -3.0f, 3.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f },
{ -3.0f, 3.0f, -3.0f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f },
{ -3.0f, 3.0f, 3.0f, -1.0f, 0.0f, 0.0f, 1.0f, 1.0f },
};
// create a vertex buffer interface called v_buffer
d3ddev->CreateVertexBuffer(24*sizeof(CUSTOMVERTEX),
0,
CUSTOMFVF,
D3DPOOL_MANAGED,
&v_buffer,
NULL);
VOID* pVoid; // a void pointer
// lock v_buffer and load the vertices into it
v_buffer->Lock(0, 0, (void**)&pVoid, 0);
memcpy(pVoid, vertices, sizeof(vertices));
v_buffer->Unlock();
// create the indices using an int array
short indices[] =
{
0, 1, 2, // side 1
2, 1, 3,
4, 5, 6, // side 2
6, 5, 7,
8, 9, 10, // side 3
10, 9, 11,
12, 13, 14, // side 4
14, 13, 15,
16, 17, 18, // side 5
18, 17, 19,
20, 21, 22, // side 6
22, 21, 23,
};
// create an index buffer interface called i_buffer
d3ddev->CreateIndexBuffer(36*sizeof(short),
0,
D3DFMT_INDEX16,
D3DPOOL_MANAGED,
&i_buffer,
NULL);
// lock i_buffer and load the indices into it
i_buffer->Lock(0, 0, (void**)&pVoid, 0);
memcpy(pVoid, indices, sizeof(indices));
i_buffer->Unlock();
}
// this is the function that sets up the lights and materials
void init_light(void)
{
D3DLIGHT9 light; // create the light struct
D3DMATERIAL9 material; // create the material struct
ZeroMemory(&light, sizeof(light)); // clear out the light struct for use
light.Type = D3DLIGHT_POINT; // make the light type 'point light'
light.Diffuse = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f); // set the light's color
//light.Specular = D3DXCOLOR(5.5f, 5.5f, 5.5f, 1.0f);
light.Position = D3DXVECTOR3(10.0f, 10.0f, 5.0f);
light.Range = 100.0f;
//light.Direction = D3DXVECTOR3(-1.0f, -0.3f, -1.0f);
light.Attenuation0 = 0.0f; // constant attenuation
light.Attenuation1 = 0.0f; // inverse attenuation
light.Attenuation2 = 0.01f; // square inverse attenuation
d3ddev->SetLight(0, &light); // send the light struct properties to light #0
d3ddev->LightEnable(0, TRUE); // turn on light #0
ZeroMemory(&material, sizeof(D3DMATERIAL9)); // clear out the struct for use
material.Diffuse = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f); // set diffuse color
material.Ambient = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f); // set ambient color
d3ddev->SetMaterial(&material); // set the globably-used material to &material
}
// this is the function that initializes DirectInput
void initDInput(HINSTANCE hInstance, HWND hWnd)
{
// create the DirectInput interface
DirectInput8Create(hInstance, // the handle to the application
DIRECTINPUT_VERSION, // the compatible version
IID_IDirectInput8, // the DirectInput interface version
(void**)&din, // the pointer to the interface
NULL); // COM stuff, so we'll set it to NULL
// create the keyboard device
din->CreateDevice(GUID_SysKeyboard, // the default keyboard ID being used
&dinkeyboard, // the pointer to the device interface
NULL); // COM stuff, so we'll set it to NULL
din->CreateDevice(GUID_SysMouse,
&dinmouse,
NULL);
// set the data format to keyboard format
dinkeyboard->SetDataFormat(&c_dfDIKeyboard);
dinmouse->SetDataFormat(&c_dfDIMouse);
// set the control you will have over the keyboard
dinkeyboard->SetCooperativeLevel(hWnd, DISCL_NONEXCLUSIVE | DISCL_FOREGROUND);
dinmouse->SetCooperativeLevel(hWnd, DISCL_EXCLUSIVE | DISCL_FOREGROUND);
}
// this is the function that gets the latest input data
void detect_input(void)
{
// get access if we don't have it already
dinkeyboard->Acquire();
dinmouse->Acquire();
// get the input data
dinkeyboard->GetDeviceState(256, (LPVOID)keystate);
dinmouse->GetDeviceState(sizeof(DIMOUSESTATE), (LPVOID)&mousestate);
}
// this is the function that closes DirectInput
void cleanDInput(void)
{
dinkeyboard->Unacquire(); // make sure the keyboard is unacquired
dinmouse->Unacquire(); // make sure the mouse in unacquired
din->Release(); // close DirectInput before exiting
}
void PrintText(char* str, int size, int x, int y, DWORD color)
{
static RECT textbox;
SetRect(&textbox, x, y, SCREEN_WIDTH, SCREEN_HEIGHT);
D3DXCreateFont(d3ddev, // the D3D Device
size, // font height
0, // default font width
FW_NORMAL, // font weight
1, // not using MipLevels
false, // italic font
DEFAULT_CHARSET, // default character set
OUT_DEFAULT_PRECIS, // default OutputPrecision,
DEFAULT_QUALITY, // default Quality
DEFAULT_PITCH | FF_DONTCARE, // default pitch and family
L"Arial", // use Facename Arial
&dxfont); // the font object
dxfont->DrawTextA(NULL,
str,
strlen(str),
&textbox,
DT_LEFT | DT_TOP,
color);
}
Don't create a new font object every time you print text.
As stefan posted, a new font is being created every time the PrintText function is called.
One way to fix this would be to move the D3DXCreateFont function call into the initD3D function, and add a matching dxfont->Release(); to the cleanD3D function.

How can I stack opengl shapes into std::vector

How can I stack up these two opengl shapes into a container class?
can someone please show me
I wont mind a template.
void myTriangle()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glTranslatef(-1.5f,0.0f,-6.0f);
glBegin(GL_TRIANGLES);
glColor3f(1.0f,0.0f,0.0f);
glVertex3f( 0.0f, 1.0f, 0.0f);
glColor3f(0.0f,1.0f,0.0f);
glVertex3f(-1.0f,-1.0f, 0.0f);
glColor3f(0.0f,0.0f,1.0f);
glVertex3f( 1.0f,-1.0f, 0.0f);
glEnd();
glutSwapBuffers ( );
}
void myQuad()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glColor3f(0.5f,0.5f,1.0f);
glBegin(GL_QUADS);
glVertex3f(-1.0f, 1.0f, 0.0f);
glVertex3f( 1.0f, 1.0f, 0.0f);
glVertex3f( 1.0f,-1.0f, 0.0f);
glVertex3f(-1.0f,-1.0f, 0.0f);
glEnd();
glutSwapBuffers ( );
}
not really sure of what you want to do, but you can do:
typedef void (*ShapeFct_t)();
typedef std::vector<ShapeFct_t> ShapeArray_t;
ShapeArray_t shapes;
shapes.push_back(myTriangle);
shapes.push_back(myQuad);
You can define a Shape base class, and have Quad and Triangle inherit from that class with an overloaded draw function. Here's a simplified, incomplete example:
/* Define these; use tuples, your own class, 3rd party, whatever */
class Position;
class Color;
/* Shape class is abstract base class */
class Shape {
public:
Shape(const Position &pos) : position(pos) {}
virtual void draw() = 0;
protected:
Position position;
};
/* Triangle and Quad classes are Shapes */
class Triangle : public Shape {
public:
Triangle(const Position &pos,
const Position &p1, const Color &c1,
const Position &p2, const Color &c2,
const Position &p3, const Color &c3)
: Shape(pos),
pos1(p1), col1(c1),
pos2(p2), col2(c2),
pos3(p3), col3(c3)
{}
virtual void draw() {
glTranslatef(position.x, position.y, position.z);
glBegin(GL_TRIANGLES);
glColor3f(col1.r, col1.g, col1.b);
glVertex3f(pos1.x, pos1.y, pos1.z);
glColor3f(col2.r, col2.g, col2.b);
glVertex3f(pos2.x, pos2.y, pos2.z);
glColor3f(col3.r, col3.g, col3.b);
glVertex3f(pos3.x, pos3.y, pos3.z);
glEnd();
}
private:
Position pos1, pos2, pos3;
Color col1, col2, col3;
};
class Quad : public Shape {
/* Your implementation here */
};
void draw_all_shapes() {
std::vector<Shape*> shapes;
shapes.push_back(new Triangle(Position(-1.5f, 0f, -6f),
Position(0f, 1f, 0f), Color(1f, 0f, 0f),
Position(-1f, -1f, 0f), Color(0f, 1f, 0f),
Position(0f, 0f, 1f), Color(0f, 0f, 1f)));
shapes.push_back(new Quad(/* Arguments */));
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
for(auto it = shapes.begin(); it != shapes.end(); it++) {
(*it)->draw();
}
glutSwapBuffers();
}
Note: As I said, the example is incomplete. It's also untested and a little bit messy (memory leaks and such) but those problems are out of the scope of this question. The main point I am trying to demonstrate here is that you can convert your functions to classes, which can leverage inheritance and polymorphism to simplify your code.
Not sure if you care to edit what the shape looks like after you create it but you could put it in a display list, then store each display list in whatever container you like:
GLuint triangleList = glGenLists(1);
glNewList(triangleList, GL_COMPILE);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glTranslatef(-1.5f,0.0f,-6.0f);
glBegin(GL_TRIANGLES);
glColor3f(1.0f,0.0f,0.0f);
glVertex3f( 0.0f, 1.0f, 0.0f);
glColor3f(0.0f,1.0f,0.0f);
glVertex3f(-1.0f,-1.0f, 0.0f);
glColor3f(0.0f,0.0f,1.0f);
glVertex3f( 1.0f,-1.0f, 0.0f);
glEnd();
glEndList();
GLuint quadList = glGenList(1);
glNewList(quadList, GL_COMPILE);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glColor3f(0.5f,0.5f,1.0f);
glBegin(GL_QUADS);
glVertex3f(-1.0f, 1.0f, 0.0f);
glVertex3f( 1.0f, 1.0f, 0.0f);
glVertex3f( 1.0f,-1.0f, 0.0f);
glVertex3f(-1.0f,-1.0f, 0.0f);
glEnd();
glEndList();
At this point you can store the quadList and triangleList in whatever container you like. You can tell OpenGL to display them by using the glCallList() function. To delete the list call glDeleteList().