forked from LiamHz/atlas
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
652 lines (528 loc) · 22.7 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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
#include <cmath>
#include <string>
#include <random>
#include <iostream>
#include <math.h>
#include <cstdlib>
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#define TINYOBJLOADER_IMPLEMENTATION
#include "tiny_obj_loader.h"
#include "shader.h"
#include "camera.h"
#include "perlin.h"
const GLint WIDTH = 1920, HEIGHT = 1080;
// Structs
struct plant {
std::string type;
float xpos;
float ypos;
float zpos;
int xOffset;
int yOffset;
plant(std::string _type, float _xpos, float _ypos, float _zpos, int _xOffset, int _yOffset) {
type = _type;
xpos = _xpos;
ypos = _ypos;
zpos = _zpos;
xOffset = _xOffset;
yOffset = _yOffset;
}
};
// Functions
int init();
void processInput(GLFWwindow *window, Shader &shader);
void mouse_callback(GLFWwindow *window, double xpos, double ypos);
void scroll_callback(GLFWwindow* window, double xoffset, double yoffset);
void render(std::vector<GLuint> &map_chunks, Shader &shader, glm::mat4 &view, glm::mat4 &model, glm::mat4 &projection, int &nIndices, std::vector<GLuint> &tree_chunks, std::vector<GLuint> &flower_chunks);
std::vector<int> generate_indices();
std::vector<float> generate_noise_map(int xOffset, int yOffset);
std::vector<float> generate_vertices(const std::vector<float> &noise_map);
std::vector<float> generate_normals(const std::vector<int> &indices, const std::vector<float> &vertices);
std::vector<float> generate_biome(const std::vector<float> &vertices, std::vector<plant> &plants, int xOffset, int yOffset);
void generate_map_chunk(GLuint &VAO, int xOffset, int yOffset, std::vector<plant> &plants);
void load_model(GLuint &VAO, std::string filename);
void setup_instancing(GLuint &VAO, std::vector<GLuint> &plant_chunk, std::string plant_type, std::vector<plant> &plants, std::string filename);
GLFWwindow *window;
// Map params
float WATER_HEIGHT = 0.1;
int chunk_render_distance = 3;
int xMapChunks = 10;
int yMapChunks = 10;
int chunkWidth = 127;
int chunkHeight = 127;
int gridPosX = 0;
int gridPosY = 0;
float originX = (chunkWidth * xMapChunks) / 2 - chunkWidth / 2;
float originY = (chunkHeight * yMapChunks) / 2 - chunkHeight / 2;
// Noise params
int octaves = 5;
float meshHeight = 32; // Vertical scaling
float noiseScale = 64; // Horizontal scaling
float persistence = 0.5;
float lacunarity = 2;
// Model params
float MODEL_SCALE = 3;
float MODEL_BRIGHTNESS = 6;
// FPS
double lastTime = glfwGetTime();
int nbFrames = 0;
// Camera
Camera camera(glm::vec3(originX, 20.0f, originY));
bool firstMouse = true;
float lastX = WIDTH / 2;
float lastY = HEIGHT / 2;
// Timing
float deltaTime = 0.0f;
float lastFrame = 0.0f;
float currentFrame;
int main() {
// Initalize variables
glm::mat4 view;
glm::mat4 model;
glm::mat4 projection;
std::vector<plant> plants;
// Initialize GLFW and GLAD
if (init() != 0)
return -1;
Shader objectShader("objectShader.vert", "objectShader.frag");
// Default to coloring to flat mode
objectShader.use();
objectShader.setBool("isFlat", true);
// Lighting intensities and direction
objectShader.setVec3("light.ambient", 0.2, 0.2, 0.2);
objectShader.setVec3("light.diffuse", 0.3, 0.3, 0.3);
objectShader.setVec3("light.specular", 1.0, 1.0, 1.0);
objectShader.setVec3("light.direction", -0.2f, -1.0f, -0.3f);
std::vector<GLuint> map_chunks(xMapChunks * yMapChunks);
for (int y = 0; y < yMapChunks; y++)
for (int x = 0; x < xMapChunks; x++) {
generate_map_chunk(map_chunks[x + y*xMapChunks], x, y, plants);
}
int nIndices = chunkWidth * chunkHeight * 6;
GLuint treeVAO, flowerVAO;
std::vector<GLuint> tree_chunks(xMapChunks * yMapChunks);
std::vector<GLuint> flower_chunks(xMapChunks * yMapChunks);
setup_instancing(treeVAO, tree_chunks, "tree", plants, "CommonTree_1.obj");
setup_instancing(flowerVAO, flower_chunks, "flower", plants, "Flowers.obj");
while (!glfwWindowShouldClose(window)) {
objectShader.use();
projection = glm::perspective(glm::radians(camera.Zoom), (float)WIDTH / (float)HEIGHT, 0.1f, (float)chunkWidth * (chunk_render_distance - 1.2f));
view = camera.GetViewMatrix();
objectShader.setMat4("u_projection", projection);
objectShader.setMat4("u_view", view);
objectShader.setVec3("u_viewPos", camera.Position);
render(map_chunks, objectShader, view, model, projection, nIndices, tree_chunks, flower_chunks);
}
for (int i = 0; i < map_chunks.size(); i++) {
glDeleteVertexArrays(1, &map_chunks[i]);
glDeleteVertexArrays(1, &tree_chunks[i]);
glDeleteVertexArrays(1, &flower_chunks[i]);
}
// TODO VBOs and EBOs aren't being deleted
// glDeleteBuffers(3, VBO);
// glDeleteBuffers(1, &EBO);
glfwTerminate();
return 0;
}
void setup_instancing(GLuint &VAO, std::vector<GLuint> &plant_chunk, std::string plant_type, std::vector<plant> &plants, std::string filename) {
std::vector<std::vector<float>> chunkInstances;
chunkInstances.resize(xMapChunks * yMapChunks);
// Instancing prep
for (int i = 0; i < plants.size(); i++) {
float xPos = plants[i].xpos / MODEL_SCALE;
float yPos = plants[i].ypos / MODEL_SCALE;
float zPos = plants[i].zpos / MODEL_SCALE;
int pos = plants[i].xOffset + plants[i].yOffset*xMapChunks;
if (plants[i].type == plant_type) {
chunkInstances[pos].push_back(xPos);
chunkInstances[pos].push_back(yPos);
chunkInstances[pos].push_back(zPos);
}
}
GLuint instancesVBO[xMapChunks * yMapChunks];
glGenBuffers(xMapChunks * yMapChunks, instancesVBO);
for (int y = 0; y < yMapChunks; y++) {
for (int x = 0; x < xMapChunks; x++) {
int pos = x + y*xMapChunks;
load_model(plant_chunk[pos], filename);
glBindVertexArray(plant_chunk[pos]);
glBindBuffer(GL_ARRAY_BUFFER, instancesVBO[pos]);
glBufferData(GL_ARRAY_BUFFER, sizeof(float) * chunkInstances[pos].size(), &chunkInstances[pos][0], GL_STATIC_DRAW);
glEnableVertexAttribArray(3);
glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
// Instanced array
// Move to next vertex attrib on next instance of object
glVertexAttribDivisor(3, 1);
}
}
}
void render(std::vector<GLuint> &map_chunks, Shader &shader, glm::mat4 &view, glm::mat4 &model, glm::mat4 &projection, int &nIndices, std::vector<GLuint> &tree_chunks, std::vector<GLuint> &flower_chunks) {
// Per-frame time logic
currentFrame = glfwGetTime();
deltaTime = currentFrame - lastFrame;
lastFrame = currentFrame;
processInput(window, shader);
glClearColor(0.53, 0.81, 0.92, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Measures number of map chunks away from origin map chunk the camera is
gridPosX = (int)(camera.Position.x - originX) / chunkWidth + xMapChunks / 2;
gridPosY = (int)(camera.Position.z - originY) / chunkHeight + yMapChunks / 2;
// Render map chunks
for (int y = 0; y < yMapChunks; y++)
for (int x = 0; x < xMapChunks; x++) {
// Only render chunk if it's within render distance
if (std::abs(gridPosX - x) <= chunk_render_distance && (y - gridPosY) <= chunk_render_distance) {
model = glm::mat4(1.0f);
model = glm::translate(model, glm::vec3(-chunkWidth / 2.0 + (chunkWidth - 1) * x, 0.0, -chunkHeight / 2.0 + (chunkHeight - 1) * y));
shader.setMat4("u_model", model);
// Terrain chunk
glBindVertexArray(map_chunks[x + y*xMapChunks]);
glDrawElements(GL_TRIANGLES, nIndices, GL_UNSIGNED_INT, 0);
// Plant chunks
model = glm::mat4(1.0f);
model = glm::translate(model, glm::vec3(-chunkWidth / 2.0 + (chunkWidth - 1) * x, 0.0, -chunkHeight / 2.0 + (chunkHeight - 1) * y));
model = glm::scale(model, glm::vec3(MODEL_SCALE));
shader.setMat4("u_model", model);
glEnable(GL_CULL_FACE);
glBindVertexArray(flower_chunks[x + y*xMapChunks]);
glDrawArraysInstanced(GL_TRIANGLES, 0, 1300, 16);
glBindVertexArray(tree_chunks[x + y*xMapChunks]);
glDrawArraysInstanced(GL_TRIANGLES, 0, 10192, 8);
glDisable(GL_CULL_FACE);
}
}
// Measure speed in ms per frame
double currentTime = glfwGetTime();
nbFrames++;
// If last prinf() was more than 1 sec ago printf and reset timer
if (currentTime - lastTime >= 1.0 ){
printf("%f ms/frame\n", 1000.0/double(nbFrames));
nbFrames = 0;
lastTime += 1.0;
}
// Use double buffer
// Only swap old frame with new when it is completed
glfwPollEvents();
glfwSwapBuffers(window);
}
void load_model(GLuint &VAO, std::string filename) {
std::vector<float> vertices;
std::vector<int> indices;
tinyobj::attrib_t attrib;
std::vector<tinyobj::shape_t> shapes;
std::vector<tinyobj::material_t> materials;
std::string warn;
std::string err;
tinyobj::LoadObj(&attrib, &shapes, &materials, &warn, &err, filename.c_str());
if (!warn.empty()) {
std::cout << warn << std::endl;
} else if (!err.empty()) {
std::cerr << err << std::endl;
}
for (size_t s = 0; s < shapes.size(); s++) {
// Loop over faces(polygon)
size_t index_offset = 0;
for (size_t f = 0; f < shapes[s].mesh.num_face_vertices.size(); f++) {
int fv = shapes[s].mesh.num_face_vertices[f];
// Loop over vertices in the face.
for (size_t v = 0; v < fv; v++) {
tinyobj::index_t idx = shapes[s].mesh.indices[index_offset + v];
vertices.push_back(attrib.vertices[3*idx.vertex_index+0]);
vertices.push_back(attrib.vertices[3*idx.vertex_index+1]);
vertices.push_back(attrib.vertices[3*idx.vertex_index+2]);
vertices.push_back(attrib.normals[3*idx.normal_index+0]);
vertices.push_back(attrib.normals[3*idx.normal_index+1]);
vertices.push_back(attrib.normals[3*idx.normal_index+2]);
vertices.push_back(materials[shapes[s].mesh.material_ids[f]].diffuse[0] * MODEL_BRIGHTNESS);
vertices.push_back(materials[shapes[s].mesh.material_ids[f]].diffuse[1] * MODEL_BRIGHTNESS);
vertices.push_back(materials[shapes[s].mesh.material_ids[f]].diffuse[2] * MODEL_BRIGHTNESS);
}
index_offset += fv;
}
}
GLuint VBO, EBO;
// Create buffers and arrays
glGenBuffers(1, &VBO);
glGenBuffers(1, &EBO);
glGenVertexArrays(1, &VAO);
// Bind vertices to VBO
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(float), &vertices[0], GL_STATIC_DRAW);
// Configure vertex position attribute
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 9 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
// Configure vertex normals attribute
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 9 * sizeof(float), (void*)(3 * sizeof(float)));
glEnableVertexAttribArray(1);
// Configure vertex color attribute
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 9 * sizeof(float), (void*)(6 * sizeof(float)));
glEnableVertexAttribArray(2);
}
void generate_map_chunk(GLuint &VAO, int xOffset, int yOffset, std::vector<plant> &plants) {
std::vector<int> indices;
std::vector<float> noise_map;
std::vector<float> vertices;
std::vector<float> normals;
std::vector<float> colors;
// Generate map
indices = generate_indices();
noise_map = generate_noise_map(xOffset, yOffset);
vertices = generate_vertices(noise_map);
normals = generate_normals(indices, vertices);
colors = generate_biome(vertices, plants, xOffset, yOffset);
GLuint VBO[3], EBO;
// Create buffers and arrays
glGenBuffers(3, VBO);
glGenBuffers(1, &EBO);
glGenVertexArrays(1, &VAO);
// Bind vertices to VBO
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO[0]);
glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(float), &vertices[0], GL_STATIC_DRAW);
// Create element buffer
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(int), &indices[0], GL_STATIC_DRAW);
// Configure vertex position attribute
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
// Bind vertices to VBO
glBindBuffer(GL_ARRAY_BUFFER, VBO[1]);
glBufferData(GL_ARRAY_BUFFER, normals.size() * sizeof(float), &normals[0], GL_STATIC_DRAW);
// Configure vertex normals attribute
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glEnableVertexAttribArray(1);
// Bind vertices to VBO
glBindBuffer(GL_ARRAY_BUFFER, VBO[2]);
glBufferData(GL_ARRAY_BUFFER, colors.size() * sizeof(float), &colors[0], GL_STATIC_DRAW);
// Configure vertex colors attribute
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glEnableVertexAttribArray(2);
}
glm::vec3 get_color(int r, int g, int b) {
return glm::vec3(r/255.0, g/255.0, b/255.0);
}
std::vector<float> generate_noise_map(int offsetX, int offsetY) {
std::vector<float> noiseValues;
std::vector<float> normalizedNoiseValues;
std::vector<int> p = get_permutation_vector();
float amp = 1;
float freq = 1;
float maxPossibleHeight = 0;
for (int i = 0; i < octaves; i++) {
maxPossibleHeight += amp;
amp *= persistence;
}
for (int y = 0; y < chunkHeight; y++) {
for (int x = 0; x < chunkWidth; x++) {
amp = 1;
freq = 1;
float noiseHeight = 0;
for (int i = 0; i < octaves; i++) {
float xSample = (x + offsetX * (chunkWidth-1)) / noiseScale * freq;
float ySample = (y + offsetY * (chunkHeight-1)) / noiseScale * freq;
float perlinValue = perlin_noise(xSample, ySample, p);
noiseHeight += perlinValue * amp;
// Lacunarity --> Increase in frequency of octaves
// Persistence --> Decrease in amplitude of octaves
amp *= persistence;
freq *= lacunarity;
}
noiseValues.push_back(noiseHeight);
}
}
for (int y = 0; y < chunkHeight; y++) {
for (int x = 0; x < chunkWidth; x++) {
// Inverse lerp and scale values to range from 0 to 1
normalizedNoiseValues.push_back((noiseValues[x + y*chunkWidth] + 1) / maxPossibleHeight);
}
}
return normalizedNoiseValues;
}
struct terrainColor {
terrainColor(float _height, glm::vec3 _color) {
height = _height;
color = _color;
};
float height;
glm::vec3 color;
};
std::vector<float> generate_biome(const std::vector<float> &vertices, std::vector<plant> &plants, int xOffset, int yOffset) {
std::vector<float> colors;
std::vector<terrainColor> biomeColors;
glm::vec3 color = get_color(255, 255, 255);
// NOTE: Terrain color height is a value between 0 and 1
biomeColors.push_back(terrainColor(WATER_HEIGHT * 0.5, get_color(60, 95, 190))); // Deep water
biomeColors.push_back(terrainColor(WATER_HEIGHT, get_color(60, 100, 190))); // Shallow water
biomeColors.push_back(terrainColor(0.15, get_color(210, 215, 130))); // Sand
biomeColors.push_back(terrainColor(0.30, get_color( 95, 165, 30))); // Grass 1
biomeColors.push_back(terrainColor(0.40, get_color( 65, 115, 20))); // Grass 2
biomeColors.push_back(terrainColor(0.50, get_color( 90, 65, 60))); // Rock 1
biomeColors.push_back(terrainColor(0.80, get_color( 75, 60, 55))); // Rock 2
biomeColors.push_back(terrainColor(1.00, get_color(255, 255, 255))); // Snow
std::string plantType;
// Determine which color to assign each vertex by its y-coord
// Iterate through vertex y values
for (int i = 1; i < vertices.size(); i += 3) {
for (int j = 0; j < biomeColors.size(); j++) {
// NOTE: The max height of a vertex is "meshHeight"
if (vertices[i] <= biomeColors[j].height * meshHeight) {
color = biomeColors[j].color;
if (j == 3) {
if (rand() % 1000 < 5) {
if (rand() % 100 < 70) {
plantType = "flower";
} else {
plantType = "tree";
}
plants.push_back(plant{plantType, vertices[i-1], vertices[i], vertices[i+1], xOffset, yOffset});
}
}
break;
}
}
colors.push_back(color.r);
colors.push_back(color.g);
colors.push_back(color.b);
}
return colors;
}
std::vector<float> generate_normals(const std::vector<int> &indices, const std::vector<float> &vertices) {
int pos;
glm::vec3 normal;
std::vector<float> normals;
std::vector<glm::vec3> verts;
// Get the vertices of each triangle in mesh
// For each group of indices
for (int i = 0; i < indices.size(); i += 3) {
// Get the vertices (point) for each index
for (int j = 0; j < 3; j++) {
pos = indices[i+j]*3;
verts.push_back(glm::vec3(vertices[pos], vertices[pos+1], vertices[pos+2]));
}
// Get vectors of two edges of triangle
glm::vec3 U = verts[i+1] - verts[i];
glm::vec3 V = verts[i+2] - verts[i];
// Calculate normal
normal = glm::normalize(-glm::cross(U, V));
normals.push_back(normal.x);
normals.push_back(normal.y);
normals.push_back(normal.z);
}
return normals;
}
std::vector<float> generate_vertices(const std::vector<float> &noise_map) {
std::vector<float> v;
for (int y = 0; y < chunkHeight + 1; y++)
for (int x = 0; x < chunkWidth; x++) {
v.push_back(x);
// Apply cubic easing to the noise
float easedNoise = std::pow(noise_map[x + y*chunkWidth] * 1.1, 3);
// Scale noise to match meshHeight
// Pervent vertex height from being below WATER_HEIGHT
v.push_back(std::fmax(easedNoise * meshHeight, WATER_HEIGHT * 0.5 * meshHeight));
v.push_back(y);
}
return v;
}
std::vector<int> generate_indices() {
std::vector<int> indices;
for (int y = 0; y < chunkHeight; y++)
for (int x = 0; x < chunkWidth; x++) {
int pos = x + y*chunkWidth;
if (x == chunkWidth - 1 || y == chunkHeight - 1) {
// Don't create indices for right or top edge
continue;
} else {
// Top left triangle of square
indices.push_back(pos + chunkWidth);
indices.push_back(pos);
indices.push_back(pos + chunkWidth + 1);
// Bottom right triangle of square
indices.push_back(pos + 1);
indices.push_back(pos + 1 + chunkWidth);
indices.push_back(pos);
}
}
return indices;
}
// Initialize GLFW and GLAD
int init() {
glfwInit();
// Set OpenGL window to version 3.3
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
// macOS compatibility
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
window = glfwCreateWindow(WIDTH, HEIGHT, "Terrain Generator", nullptr, nullptr);
// Account for macOS retina resolution
int screenWidth, screenHeight;
glfwGetFramebufferSize(window, &screenWidth, &screenHeight);
if (window == NULL) {
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
glfwSetScrollCallback(window, scroll_callback);
glfwSetCursorPosCallback(window, mouse_callback);
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) {
std::cout << "Failed to initialize GLAD" << std::endl;
return -1;
}
glViewport(0, 0, screenWidth, screenHeight);
// Enable z-buffer
glEnable(GL_DEPTH_TEST);
glEnable(GL_FRAMEBUFFER_SRGB);
// Enable mouse input
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
return 0;
}
void processInput(GLFWwindow *window, Shader &shader) {
if (glfwGetKey(window, GLFW_KEY_Q) == GLFW_PRESS)
glfwSetWindowShouldClose(window, true);
// Enable wireframe mode
if (glfwGetKey(window, GLFW_KEY_F) == GLFW_PRESS)
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
// Enable flat mode
if (glfwGetKey(window, GLFW_KEY_G) == GLFW_PRESS) {
shader.use();
shader.setBool("isFlat", false);
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
}
if (glfwGetKey(window, GLFW_KEY_H) == GLFW_PRESS) {
shader.use();
shader.setBool("isFlat", true);
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
}
if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)
camera.ProcessKeyboard(FORWARD, deltaTime);
if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)
camera.ProcessKeyboard(BACKWARD, deltaTime);
if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)
camera.ProcessKeyboard(LEFT, deltaTime);
if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS)
camera.ProcessKeyboard(RIGHT, deltaTime);
}
void mouse_callback(GLFWwindow *window, double xpos, double ypos) {
// Prevent camera jumping when mouse first enters screen
if (firstMouse) {
lastX = xpos;
lastY = ypos;
firstMouse = false;
}
// yoffset is reversed since y-coords go from bottom to top
float xoffset = xpos - lastX;
float yoffset = lastY - ypos;
lastX = xpos;
lastY = ypos;
camera.ProcessMouseMovement(xoffset, yoffset);
}
void scroll_callback(GLFWwindow* window, double xoffset, double yoffset) {
camera.ProcessMouseScroll(yoffset);
}