studies/grafik/Computergrafik-Code7/cgapplication.cpp
⇒
download file
1
2
3
4
5
6
7
8
9 #include "cgapplication.h"
10
11
12 static CGApplication* activeApplication_ = 0;
13
14
15 static int lastDragDropX_ = 0;
16 static int lastDragDropY_ = 0;
17
18
19 CGApplication::CGApplication() {
20 assert(!activeApplication_);
21 activeApplication_ = this;
22 }
23
24 CGApplication::~CGApplication() {
25 activeApplication_ = 0;
26 }
27
28
29 void CGApplication::onInit() { }
30 void CGApplication::onButton(MouseButton button, int x, int y) { }
31 void CGApplication::onMove(int x, int y) { }
32 void CGApplication::onDrag(double dx, double dy) { }
33 void CGApplication::onKey(unsigned char key) { }
34 void CGApplication::onIdle() { }
35
36
37 static void displayFunc() {
38 assert(activeApplication_);
39 activeApplication_->onDraw();
40 }
41
42
43 static void reshapeFunc(int newWidth, int newHeight) {
44 assert(activeApplication_);
45 activeApplication_->onSize(newWidth, newHeight);
46 }
47
48
49 static void mouseFunc(int button, int state, int x, int y) {
50 assert(activeApplication_);
51
52 if(state == GLUT_DOWN) {
53 y = glutGet(GLenum(GLUT_WINDOW_HEIGHT)) - y;
54 if(button == GLUT_LEFT_BUTTON) {
55 activeApplication_->onButton(CGApplication::LeftMouseButton, x, y);
56 } else {
57 activeApplication_->onButton(CGApplication::RightMouseButton, x, y);
58 }
59
60 lastDragDropX_ = x;
61 lastDragDropY_ = y;
62 }
63 }
64
65
66 static void motionFunc(int x, int y) {
67 assert(activeApplication_);
68
69 y = glutGet(GLenum(GLUT_WINDOW_HEIGHT)) - y;
70
71 double distanceX = x - lastDragDropX_;
72 double distanceY = y - lastDragDropY_;
73
74 activeApplication_->onMove(x, y);
75
76 double relativeX = distanceX / GLenum(GLUT_WINDOW_WIDTH);
77 double relativeY = distanceY / GLenum(GLUT_WINDOW_HEIGHT);
78
79
80 activeApplication_->onDrag(relativeX, relativeY);
81
82 lastDragDropX_ = x;
83 lastDragDropY_ = y;
84 }
85
86
87 static void keyboardFunc(unsigned char key, int x, int y) {
88 assert(activeApplication_);
89 activeApplication_->onKey(key);
90 }
91
92
93
94 static void idleFunc() {
95 assert(activeApplication_);
96 activeApplication_->onIdle();
97 }
98 void CGApplication::start(const char* windowTitle, bool doubleBuffering,
99 unsigned long width, unsigned long height) {
100
101 glutInitDisplayMode(GLUT_RGB | (doubleBuffering ? GLUT_DOUBLE : GLUT_SINGLE));
102
103
104 glutInitWindowSize(width, height);
105
106
107 glutCreateWindow(windowTitle);
108
109
110
111 glutDisplayFunc(displayFunc);
112 glutReshapeFunc(reshapeFunc);
113 glutMouseFunc(mouseFunc);
114 glutMotionFunc(motionFunc);
115 glutKeyboardFunc(keyboardFunc);
116 glutIdleFunc(idleFunc);
117
118
119 glutShowWindow();
120
121
122 onInit();
123
124
125 glutMainLoop();
126 }
127
128 void CGApplication::swapBuffers() {
129 glutSwapBuffers();
130 }
131
132