-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
277 lines (244 loc) · 9.71 KB
/
main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
/*
* This project is to provide a convenient starting place for game-like projects using SDL and OpenGL.
* It includes getting the graphics environment up and running, as well as an example object (SimpleSquare).
* It handles input events for things like exiting (which should take one key press) and movement controls
* (which should depend on current key state at a given frame). It even implements rudimentary physics, meaning
* that it records time to calculate a semi-accurate time step by which to multiply the velocity of an object to
* produce displacement over the time it took to generate the frame.
* Hopefully this code is easy to understand and expand. Some difficulty in readability may occur due to all the
* error checking that I have included, but I think it's worth it.
*/
#include <iostream>
#include <SDL.h>
#include <GL/glew.h>
#include "SimpleSquare.h"
#define RESOLUTION_X 800
#define RESOLUTION_Y 600
#define GLVERSION_MAJOR 3
#define GLVERSION_MINOR 3
#define SCREENOPTIONS SDL_WINDOW_OPENGL // | SDL_WINDOW_FULLSCREEN_DESKTOP
#define USE_VSYNC
#define CLEARCOLOR 0.0f,0.0f,0.0f,1.0f
#define USE_TRANSPARENCY
#define USE_DEPTHBUFFER
#define USE_BACKFACE_CULLING
//#define DEBUG_DRIVERS
#define OUTSTREAM std::cout
SDL_Window* pWindow; // The SDL window
SDL_GLContext context; // The openGL context
SimpleSquare square; // The square object to render
unsigned previousTime, currentTime, deltaTime; // Used to regulate physics time step
void mainLoop();
bool initGL ();
void checkGlError(int line = -1);
void checkSDLError(int line = -1);
void cleanup();
int main(int argc, char* argv[]) {
if (!initGL()) { // if init fails, exit
return 1;
}
OUTSTREAM << square.init();
previousTime = SDL_GetTicks();
mainLoop();
cleanup();
return 0;
}
void mainLoop() {
bool loop = true;
while (loop) {
/**************************** HANDLE EVENTS *********************************/
SDL_Event event;
while (SDL_PollEvent(&event)) { // process all accumulated events
if (event.type == SDL_QUIT) { // quit events (like if you press the x)
loop = false;
} else if (event.type == SDL_KEYDOWN) { // keydown events (generated only once per key press)
switch (event.key.keysym.sym) {
case SDLK_ESCAPE:
loop = false;
break;
default:
break;
}
}
}
/**************************** HANDLE KEY STATE *********************************/
// calculate square movement speed with appropriate time step:
currentTime = SDL_GetTicks();
deltaTime = currentTime - previousTime;
previousTime = currentTime;
// Get current keyboard state ( this is used for smooth controls rather than key press event controls above )
const Uint8* keyStates = SDL_GetKeyboardState(NULL);
// apply movement according to which keys are down
float squareSpeed = 0.001f * deltaTime;
if (keyStates[SDL_SCANCODE_UP]) {
square.translate(0.0f, squareSpeed, 0.0f);
}
if (keyStates[SDL_SCANCODE_DOWN]) {
square.translate(0.0f, -squareSpeed, 0.0f);
}
if (keyStates[SDL_SCANCODE_LEFT]) {
square.translate(-squareSpeed, 0.0f, 0.0f);
}
if (keyStates[SDL_SCANCODE_RIGHT]) {
square.translate(squareSpeed, 0.0f, 0.0f);
}
/**************************** DO THE DRAWING *********************************/
// clear the buffer
glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
// draw the square
square.draw();
// swap frame buffers (back buffer was drawn, will now be shown)
SDL_GL_SwapWindow(pWindow);
}
}
bool initGL() {
#ifdef DEBUG_DRIVERS /************ DEBUG DRIVERS ********************************/
// Identify video drivers (this is for debug)
OUTSTREAM << "\nSDL found the following video drivers:\n";
int numdrivers = SDL_GetNumVideoDrivers();
const char* drivername;
for (int i = 0; i < numdrivers; ++i) {
drivername = SDL_GetVideoDriver(i);
if (SDL_VideoInit(drivername) == 0) {
SDL_VideoQuit();
OUTSTREAM << "\t\t Driver " << drivername << " works.\n";
}
else {
OUTSTREAM << "\t<!>\tDriver " << drivername << " DOES NOT WORK!\n";
}
}
// Identify render drivers (this is for debug)
OUTSTREAM << "SDL found the following render drivers: ";
numdrivers = SDL_GetNumRenderDrivers();
for (int i = 0; i < numdrivers; ++i) {
SDL_RendererInfo info;
SDL_GetRenderDriverInfo(i, &info);
OUTSTREAM << info.name << ((i < numdrivers - 1)? ", " : "\n");
}
#endif /************************** DEBUG DRIVERS ********************************/
// Initialize SDL overall.
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
OUTSTREAM << "<!> SDL did not initialize! SDL Error: " << SDL_GetError() << std::endl;
return false;
}
// SDL_GL_CONTEXT_CORE gives us only the newer version, deprecated functions are disabled
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
// Specify OpenGL version
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, GLVERSION_MAJOR);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, GLVERSION_MINOR);
// Turn on double buffering with a 24bit Z buffer.
// You may need to change this to 16 or 32 for your system
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
// Create the SDL window
pWindow = SDL_CreateWindow("OpenGL Window", // name of window
SDL_WINDOWPOS_CENTERED, // x position of window
SDL_WINDOWPOS_CENTERED, // y position of window
RESOLUTION_X, RESOLUTION_Y, // x and y width of window
SCREENOPTIONS); // options (fullscreen, etc)
// If the window couldn't be created for whatever reason
if (pWindow == NULL) {
OUTSTREAM << "<!> SDL window was not created! SDL Error: " << SDL_GetError() << std::endl;
return false;
}
else {
OUTSTREAM << "SDL window created.\n";
}
//Create context
context = SDL_GL_CreateContext(pWindow); //context is the place where openGL can draw
if(context == NULL) {
OUTSTREAM << "<!> OpenGL context was not created! SDL Error: " << SDL_GetError() << std::endl;
return false;
}
else {
OUTSTREAM << "GL context created.\n";
}
checkGlError(__LINE__);
//Initialize GLEW (openGL Extensions Wrangler)
glewExperimental = GL_TRUE; // Sometimes things wont work without this line
GLenum glewError = glewInit(); // GL enumerator error is thrown here when using openGL versions 3.2+ It's fine.
// see https://www.opengl.org/wiki/OpenGL_Loading_Library
if(glewError != GLEW_OK) {
OUTSTREAM << "<!> Could not initialize GLEW! " << glewGetErrorString(glewError) << std::endl;
return false;
}
else {
OUTSTREAM << "GLEW initialized.\n";
}
checkGlError(__LINE__);
#ifdef USE_VSYNC /************ USE VSYNC ********************************/
if (SDL_GL_SetSwapInterval(1) < 0) {
OUTSTREAM << "<!> Warning: Unable to set VSync! SDL Error: " << SDL_GetError() << std::endl;
// Do not return. This is not an essential functionality.
}
else {
OUTSTREAM << "VSync enabled.\n";
}
#endif /********************** USE VSYNC ********************************/
// set openGL clear color
glClearColor(CLEARCOLOR);
#ifdef USE_DEPTHBUFFER
// enable the occlusion of objects hidden behind other objects (using the depth buffer)
glEnable(GL_DEPTH_TEST);
// set the test for that occlusion to: "draw if distance of new fragment is less than or equal to old fragment"
glDepthFunc(GL_LEQUAL);
#endif
#ifdef USE_BACKFACE_CULLING
// enable the culling of back faces (back faces will not be drawn)
glEnable(GL_CULL_FACE);
#endif
#ifdef USE_TRANSPARENCY
// enable transparency
glEnable (GL_BLEND);
// set transparency function (this is standard transparency)
glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
#endif
checkGlError(__LINE__);
checkSDLError(__LINE__);
return true;
}
/*
* DO NOT call this function before the gl context has initialized. It will make an infinite loop.
* This is because glGetError always returns GL_INVALID_OPERATION before there exists a context. There's
* code in here to catch the loop and stop, but it will still produce unnecessary scary output.
*/
void checkGlError(int line /*= -1*/) {
GLenum glErr = glGetError();
if (glErr != GL_NO_ERROR) {
OUTSTREAM << "<!> GL error(s) detected";
if (line > 0) {
OUTSTREAM << " at line " << line;
}
OUTSTREAM << ":\n";
int loopGuard = 0;
while (glErr != GL_NO_ERROR) {
if (++loopGuard <= 10) {
OUTSTREAM << "\t\t\t" << gluErrorString(glErr) << std::endl;
glErr = glGetError();
}
else {
OUTSTREAM << "\t\t\t<!> Suppressing further errors...\n";
break;
}
}
}
}
void checkSDLError(int line /*= -1*/) {
std::string error = SDL_GetError();
if (error != "") {
OUTSTREAM << "<!> SLD Error";
if (line > 0) {
OUTSTREAM << " at line " << line;
}
OUTSTREAM << ": " << error;
SDL_ClearError();
}
}
void cleanup() {
// There is probably more cleanup to do. This
// Delete our OpengL context
SDL_GL_DeleteContext(context);
// Destroy our window
SDL_DestroyWindow(pWindow);
// Shutdown SDL 2
SDL_Quit();
}