50% developed

Guide to Game Development/Rendering and Game Engines/OpenGL/GLUT/Basic 2D window creation

From Wikibooks, open books for an open world
Jump to navigation Jump to search

This is some code that you can use for a basic orthographic set-up in a 2D environment[1].

#include <glut.h>
void Display() {
        //OpenGL code used as a viewing example to show it works
	glClear(GL_COLOR_BUFFER_BIT);
	glColor3f(1.0, 1.0, 1.0);
	glBegin(GL_LINES);
		glVertex3f(0.25, 0.25, 0.0);
		glVertex3f(0.75, 0.75, 0.0);
	glEnd();

	glutSwapBuffers(); //Swaps the double-buffer
}

void Init() {
        //Background colour
	glClearColor(0.0, 0.0, 0.0, 0.0);
	glMatrixMode(GL_PROJECTION);
        //Set-up the scene for as Orthographic
	glLoadIdentity();
	glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0);
}

int main(int iArgc, char** cppArgv) {
	glutInit(&iArgc, cppArgv); //Allows glut to initiate with the parameters of main
	glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); //Double buffering, RGBA colour space, Depth buffer (displays things in the correct order, things don't overlap in the wrong order)
	glutInitWindowSize(250, 250); //Sets the size of the window
	glutInitWindowPosition(200, 200); //Positions the window where 0,0 is the top left corner of your screen
	glutCreateWindow("GLUT Window"); //Create the window with the name provided
	Init(); //Set-up what you need to
	glutReshapeFunc(Reshape); //Sets the function that wants to be called when the form is resized
	glutDisplayFunc(Display); //the tick function that gets called as fast as it can to update the graphics
        glutIdleFunc(Display); //Constantly recall the display function
	glutMainLoop(); //Starts the glut tick loop cycle
	return 0;
}

References[edit | edit source]

  1. All of the code was taken from: https://www.youtube.com/watch?v=TH_hA_Sru6Q and then slightly modified and commented