include GL glu include GLFW glfw3 include iostream include vector stru

 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
#include <GL/glu.h>
#include <GLFW/glfw3.h>
#include <iostream>
#include <vector>
struct Point {
int x, y;
};
int WIDTH = 640, HEIGHT = 480;
std::vector<Point> polygon;
void error_callback(int error, const char* description) {
fputs(description, stderr);
}
void put_angles(GLFWwindow* window, int button, int action, int mods){
if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_PRESS) {
double x, y;
glfwGetCursorPos(window, &x, &y);
y = HEIGHT - (int)y;
polygon.push_back({ (int)x, (int)y });
}
}
void project(double width, double height) {
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0, width, 0, height);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void window_size_callback(GLFWwindow* window, int width, int height) {
glViewport(0, 0, width, height);
project(width, height);
}
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) {
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) {
glfwSetWindowShouldClose(window, GL_TRUE);
} else if (key == GLFW_KEY_SPACE && action == GLFW_PRESS) {
polygon.push_back(polygon[0]);
}
}
void init(GLFWwindow* window, int width, int height) {
glfwMakeContextCurrent(window);
glfwSetKeyCallback(window, key_callback);
glfwSetWindowSizeCallback(window, window_size_callback);
glfwSetMouseButtonCallback(window, put_angles);
glClearColor(0, 0, 0, 0);
project(width, height);
}
void display() {
glColor3d(0, 100, 0);
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_LINE_STRIP);
for (Point p: polygon) {
glVertex2d(p.x, p.y);
}
glEnd();
}
int main() {
GLFWwindow* window;
int width = WIDTH, height = HEIGHT;
glfwSetErrorCallback(error_callback);
if (!glfwInit()) {
exit(EXIT_FAILURE);
}
window = glfwCreateWindow(width, height, "lab4", nullptr, nullptr);
if (!window) {
glfwTerminate();
exit(EXIT_FAILURE);
}
init(window, width, height);
while (!glfwWindowShouldClose(window)) {
display();
glfwSwapBuffers(window);
glfwWaitEvents();
}
glfwDestroyWindow(window);
glfwTerminate();
exit(EXIT_SUCCESS);
}