Jump to content
  • Advertisement
Sign in to follow this  
Jouei

OpenGL Gui Issues and Code Bash

This topic is 3633 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Langauge: C++ Compiler: Microsoft Visual C++ 2008 express First off this is my first GUI so i am sure it is full of many not so much errors but excess code and code that code be writen better. The main problem is that it seems the controls textures for the buttons leaked into the panel control sum how. In order to overcum this i diabled the 2d textureing in the panels render func but i am sure there is a good reason for it. first the Gui header

#ifndef HEX_GUI_H
#define HEX_GUI_H

#define BOOST_SP_DISABLE_THREADS 

#include <windows.h>
#include <gl\gl.h>									// Header File For The OpenGL32 Library
#include <gl\glu.h>									// Header File For The GLu32 Library

#include <iostream>                                 //Standard input output Header
#include <list>
#include "boost/smart_ptr.hpp"

typedef unsigned int UINT;

void glEnable2D();
void glDisable2D();

//gui State Types

#define NORMAL 0
#define DEPRESSED 1
#define HOVERED 2

//Gui Message message types

#define MOUSE_LEFT_CLICK 201


//Gui Error Messages

#define GUI_BAD_PATH  400
#define GUI_BAD_IMAGE 401


//Gui Flag defines
#define GUI_NO_HOVER 0x00100000L

namespace HEX_GUI
{


	////////////////////////////////////////////////////////////////////////
	//                                                                    //
	//  This is Our Gui Descriptor Used for all of the the constrution    //
	//  of controls.                                                      //
	//                                                                    //
	////////////////////////////////////////////////////////////////////////

	enum CONTROL_TYPE
	{
    Panel,
	Button
	};

	struct HEX_GUI_DESC
	{
		CONTROL_TYPE Type;
		std::string Name;
		UINT ID;
		UINT ControlPostionX;
		UINT ControlPostionY;
		UINT ControlWidth;
		UINT ControlHeight;
		std::string FaceImage;
		std::string DepressedImage;
		std::string HoverImage; 
		bool Visible;

		//Specal Field
		DWORD Flags;
	};

	class GUI_WINDOW;

	//Make a Shorty for a pointer to controls
	typedef boost::shared_ptr<GUI_WINDOW> ControlPtr;

	//Make a Shorty for a pointer to Windows
	typedef boost::shared_ptr<GUI_WINDOW> WindowPtr;

	class GUI_MESSAGE
	{
	public:

		GUI_WINDOW * MessageFrom;
		UINT Message;
		std::string Text;
		float Value;
		void Clear(){MessageFrom = NULL; Message = 0; Text.clear(); Value = 0;}
	};


	////////////////////////////////////////////////////////////////////////
	//  This is our main gui base class Since all controls are windows    //
	//  Each control will virtaly overide base functionality for its own  //
	//  and retain its own data in addition some contros will have child  //
    //  controls that are also of this base class.                        //
	////////////////////////////////////////////////////////////////////////

	class GUI_WINDOW
	{
	public:
		
		GUI_WINDOW(){};
		GUI_WINDOW(HEX_GUI_DESC){};
		virtual bool init(){ return false;};
		virtual GUI_MESSAGE Logic(UINT MouseX,UINT MouseY, UINT MouseState){GUI_MESSAGE Empty; return Empty; };
		virtual void Render(){};
		virtual UINT AddWindow(HEX_GUI_DESC HGDesc){ return 0;};
		virtual bool IsSelected(UINT MouseX,UINT MouseY,UINT MouseState);
		virtual bool IsHovered(UINT MouseX,UINT MouseY);

		void MoveWindow(UINT PostionX,UINT PostionY){CurPostionX = PostionX; CurPostionY = PostionY; }
		void ShowWindow(bool Show){WindowVisible = Show;}
		void SetWindowText(std::string & Text){WindowName = Text;}
		void SetWindowID(UINT ID){WindowID = ID;}
		void SetWindowHeight(UINT Height){CurHeight = Height;}
		void SetWindowWidth(UINT Width){CurWidth = Width;}

		std::string GetWindowText(){return WindowName;}
		UINT GetWindowID(){return WindowID;}
		const UINT GetXPostion(){return CurPostionX;}
		const UINT GetYPostion(){return CurPostionY;}
		const UINT GetHeight(){return CurHeight;}
		const UINT GetWidth(){return CurWidth;}
		const std::string GetWindowName(){return WindowName;}

		~GUI_WINDOW(){};

	private:

		std::string WindowName;
		UINT WindowID;
		UINT CurPostionX;
		UINT CurPostionY;
		UINT CurWidth;
		UINT CurHeight;
		bool WindowVisible;
		
	};


	/////////////////////////////////////////////////////////////////////
	//  This is our basic button control, Three state.                 //
	//  Clicked, UnClicked and MouseOver                               //
	/////////////////////////////////////////////////////////////////////

	class GUI_BUTTON : public GUI_WINDOW
	{
	public:

		GUI_BUTTON(){};
		GUI_BUTTON(HEX_GUI_DESC);

		GUI_MESSAGE Logic(UINT MouseX,UINT MouseY,UINT MouseState);
		void Render();
		
		void SetTexture(GLuint Texture,UINT ID){ID--; Textures[ID] = Texture;}  
		void SetState(UINT ControlState){State = ControlState;}
		UINT LoadTexture(std::string FileName, GLuint & TextureStorage);

		GLuint GetTexture(UINT ID){return Textures[ID];}
		UINT GetState(){return State;}
	private:

		//Texture storage for our Button States OpenGL specfic
		GLuint Textures[3];			//Button Up, Button Down and Button Hover
		UINT State;
	};

	/////////////////////////////////////////////////////////////////////
	//  This Is the first and most important Gui Control Its a panel   //
	//  This acts as a virtual window a contrl that holds other        //
	//  controls and is useful for Dialog boxs and Layout managerment  //
	/////////////////////////////////////////////////////////////////////

	class GUI_PANEL : public GUI_WINDOW
	{
	public:

		GUI_PANEL(){};
		GUI_PANEL(HEX_GUI_DESC);
		bool Init(){};
		GUI_MESSAGE Logic(UINT MouseX,UINT MouseY, UINT MouseState);
		void Render();
		UINT AddWindow(HEX_GUI_DESC HGDesc);
		
		~GUI_PANEL(){};

	private:

		std::list < boost::shared_ptr <GUI_WINDOW> > ControlList;
	};

	class GUI_MANAGER
	{
	
	public:
		GUI_MANAGER(){CurMousePosX = 0; CurMousePosY = 0; CurMouseButtonState = 0;};
		
		void InjectMouseInput(UINT MouseX, UINT MouseY, UINT MouseButtonState)
		{CurMousePosX = MouseX; CurMousePosY = MouseY; CurMouseButtonState = MouseButtonState;}
		void InjectKetboardInput(DWORD VirtualKeyCode);
		UINT GetMouseX(){return CurMousePosX;};
		UINT GetMouseY(){return CurMousePosY;};
		UINT GetMouseButtonState();

		void SetLastMessage(GUI_MESSAGE CurMessage){LastMessage = CurMessage;} 
		GUI_MESSAGE GetMessage(){GUI_MESSAGE Temp = LastMessage; LastMessage.Clear(); return Temp; }
		bool AddWindow(HEX_GUI_DESC HGDesc);
		void Logic();
		void Render();

		

		private:
		
		GUI_MESSAGE LastMessage;											//Last Message Recived
		std::list < boost::shared_ptr <GUI_WINDOW> > WindowList;
		UINT CurMousePosX;													//Current Mouse X postion
		UINT CurMousePosY;													//Current Mouse Y Postion
		UINT CurMouseButtonState;											//Current Mouse Button State

		bool KeyStats[256];													//An Array for Key Stats
	};
		


//End of namespace
}




#endif HEX_GUI_DEF

Next the Gui Cpp file

#include "HexGui.h"

using namespace HEX_GUI;

//-----------------------------------------------------------------------------
// Name: glEnable2D
// Desc: Enabled 2D primitive rendering by setting up the appropriate orthographic
//		 perspectives and matrices.
//-----------------------------------------------------------------------------
void glEnable2D()
{
	GLint iViewport[4];

	// Get a copy of the viewport
	glGetIntegerv( GL_VIEWPORT, iViewport );

	// Save a copy of the projection matrix so that we can restore it 
	// when it's time to do 3D rendering again.
	glMatrixMode( GL_PROJECTION );
	glPushMatrix();
	glLoadIdentity();

	// Set up the orthographic projection
	glOrtho( iViewport[0], iViewport[0]+iViewport[2],
			 iViewport[1]+iViewport[3], iViewport[1], -1, 1 );
	glMatrixMode( GL_MODELVIEW );
	glPushMatrix();
	glLoadIdentity();

}


//-----------------------------------------------------------------------------
// Name: glDisable2D
// Desc: Disables 2D rendering and restores the previous matrix and render states
//		 before they were modified.
//-----------------------------------------------------------------------------
void glDisable2D()
{
	glMatrixMode( GL_PROJECTION );
	glPopMatrix();
	glMatrixMode( GL_MODELVIEW );
	glPopMatrix();
}

	/////////////////////////////////////////////////////////////////////
	//   These are the functions for the GUI base window class         //
	/////////////////////////////////////////////////////////////////////

	bool GUI_WINDOW::IsSelected(UINT MouseX,UINT MouseY,UINT MouseState)
	{
		UINT X = GetXPostion();
		if(MouseX >= X && MouseX <= (X + GetWidth()))
		{
			UINT Y = GetYPostion();
			if(MouseY >= Y && MouseY <= (Y + GetHeight()))
			{
				if(MouseState == 1)return true;
			}
		}
		return false;
	}

	bool GUI_WINDOW::IsHovered(UINT MouseX,UINT MouseY)
	{
		UINT X = GetXPostion();
		if(MouseX >= X && MouseX <= (X + GetWidth()))
		{
			UINT Y = GetYPostion();
			if(MouseY >= Y && MouseY <= (Y + GetHeight()))
			{
				return true;
			}
		}
		return false;
	}




	bool GUI_MANAGER::AddWindow(HEX_GUI_DESC HGDesc)
	{
		
		switch(HGDesc.Type)
		{
		case Panel:
			WindowList.push_back( (WindowPtr) new GUI_PANEL(HGDesc));
		return true;

		case Button:
			WindowList.push_back( (WindowPtr) new GUI_BUTTON(HGDesc));
		return true;

		default:
			return false;
		}

		return false;
	}

	void GUI_MANAGER::Render()
	{
		if(!WindowList.empty())
		{
			glEnable2D();
			
			for(std::list<boost::shared_ptr <GUI_WINDOW>>::iterator WindowIterlator = WindowList.begin();
				WindowIterlator != WindowList.end(); WindowIterlator++)
			{

				WindowPtr Window = *WindowIterlator;
				Window->Render();
			}	
			glDisable2D();

		}
	}
	void GUI_MANAGER::Logic()
	{
		if(!WindowList.empty())
		{
			GUI_MESSAGE GuiMessage;
			for(std::list<boost::shared_ptr <GUI_WINDOW>>::iterator WindowIterlator = WindowList.begin();
				WindowIterlator != WindowList.end(); WindowIterlator++)
			{
				WindowPtr Window = *WindowIterlator;
				GuiMessage = Window->Logic(GetMouseX(),GetMouseY(),GetMouseButtonState());
				if(GuiMessage.Message != 0)
				{
					SetLastMessage(GuiMessage);
					return;
				}
			}
		}
	}

	UINT GUI_MANAGER::GetMouseButtonState()
	{
		if(CurMouseButtonState == MK_LBUTTON)
		{
			return 1;
		}
	}

Ok and now the Gui panel control Cpp

#include "HexGui.h"

using namespace HEX_GUI;

	////////////////////////////////////////////////////////////////////////////////////////
	//                                                                                    //
	//                 GUI_PANEL's Function Defines and routiens.                         //
	//                                                                                    //
	////////////////////////////////////////////////////////////////////////////////////////

	GUI_PANEL::GUI_PANEL(HEX_GUI_DESC HGDesc)
	{
		if(HGDesc.Type == Panel)
		{
			SetWindowText(HGDesc.Name);
			SetWindowID(HGDesc.ID);
			SetWindowHeight(HGDesc.ControlHeight);
			SetWindowWidth(HGDesc.ControlWidth);
			MoveWindow(HGDesc.ControlPostionX,HGDesc.ControlPostionY);
			ShowWindow(HGDesc.Visible);
		}
	}

	UINT GUI_PANEL::AddWindow(HEX_GUI_DESC HGDesc)
	{
		if(HGDesc.Type <= 0)return false;

		switch(HGDesc.Type)
		{
		case Button:
			// To Implement Button addition to std list
			return true;

		default:
			return false;
		}

		return false;
	}

	

	void GUI_PANEL::Render()
	{
		glFlush();
		glDisable(GL_TEXTURE_2D);
		glPushMatrix();
		
		//Render Self if needed
		glBegin( GL_QUADS );
		glVertex2i(GetXPostion(), GetYPostion() );												//Top Left
		glVertex2i(GetXPostion() + GetWidth(), GetYPostion() );									//Top Right
		glVertex2i(GetXPostion() + GetWidth(), GetYPostion() + GetHeight());					//Bottum right
		glVertex2i(GetXPostion(), GetYPostion() + GetHeight() );								//Bottum Left
		glEnd();

		glPopMatrix();

		//Check to see if the Panels control list is valid and if so draw the child controls
		if(!ControlList.empty())
		{
			for(std::list<boost::shared_ptr <GUI_WINDOW>>::iterator ControlIterlator = ControlList.begin();
				ControlIterlator != ControlList.end(); ControlIterlator++)
			{
				ControlPtr Control = *ControlIterlator;
				Control->Render();
			}
		}
	}

	GUI_MESSAGE GUI_PANEL::Logic(UINT MouseX,UINT MouseY, UINT MouseState)
	{
		if(IsSelected(MouseX,MouseY,MouseState == 1))
		{
			GUI_MESSAGE GuiMessage;
			GuiMessage.MessageFrom = this;
			GuiMessage.Message = MOUSE_LEFT_CLICK;
			GuiMessage.Text = GetWindowName();
			GuiMessage.Value = 0;
			return GuiMessage;
		}

		GUI_MESSAGE GuiEmpty;
		GuiEmpty.Message = 0;
		GuiEmpty.MessageFrom = NULL;
		GuiEmpty.Value = 0;

		return GuiEmpty;
	}


ok now the Button control Cpp

#include "HexGui.h"

#include <olectl.h>
#include <math.h>

using namespace HEX_GUI;

GUI_BUTTON::GUI_BUTTON(HEX_GUI_DESC HGDesc)
{
	//Load Face Image
	if(!HGDesc.FaceImage.empty())
	{
		LoadTexture(HGDesc.FaceImage,Textures[0]);
		if(!Textures[1]) throw GUI_BAD_IMAGE;
	}
	else throw GUI_BAD_PATH;

	//Load Back Image
	if(!HGDesc.DepressedImage.empty())
	{
	LoadTexture(HGDesc.DepressedImage,Textures[1]);		
		if(!Textures[2]) throw GUI_BAD_IMAGE;
	}
	else throw GUI_BAD_PATH;

	//Check to see if there is a no hover flag
	if(HGDesc.Flags != GUI_NO_HOVER)
	{
		if(!HGDesc.DepressedImage.empty())
		{
			LoadTexture(HGDesc.HoverImage,Textures[2]);		
			if(!Textures[3]) throw GUI_BAD_IMAGE;
			
		}
		else throw GUI_BAD_PATH;
	}

	SetWindowText(HGDesc.Name);
	SetWindowID(HGDesc.ID);
	SetWindowHeight(HGDesc.ControlHeight);
	SetWindowWidth(HGDesc.ControlWidth);
	MoveWindow(HGDesc.ControlPostionX,HGDesc.ControlPostionY);
	ShowWindow(HGDesc.Visible);

	SetState(NORMAL);

}

//GUI_BUTTON Logic funtion

GUI_MESSAGE GUI_BUTTON::Logic(UINT MouseX,UINT MouseY, UINT MouseState)
{
	if(IsSelected(MouseX,MouseY,MouseState == 1))
	{
		SetState(DEPRESSED);
		GUI_MESSAGE GuiMessage;
		GuiMessage.MessageFrom = this;
		GuiMessage.Message = MOUSE_LEFT_CLICK;
		GuiMessage.Text = GetWindowName();
		GuiMessage.Value = 0;
		return GuiMessage;
	}

	if(IsHovered(MouseX,MouseY))
	{
		SetState(HOVERED); 
	}
	else
	{
		SetState(NORMAL);
	}

	GUI_MESSAGE GuiEmpty;
	GuiEmpty.Message = 0;
	GuiEmpty.MessageFrom = NULL;
	GuiEmpty.Value = 0;

	return GuiEmpty;
}

//Buttons Render Function

void GUI_BUTTON::Render()
{

	glFlush();
	glEnable(GL_TEXTURE_2D);
	glPushMatrix();

	//Render Self if needed
	glBindTexture(GL_TEXTURE_2D, GetTexture(GetState()));

	glBegin( GL_QUADS );
	glTexCoord2f(0.0f,1.0f);
	glVertex2i(GetXPostion(), GetYPostion() );												//Top Left
	glTexCoord2f(1.0f,1.0f);
	glVertex2i(GetXPostion() + GetWidth(), GetYPostion() );									//Bottum Left
	glTexCoord2f(1.0f,0.0f);
	glVertex2i(GetXPostion() + GetWidth(), GetYPostion() + GetHeight());						//Bottum right
	glTexCoord2f(0.0f,0.0f);
	glVertex2i(GetXPostion(), GetYPostion() + GetHeight() );									//Top Right
	glEnd();

	glPopMatrix();	


}


//Function for loading a OpenGL texture via Jpeg format

UINT GUI_BUTTON::LoadTexture(std::string FileName, GLuint &TextureStorage)
{

	HDC		hdcTemp;					            	// The DC To Hold Our Bitmap
	HBITMAP		hbmpTemp;					         	// Holds The Bitmap Temporarily
	IPicture	*pPicture;					          	// IPicture Interface
	OLECHAR		wszPath[MAX_PATH+1];					// Full Path To Picture (WCHAR)
	char		szPath[MAX_PATH+1];			      		// Full Path To Picture
	long		lWidth;						        	// Width In Logical Units
	long		lHeight;					            // Height In Logical Units
	long		lWidthPixels;						    // Width In Pixels
	long		lHeightPixels;						    // Height In Pixels
	GLint		glMaxTexDim ;						    // Holds Maximum Texture Size


	std::string TempPath;

	if (strstr(FileName.c_str(), "http://"))					// If PathName Contains http:// Then...
	{
		strcpy_s(szPath,FileName.size(), FileName.c_str());					// Append The PathName To szPath
	}
	else									// Otherwise... We Are Loading From A File
	{
		GetCurrentDirectory(MAX_PATH, szPath);				// Get Our Working Directory

		TempPath += szPath;
		TempPath += "\\";
		TempPath += FileName;
	}

	MultiByteToWideChar(CP_ACP, 0, TempPath.c_str(), -1, wszPath, MAX_PATH);		// Convert From ASCII To Unicode
	HRESULT hr = OleLoadPicturePath(wszPath, 0, 0, 0, IID_IPicture, (void**)&pPicture);

	if(FAILED(hr))								// If Loading Failed
	return false;							// Return False
	
	hdcTemp = CreateCompatibleDC(GetDC(0));					// Create The Windows Compatible Device Context
	if(!hdcTemp)								// Did Creation Fail?
	{
		pPicture->Release();						// Decrements IPicture Reference Count
		return false;							// Return False (Failure)
	}

   	glGetIntegerv(GL_MAX_TEXTURE_SIZE, &glMaxTexDim);			// Get Maximum Texture Size Supported
	
	pPicture->get_Width(&lWidth);						// Get IPicture Width (Convert To Pixels)
	lWidthPixels	= MulDiv(lWidth, GetDeviceCaps(hdcTemp, LOGPIXELSX), 2540);
	pPicture->get_Height(&lHeight);						// Get IPicture Height (Convert To Pixels)
	lHeightPixels	= MulDiv(lHeight, GetDeviceCaps(hdcTemp, LOGPIXELSY), 2540);

	// Resize Image To Closest Power Of Two
	if (lWidthPixels <= glMaxTexDim)					// Is Image Width Less Than Or Equal To Cards Limit
		lWidthPixels = 1 << (int)floor((log((double)lWidthPixels)/log(2.0f)) + 0.5f); 
	else									// Otherwise  Set Width To "Max Power Of Two" That The Card Can Handle
		lWidthPixels = glMaxTexDim;
 
	if (lHeightPixels <= glMaxTexDim)					// Is Image Height Greater Than Cards Limit
		lHeightPixels = 1 << (int)floor((log((double)lHeightPixels)/log(2.0f)) + 0.5f);
	else									// Otherwise  Set Height To "Max Power Of Two" That The Card Can Handle
		lHeightPixels = glMaxTexDim;


	// Create A Temporary Bitmap
	BITMAPINFO	bi = {0};						// The Type Of Bitmap We Request
	DWORD		*pBits = 0;						// Pointer To The Bitmap Bits

	bi.bmiHeader.biSize		= sizeof(BITMAPINFOHEADER);		// Set Structure Size
	bi.bmiHeader.biBitCount		= 32;					// 32 Bit
	bi.bmiHeader.biWidth		= lWidthPixels;				// Power Of Two Width
	bi.bmiHeader.biHeight		= lHeightPixels;			// Make Image Top Up (Positive Y-Axis)
	bi.bmiHeader.biCompression	= BI_RGB;				// RGB Encoding
	bi.bmiHeader.biPlanes		= 1;					// 1 Bitplane

	// Creating A Bitmap This Way Allows Us To Specify Color Depth And Gives Us Imediate Access To The Bits
	hbmpTemp = CreateDIBSection(hdcTemp, &bi, DIB_RGB_COLORS, (void**)&pBits, 0, 0);
	
	if(!hbmpTemp)								// Did Creation Fail?
	{
		DeleteDC(hdcTemp);						// Delete The Device Context
		pPicture->Release();						// Decrements IPicture Reference Count
		return FALSE;							// Return False (Failure)
	}

	SelectObject(hdcTemp, hbmpTemp);					// Select Handle To Our Temp DC And Our Temp Bitmap Object

	// Render The IPicture On To The Bitmap
	pPicture->Render(hdcTemp, 0, 0, lWidthPixels, lHeightPixels, 0, lHeight, lWidth, -lHeight, 0);

	// Convert From BGR To RGB Format And Add An Alpha Value Of 255
	for(long i = 0; i < lWidthPixels * lHeightPixels; i++)			// Loop Through All Of The Pixels
	{
		BYTE* pPixel	= (BYTE*)(&pBits);				// Grab The Current Pixel
		BYTE  temp	= pPixel[0];					// Store 1st Color In Temp Variable (Blue)
		pPixel[0]	= pPixel[2];					// Move Red Value To Correct Position (1st)
		pPixel[2]	= temp;						// Move Temp Value To Correct Blue Position (3rd)
		pPixel[3]	= 255;						// Set The Alpha Value To 255
	}


   /*///////////////////////////////////////////////////////////////
   
   TO DO MAKE FUNC RETURN TEXTURE TO BE STORED IN THE TEXTURE ARRAY
   
   *////////////////////////////////////////////////////////////////

	glGenTextures(1, &TextureStorage);						// Create The Texture

	// Typical Texture Generation Using Data From The Bitmap
	glBindTexture(GL_TEXTURE_2D, TextureStorage);					// Bind To The Texture ID
	glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);		// (Modify This For The Type Of Filtering You Want)
	glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);		// (Modify This For The Type Of Filtering You Want)

	// (Modify This If You Want Mipmaps)	
	glTexImage2D(GL_TEXTURE_2D, 0, 3, lWidthPixels, lHeightPixels, 0, GL_RGBA, GL_UNSIGNED_BYTE, pBits);

	DeleteObject(hbmpTemp);							// Delete The Object
	DeleteDC(hdcTemp);							// Delete The Device Context

	pPicture->Release();							// Decrements IPicture Reference Count

return 1;
}

And now the Win Main Cpp

/*
 *		This Code Was Created By Jeff Molofee 2000
 *		A HUGE Thanks To Fredric Echols For Cleaning Up
 *		And Optimizing This Code, Making It More Flexible!
 *		If You've Found This Code Useful, Please Let Me Know.
 *		Visit My Site At nehe.gamedev.net
 */

#include <windows.h>		// Header File For Windows
#include <gl\gl.h>			// Header File For The OpenGL32 Library
#include <gl\glu.h>			// Header File For The GLu32 Library

#include "HexGui.h"

HDC			hDC=NULL;		// Private GDI Device Context
HGLRC		hRC=NULL;		// Permanent Rendering Context
HWND		hWnd=NULL;		// Holds Our Window Handle
HINSTANCE	hInstance;		// Holds The Instance Of The Application

bool	keys[256];			// Array Used For The Keyboard Routine
bool	active=TRUE;		// Window Active Flag Set To TRUE By Default
bool	fullscreen=TRUE;	// Fullscreen Flag Set To Fullscreen Mode By Default

LRESULT	CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);	// Declaration For WndProc

GLvoid ReSizeGLScene(GLsizei width, GLsizei height)		// Resize And Initialize The GL Window
{
	if (height==0)										// Prevent A Divide By Zero By
	{
		height=1;										// Making Height Equal One
	}

	glViewport(0,0,width,height);						// Reset The Current Viewport

	glMatrixMode(GL_PROJECTION);						// Select The Projection Matrix
	glLoadIdentity();									// Reset The Projection Matrix

	// Calculate The Aspect Ratio Of The Window
	gluPerspective(45.0f,(GLfloat)width/(GLfloat)height,0.1f,100.0f);

	glMatrixMode(GL_MODELVIEW);							// Select The Modelview Matrix
	glLoadIdentity();									// Reset The Modelview Matrix
}

int InitGL(GLvoid)										// All Setup For OpenGL Goes Here
{
	glShadeModel(GL_SMOOTH);							// Enable Smooth Shading
	glEnable(GL_TEXTURE_2D);							// Enable Texture Mapping ( NEW )
	glClearColor(0.0f, 0.0f, 0.0f, 0.5f);				// 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
	glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);	// Really Nice Perspective Calculations
	return TRUE;										// Initialization Went OK
}

int DrawGLScene(GLvoid)									// Here's Where We Do All The Drawing
{
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);	// Clear Screen And Depth Buffer
	glLoadIdentity();									// Reset The Current Modelview Matrix


	return TRUE;										// Everything Went OK
}

GLvoid KillGLWindow(GLvoid)								// Properly Kill The Window
{
	if (fullscreen)										// Are We In Fullscreen Mode?
	{
		ChangeDisplaySettings(NULL,0);					// If So Switch Back To The Desktop
		ShowCursor(TRUE);								// Show Mouse Pointer
	}

	if (hRC)											// Do We Have A Rendering Context?
	{
		if (!wglMakeCurrent(NULL,NULL))					// Are We Able To Release The DC And RC Contexts?
		{
			MessageBox(NULL,"Release Of DC And RC Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
		}

		if (!wglDeleteContext(hRC))						// Are We Able To Delete The RC?
		{
			MessageBox(NULL,"Release Rendering Context Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
		}
		hRC=NULL;										// Set RC To NULL
	}

	if (hDC && !ReleaseDC(hWnd,hDC))					// Are We Able To Release The DC
	{
		MessageBox(NULL,"Release Device Context Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
		hDC=NULL;										// Set DC To NULL
	}

	if (hWnd && !DestroyWindow(hWnd))					// Are We Able To Destroy The Window?
	{
		MessageBox(NULL,"Could Not Release hWnd.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
		hWnd=NULL;										// Set hWnd To NULL
	}

	if (!UnregisterClass("OpenGL",hInstance))			// Are We Able To Unregister Class
	{
		MessageBox(NULL,"Could Not Unregister Class.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
		hInstance=NULL;									// Set hInstance To NULL
	}
}

/*	This Code Creates Our OpenGL Window.  Parameters Are:					*
 *	title			- Title To Appear At The Top Of The Window				*
 *	width			- Width Of The GL Window Or Fullscreen Mode				*
 *	height			- Height Of The GL Window Or Fullscreen Mode			*
 *	bits			- Number Of Bits To Use For Color (8/16/24/32)			*
 *	fullscreenflag	- Use Fullscreen Mode (TRUE) Or Windowed Mode (FALSE)	*/
 
BOOL CreateGLWindow(char* title, int width, int height, int bits, bool fullscreenflag)
{
	GLuint		PixelFormat;			// Holds The Results After Searching For A Match
	WNDCLASS	wc;						// Windows Class Structure
	DWORD		dwExStyle;				// Window Extended Style
	DWORD		dwStyle;				// Window Style
	RECT		WindowRect;				// Grabs Rectangle Upper Left / Lower Right Values
	WindowRect.left=(long)0;			// Set Left Value To 0
	WindowRect.right=(long)width;		// Set Right Value To Requested Width
	WindowRect.top=(long)0;				// Set Top Value To 0
	WindowRect.bottom=(long)height;		// Set Bottom Value To Requested Height

	fullscreen=fullscreenflag;			// Set The Global Fullscreen Flag

	hInstance			= GetModuleHandle(NULL);				// Grab An Instance For Our Window
	wc.style			= CS_HREDRAW | CS_VREDRAW | CS_OWNDC;	// Redraw On Size, And Own DC For Window.
	wc.lpfnWndProc		= (WNDPROC) WndProc;					// WndProc Handles Messages
	wc.cbClsExtra		= 0;									// No Extra Window Data
	wc.cbWndExtra		= 0;									// No Extra Window Data
	wc.hInstance		= hInstance;							// Set The Instance
	wc.hIcon			= LoadIcon(NULL, IDI_WINLOGO);			// Load The Default Icon
	wc.hCursor			= LoadCursor(NULL, IDC_ARROW);			// Load The Arrow Pointer
	wc.hbrBackground	= NULL;									// No Background Required For GL
	wc.lpszMenuName		= NULL;									// We Don't Want A Menu
	wc.lpszClassName	= "OpenGL";								// Set The Class Name

	if (!RegisterClass(&wc))									// Attempt To Register The Window Class
	{
		MessageBox(NULL,"Failed To Register The Window Class.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;											// Return FALSE
	}
	
	if (fullscreen)												// Attempt Fullscreen Mode?
	{
		DEVMODE dmScreenSettings;								// Device Mode
		memset(&dmScreenSettings,0,sizeof(dmScreenSettings));	// Makes Sure Memory's Cleared
		dmScreenSettings.dmSize=sizeof(dmScreenSettings);		// Size Of The Devmode Structure
		dmScreenSettings.dmPelsWidth	= width;				// Selected Screen Width
		dmScreenSettings.dmPelsHeight	= height;				// Selected Screen Height
		dmScreenSettings.dmBitsPerPel	= bits;					// Selected Bits Per Pixel
		dmScreenSettings.dmFields=DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT;

		// Try To Set Selected Mode And Get Results.  NOTE: CDS_FULLSCREEN Gets Rid Of Start Bar.
		if (ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN)!=DISP_CHANGE_SUCCESSFUL)
		{
			// If The Mode Fails, Offer Two Options.  Quit Or Use Windowed Mode.
			if (MessageBox(NULL,"The Requested Fullscreen Mode Is Not Supported By\nYour Video Card. Use Windowed Mode Instead?","NeHe GL",MB_YESNO|MB_ICONEXCLAMATION)==IDYES)
			{
				fullscreen=FALSE;		// Windowed Mode Selected.  Fullscreen = FALSE
			}
			else
			{
				// Pop Up A Message Box Letting User Know The Program Is Closing.
				MessageBox(NULL,"Program Will Now Close.","ERROR",MB_OK|MB_ICONSTOP);
				return FALSE;									// Return FALSE
			}
		}
	}

	if (fullscreen)												// Are We Still In Fullscreen Mode?
	{
		dwExStyle=WS_EX_APPWINDOW;								// Window Extended Style
		dwStyle=WS_POPUP;										// Windows Style
		ShowCursor(FALSE);										// Hide Mouse Pointer
	}
	else
	{
		dwExStyle=WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;			// Window Extended Style
		dwStyle=WS_OVERLAPPEDWINDOW;							// Windows Style
	}

	AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle);		// Adjust Window To True Requested Size

	// Create The Window
	if (!(hWnd=CreateWindowEx(	dwExStyle,							// Extended Style For The Window
								"OpenGL",							// Class Name
								title,								// Window Title
								dwStyle |							// Defined Window Style
								WS_CLIPSIBLINGS |					// Required Window Style
								WS_CLIPCHILDREN,					// Required Window Style
								0, 0,								// Window Position
								WindowRect.right-WindowRect.left,	// Calculate Window Width
								WindowRect.bottom-WindowRect.top,	// Calculate Window Height
								NULL,								// No Parent Window
								NULL,								// No Menu
								hInstance,							// Instance
								NULL)))								// Dont Pass Anything To WM_CREATE
	{
		KillGLWindow();								// Reset The Display
		MessageBox(NULL,"Window Creation Error.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE
	}

	static	PIXELFORMATDESCRIPTOR pfd=				// pfd Tells Windows How We Want Things To Be
	{
		sizeof(PIXELFORMATDESCRIPTOR),				// Size Of This Pixel Format Descriptor
		1,											// Version Number
		PFD_DRAW_TO_WINDOW |						// Format Must Support Window
		PFD_SUPPORT_OPENGL |						// Format Must Support OpenGL
		PFD_DOUBLEBUFFER,							// Must Support Double Buffering
		PFD_TYPE_RGBA,								// Request An RGBA Format
		bits,										// Select Our Color Depth
		0, 0, 0, 0, 0, 0,							// Color Bits Ignored
		0,											// No Alpha Buffer
		0,											// Shift Bit Ignored
		0,											// No Accumulation Buffer
		0, 0, 0, 0,									// Accumulation Bits Ignored
		16,											// 16Bit Z-Buffer (Depth Buffer)  
		0,											// No Stencil Buffer
		0,											// No Auxiliary Buffer
		PFD_MAIN_PLANE,								// Main Drawing Layer
		0,											// Reserved
		0, 0, 0										// Layer Masks Ignored
	};
	
	if (!(hDC=GetDC(hWnd)))							// Did We Get A Device Context?
	{
		KillGLWindow();								// Reset The Display
		MessageBox(NULL,"Can't Create A GL Device Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE
	}

	if (!(PixelFormat=ChoosePixelFormat(hDC,&pfd)))	// Did Windows Find A Matching Pixel Format?
	{
		KillGLWindow();								// Reset The Display
		MessageBox(NULL,"Can't Find A Suitable PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE
	}

	if(!SetPixelFormat(hDC,PixelFormat,&pfd))		// Are We Able To Set The Pixel Format?
	{
		KillGLWindow();								// Reset The Display
		MessageBox(NULL,"Can't Set The PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE
	}

	if (!(hRC=wglCreateContext(hDC)))				// Are We Able To Get A Rendering Context?
	{
		KillGLWindow();								// Reset The Display
		MessageBox(NULL,"Can't Create A GL Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE
	}

	if(!wglMakeCurrent(hDC,hRC))					// Try To Activate The Rendering Context
	{
		KillGLWindow();								// Reset The Display
		MessageBox(NULL,"Can't Activate The GL Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE
	}

	ShowWindow(hWnd,SW_SHOW);						// Show The Window
	SetForegroundWindow(hWnd);						// Slightly Higher Priority
	SetFocus(hWnd);									// Sets Keyboard Focus To The Window
	ReSizeGLScene(width, height);					// Set Up Our Perspective GL Screen

	if (!InitGL())									// Initialize Our Newly Created GL Window
	{
		KillGLWindow();								// Reset The Display
		MessageBox(NULL,"Initialization Failed.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE
	}

	return TRUE;									// Success
}

HEX_GUI::GUI_MANAGER GuiManager;
UINT MouseX;
UINT MouseY;
UINT ButtonState;

LRESULT CALLBACK WndProc(	HWND	hWnd,			// Handle For This Window
							UINT	uMsg,			// Message For This Window
							WPARAM	wParam,			// Additional Message Information
							LPARAM	lParam)			// Additional Message Information
{
	switch (uMsg)									// Check For Windows Messages
	{
		case WM_ACTIVATE:							// Watch For Window Activate Message
		{
			if (!HIWORD(wParam))					// Check Minimization State
			{
				active=TRUE;						// Program Is Active
			}
			else
			{
				active=FALSE;						// Program Is No Longer Active
			}

			return 0;								// Return To The Message Loop
		}

		case WM_SYSCOMMAND:							// Intercept System Commands
		{
			switch (wParam)							// Check System Calls
			{
				case SC_SCREENSAVE:					// Screensaver Trying To Start?
				case SC_MONITORPOWER:				// Monitor Trying To Enter Powersave?
				return 0;							// Prevent From Happening
			}
			break;									// Exit
		}

		case WM_CLOSE:								// Did We Receive A Close Message?
		{
			PostQuitMessage(0);						// Send A Quit Message
			return 0;								// Jump Back
		}

		case WM_KEYDOWN:							// Is A Key Being Held Down?
		{
			keys[wParam] = TRUE;					// If So, Mark It As TRUE
			return 0;								// Jump Back
		}

		case WM_KEYUP:								// Has A Key Been Released?
		{
			keys[wParam] = FALSE;					// If So, Mark It As FALSE
			return 0;								// Jump Back
		}

		case WM_SIZE:								// Resize The OpenGL Window
		{
			ReSizeGLScene(LOWORD(lParam),HIWORD(lParam));  // LoWord=Width, HiWord=Height
			return 0;								// Jump Back
		}

		case WM_MOUSEMOVE:
		{
			MouseX = LOWORD(lParam);
			MouseY = HIWORD(lParam);

			return 0;
		}

		case WM_LBUTTONDOWN:
		{
			ButtonState = 1;
			return 0;
		}

		case WM_LBUTTONUP:
		{
			ButtonState = 0;
			return 0;
		}


	}

	// Pass All Unhandled Messages To DefWindowProc
	return DefWindowProc(hWnd,uMsg,wParam,lParam);
}

int WINAPI WinMain(	HINSTANCE	hInstance,			// Instance
					HINSTANCE	hPrevInstance,		// Previous Instance
					LPSTR		lpCmdLine,			// Command Line Parameters
					int			nCmdShow)			// Window Show State
{
	MSG		msg;									// Windows Message Structure
	BOOL	done=FALSE;								// Bool Variable To Exit Loop

	// Ask The User Which Screen Mode They Prefer
	if (MessageBox(NULL,"Would You Like To Run In Fullscreen Mode?", "Start FullScreen?",MB_YESNO|MB_ICONQUESTION)==IDNO)
	{
		fullscreen=FALSE;							// Windowed Mode
	}
	
	// Create Our OpenGL Window
	if (!CreateGLWindow("NeHe's OpenGL Framework",800,600,32,fullscreen))
	{
		return 0;							// Quit If Window Was Not Created
	}

	
	HEX_GUI::HEX_GUI_DESC HGDesc;
	
	HGDesc.Type = HEX_GUI::Panel;
	HGDesc.ControlPostionX = 0;
	HGDesc.ControlPostionY = 400;
	HGDesc.ControlHeight = 200;
	HGDesc.ControlWidth = 800;
	HGDesc.Visible = true;
	HGDesc.ID = 2;
	GuiManager.AddWindow(HGDesc);

	HGDesc.Type = HEX_GUI::Button;
	HGDesc.Name = "Test Window 2";
	HGDesc.ID = 1;
	HGDesc.Visible = true;
	HGDesc.ControlPostionX =  128;
	HGDesc.ControlPostionY = 256;
	HGDesc.ControlHeight = 32;
	HGDesc.ControlWidth = 128;
	HGDesc.FaceImage = "ButtonUp.jpg";
	HGDesc.DepressedImage = "ButtonDown.jpg";
	HGDesc.HoverImage = "ButtonHover.jpg";
	HGDesc.Flags = GUI_NO_HOVER;
	
	GuiManager.AddWindow(HGDesc);



	HEX_GUI::GUI_MESSAGE GuiMessage;
	ShowCursor(true);
	
	//FPS Calc method for performance 

	while(!done)									// Loop That Runs While done=FALSE
	{
		if (PeekMessage(&msg,NULL,0,0,PM_REMOVE))	// Is There A Message Waiting?
		{

					DrawGLScene();					// Draw The Scene
					GuiManager.InjectMouseInput(MouseX,MouseY,ButtonState); 
					GuiManager.Logic();
					GuiManager.Render();			
					GuiMessage = GuiManager.GetMessage(); 
					SwapBuffers(hDC);				// Swap Buffers (Double Buffering)

			if (msg.message==WM_QUIT)				// Have We Received A Quit Message?
			{
				done=TRUE;							// If So done=TRUE
			}
			else									// If Not, Deal With Window Messages
			{
				TranslateMessage(&msg);				// Translate The Message
				DispatchMessage(&msg);				// Dispatch The Message
			}
			
		}
		else										// If There Are No Messages
		{
			// Draw The Scene.  Watch For ESC Key And Quit Messages From DrawGLScene()
			if (active)								// Program Active?
			{
				if (keys[VK_ESCAPE])				// Was ESC Pressed?
				{
					done=TRUE;						// ESC Signalled A Quit
				}
				else								// Not Time To Quit, Update Screen
				{
							
	
				}
			}

			if (keys[VK_F1])						// Is F1 Being Pressed?
			{
				keys[VK_F1]=FALSE;					// If So Make Key FALSE
				KillGLWindow();						// Kill Our Current Window
				fullscreen=!fullscreen;				// Toggle Fullscreen / Windowed Mode
				// Recreate Our OpenGL Window
				if (!CreateGLWindow("NeHe's OpenGL Framework",640,480,16,fullscreen))
				{
					return 0;						// Quit If Window Was Not Created
				}
			}
		}
	}

	// Shutdown
	KillGLWindow();									// Kill The Window
	return (msg.wParam);							// Exit The Program
}


Please remmeber this is not a full implemention and imporvoments do need to be made so please feel free to mention anything and any imporvment ideas. Thanks and please take your time to respond Regards Jouei

Share this post


Link to post
Share on other sites
Advertisement
	bool GUI_WINDOW::IsSelected(UINT MouseX,UINT MouseY,UINT MouseState)
{
UINT X = GetXPostion();
if(MouseX >= X && MouseX <= (X + GetWidth()))
{
UINT Y = GetYPostion();
if(MouseY >= Y && MouseY <= (Y + GetHeight()))
{
if(MouseState == 1)return true;
}
}
return false;
}

bool GUI_WINDOW::IsHovered(UINT MouseX,UINT MouseY)
{
UINT X = GetXPostion();
if(MouseX >= X && MouseX <= (X + GetWidth()))
{
UINT Y = GetYPostion();
if(MouseY >= Y && MouseY <= (Y + GetHeight()))
{
return true;
}
}
return false;
}

These are essentially the same functions, with the exception that IsSelected also checks if the mouse is clicked. To prevent code duplication, IsSelected could be defined like so:
return IsHovered( MouseX, MouseY ) && MouseState == 1;

You put your class in its own namespace, which isn't bad, but then you write using namespace HEX_GUI, thus invalidating the whole point of putting it in a namespace!

I don't know why you haven't gotten any responses, but the amount of code you've given us is a little daunting. You'd be doing us a favor by finding the smallest sub-group that produces your problem. However, still having the rest of the code, but off to the side helps in case you're wrong.

Also, I don't get what you mean by "The main problem is that it seems the controls textures for the buttons leaked into the panel control sum how."

Share this post


Link to post
Share on other sites
Well it seems that the Textures from the button class were affecting the none textured drawing of the Panel class Eg i just did some base colored textures for testing like red for hover and blue for clicked and white for no action

When i ether hovered or clicked the color of the panel was also changed even though it should of remained what i hade set it too even though it gets set evern time in the render loop for panel..

So even if i set the panels color to be green it would render white and when i hover on the button it would change to the red color and then when i clicked on the button it would change to blue.. however the reverse is not true when i clicked on the panel and or hovered on the panel it does not change anything.

and that is the texturing problem besides that there are no real problems i just would like to know if the overal code itself is in good standing before i continue and have to rewrite abunch of code because i did something dubm back at the start.

Regards Jouei.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!