Guide to Game Development/Rendering and Game Engines/OpenGL/GLUT/Basic 3D window creation
Here's the C++ code for creating a basic perspective window for a 3D environment[1]:
#include <iostream>
#include <glut.h>
using namespace std;
void Init() {
glClearColor(0.2, 0.0, 0.0, 0.0); //Write your openGL set-up commands
}
void Display() {
//OpenGL functions to draw a basic triangle
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glBegin(GL_TRIANGLES);
glColor3f(1.0,0.0,0.0);
glVertex3f(-1.0, -1.0, -3.0);
glColor3f(0.0,1.0,0.0);
glVertex3f(0.0, 1.0, -3.0);
glColor3f(0.0,0.0,1.0);
glVertex3f(1.0, -1.0, -3.0);
glEnd();
//
glutSwapBuffers(); //Swaps the double-buffer
}
void Reshape(int w, int h){
//This fixes resize problems
if (h == 0){
h = 1;
}
float ratio = (float)w/h;
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glViewport(0,0,w,h);
gluPerspective(45, //FOV
ratio, //Aspect Ratio
0.01, //Closest thing you can see
1000); //Furthest thing you can see
glMatrixMode(GL_MODELVIEW);
}
int main(int Argc, char** Argv) {
glutInit(&Argc, Argv); //Allows glut to initiate with the parameters of main
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | 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(); //Other setups you need
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- ↑ Small parts of code were altered and changed from this playlist: https://www.youtube.com/playlist?list=PL2E88A9FE78FBF3B8