/
simple_gl_common.cpp
110 lines (90 loc) · 2.2 KB
/
simple_gl_common.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
#include "simple_gl_common.h"
#include <cmath>
#include "GL/glew.h"
#include "common.h" //PI
#include "camera.h"
#include "clock.h"
#include "simple_gl.h"
static float g_transSpeed = 5.0f;
static float g_rotSpeed = PI/4.0f;
static float g_lastFrameSeconds = 0.f;
static Clock<20> g_clock;
void nglPerspective(float fovy, float aspect, float z1, float z2)
{
fovy *= 0.5f; //use only half the angle because interval
//goes from -u to u (2*u)
fovy *= PI/180; //convert to radians
float u = z1*(float)tan(fovy);
float r = u*aspect;
glFrustum(-r, r, -u, u, z1, z2);
}
void updateProjectionMatrix(int w, int h)
{
float aspect = float(w)/float(h);
//initialize matrices and viewport
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
float zNear = 0.1f*128, zFar = 2500.0f*128;
if(w > h)
nglPerspective(2*22.5f, aspect, zNear, zFar);
else
{
//calculate fovy to keep fovx constant
float fovy = (float)atan(tan(22.5f*PI/180)/aspect)*(180/PI);
nglPerspective(2*fovy, aspect, zNear, zFar);
}
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glViewport(0, 0, w, h);
}
void handleCamera()
{
float walkSpeed = g_transSpeed*getLastFrameSeconds();
if(isKeyPressed(BKEY_SHIFT))
walkSpeed *= 10.0f;
if(isKeyPressed(BKEY_CONTROL))
walkSpeed /= 100.0f;
walkSpeed *= 128;
if(isKeyPressed('A'))
walkLeft(walkSpeed);
if(isKeyPressed('D'))
walkRight(walkSpeed);
if(isKeyPressed('W')) {
if (isKeyPressed(BKEY_ALT))
walkUp(walkSpeed);
else
walkForward(walkSpeed);
}
if(isKeyPressed('S')) {
if (isKeyPressed(BKEY_ALT))
walkDown(walkSpeed);
else
walkBack(walkSpeed);
}
float rotSpeed = g_rotSpeed*getLastFrameSeconds();
if(isKeyPressed('J'))
turnLeft(rotSpeed);
if(isKeyPressed('L'))
turnRight(rotSpeed);
if(isKeyPressed('I'))
turnUp(rotSpeed);
if(isKeyPressed('K'))
turnDown(rotSpeed);
if(isKeyPressed('U'))
turnCCW(rotSpeed);
if(isKeyPressed('O'))
turnCW(rotSpeed);
}
void setLastFrameSeconds(float s)
{
g_clock.addValue(s);
g_lastFrameSeconds = s;
}
float getLastFrameSeconds()
{
return g_lastFrameSeconds;
}
float getAverageSecondsPerFrame()
{
return g_clock.getAverage();
}