-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLandscape.cpp
More file actions
414 lines (344 loc) · 12.1 KB
/
Copy pathLandscape.cpp
File metadata and controls
414 lines (344 loc) · 12.1 KB
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
#include "Landscape.h"
#include <glm/gtc/noise.hpp>
#include <algorithm>
#include <random>
Landscape::Landscape(int octaves, GLfloat frequency, GLfloat scale) : Object3D()
{
xsize = 0;
zsize = 0;
perlin_octaves = octaves;
perlin_freq = frequency;
perlin_scale = scale;
height_scale = 1.0f;
noise = NULL;
}
Landscape::~Landscape()
{
}
void Landscape::generateLanscape(glm::vec2 pixel_dimensions, glm::vec2 region_size, GLfloat sealevel)
{
this->xsize = pixel_dimensions.x;
this->zsize = pixel_dimensions.y;
this->width = region_size.x;
this->height = region_size.y;
height_scale = region_size.x * 4.f;
const size_t* vert_count = new size_t(xsize * zsize);
this->vertex_positions.resize(*vert_count);
this->vertex_colours.resize(*vert_count);
this->vertex_normals.resize(*vert_count);
this->texture_coords.resize(*vert_count);
delete vert_count;
calculateNoise();
/* Define starting (x,z) positions and the step changes */
GLfloat xpos = -width / 2.f;
GLfloat xpos_step = width / GLfloat(xsize);
GLfloat zpos_step = height / GLfloat(zsize);
GLfloat zpos_start = -height / 2.f;
/* Define the vertex positions for a flat surface */
/* Set the normals to zero */
/* Note, for a flat surface, set the normals to (0, 1, 0) but we don't do that because
that will affect the true normal calculation in the next step */
for (GLuint row = 0; row < zsize; row++)
{
GLfloat zpos = zpos_start;
for (GLuint col = 0; col < zsize; col++)
{
GLfloat height = noise[(row * xsize + col) * perlin_octaves + perlin_octaves - 1];
this->vertex_positions[row * xsize + col] = glm::vec3(xpos, (height - 0.5f) * height_scale, zpos);
// Zero the normal, it gets calculated at the end of this method after all the vertex positions
// have been set.
this->vertex_normals[row * xsize + col] = glm::vec3(0, 0, 0);
zpos += zpos_step;
}
xpos += xpos_step;
}
/* Define vertices for triangle strips */
for (GLuint x = 0; x < xsize - 1; x++)
{
GLuint top = x * zsize;
GLuint bottom = top + zsize;
for (GLuint z = 0; z < zsize; z++)
{
this->indices.push_back(top++);
this->indices.push_back(bottom++);
}
}
// Define the range of terrina heights
height_max = xsize / 8.f;
height_min = -height_max;
// Stretch the height values to a defined height range
stretchToRange(height_min, height_max);
defineSeaLevel(sealevel);
// Calculate the normals by averaging cross products for all triangles
calculateNormals();
computeUVS();
}
void Landscape::makeObject()
{
Object3D::makeObject();
// Generate a buffer for the indices
glGenBuffers(1, &indexBufferObj);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBufferObj);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(GLuint), &(this->indices[0]), GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
void Landscape::drawObject(bool clockwise)
{
Object3D::drawObject(clockwise);
int size = 0;
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBufferObj);
glGetBufferParameteriv(GL_ELEMENT_ARRAY_BUFFER, GL_BUFFER_SIZE, &size);
/* Draw the triangle strips */
for (GLuint i = 0; i < xsize - 1; i++)
{
GLuint location = sizeof(GLuint) * (i * zsize * 2);
glDrawElements(GL_TRIANGLE_STRIP, zsize * 2, GL_UNSIGNED_INT, (GLvoid*)(location));
}
}
void Landscape::createFoliageScatterPoints(std::vector<glm::vec3>& scatter_points, std::vector<GLfloat>& scatter_scales) {
size_t vert_count = this->vertex_positions.size();
std::mt19937_64 generator(0);
std::uniform_int_distribution<size_t> distribution(0, vert_count);
std::uniform_int_distribution<size_t> distribution_scale(0.66f, 1.33f);
for (size_t i = 0; i < vert_count/25; ++i) {
size_t point = distribution(generator);
size_t scale = distribution_scale(generator);
if (this->preBlendVertexColours[point] != glm::vec4(0, 0, 1, 1)) {
scatter_points.push_back( this->vertex_positions[point] );
scatter_scales.push_back(scale);
}
}
// Empty vector as it is not needed anymore.
preBlendVertexColours.clear();
preBlendVertexColours.resize(0);
}
void Landscape::setSolidColour(glm::vec4 rgba)
{
size_t size = this->vertex_positions.size();
this->vertex_colours.assign(size, rgba);
}
void Landscape::setColourByHeight(HeightToColour mapping[3])
{
std::vector<HeightToColour> mappings = {
mapping[0],
mapping[1],
mapping[2]
};
// Sort mapping lowest height first - https://en.cppreference.com/w/cpp/algorithm/sort - Date Accessed: 05/12/2023
std::sort(mappings.begin(), mappings.end());
// Assign colours based on height mappings
#pragma omp parallel for
for (size_t i = 0; i < this->vertex_positions.size(); i++) {
// Highest
if (this->vertex_positions[i].y <= mappings[2].height) {
this->vertex_colours[i] = mappings[2].colour;
}
if (this->vertex_positions[i].y <= mappings[1].height){
this->vertex_colours[i] = mappings[1].colour;
}
// Lowest
if (this->vertex_positions[i].y <= mappings[0].height) {
this->vertex_colours[i] = mappings[0].colour;
}
// If the vertex is not coloured then make it the colour of the last (greatest height)
if (this->vertex_positions[i].y > mappings[2].height) {
this->vertex_colours[i] = mappings[2].colour;
}
}
// Copy colours before blending for foliage scattering.
this->preBlendVertexColours = this->vertex_colours;
//Colour blending by neihbouring point
for (size_t z = 0; z < xsize; z++)
{
for (size_t x = 0; x < zsize; x++)
{
std::vector<long int> index_list; // Stores a list of valid neighbouring indices of vertices.
std::vector<long int> colour_list; // Stores a list of indices of neighbouring vertices where their colour differs and are not the specified colours.
long int index = (x + (z * zsize));
long int index_xoffset_pos = ((x + 1) + (z * zsize)); // X offset
long int index_zoffset_pos = (x * ((z + 1) + zsize)); // Z offset
long int index_xzoffset_pos = ((x + 1) + ((z + 1) * zsize)); // XZ offset
long int index_xoffset_neg = ((x - 1) + (z * zsize)); // -X offset
long int index_zoffset_neg = (x + ((z - 1) * zsize)); // -Z offset
long int index_xzoffset_neg = ((x - 1) + ((z - 1) * zsize)); //-(XZ) offset
long int index_posxnegz_offset = ((x + 1) + ((z - 1) * zsize)); //(+X-Z) offset
long int index_negxposz_offset = ((x - 1) + ((z + 1) * zsize)); //(-X+Z) offset
#pragma omp parallel
{
// Get all valid neigbouring indices
if (index_xoffset_pos >= 0 && index_xoffset_pos < xsize) {
index_list.push_back(index_xoffset_pos);
}
if (index_zoffset_pos >= 0 && index_zoffset_pos < zsize) {
index_list.push_back(index_zoffset_pos);
}
if (index_xzoffset_pos < (xsize * zsize)) {
index_list.push_back(index_xzoffset_pos);
}
if (index_xoffset_neg >= 0) {
index_list.push_back(index_xoffset_neg);
}
if (index_zoffset_neg >= 0) {
index_list.push_back(index_zoffset_neg);
}
if (index_xzoffset_neg >= 0) {
index_list.push_back(index_xzoffset_neg);
}
if (index_posxnegz_offset >= 0 && index_posxnegz_offset < (xsize * zsize)) {
index_list.push_back(index_posxnegz_offset);
}
if (index_negxposz_offset >= 0 && index_negxposz_offset < zsize) {
index_list.push_back(index_negxposz_offset);
}
}
// Check if a neighbouring vertex colours is not the same.
// If true then skip to next iteration.
for (auto& i : index_list) {
if (this->vertex_colours[index] != this->vertex_colours[i]) {
colour_list.push_back(i);
}
}
// Skip this iteration if the colour list is empty or does not have enough vertex colour indices stored.
if (colour_list.empty() == true) continue;
#pragma omp parallel for
// Blend colours halfway
for (auto& i : colour_list) {
glm::vec4 current_colour = this->vertex_colours[index];
glm::vec4 neighbour_colour = this->vertex_colours[i];
// Weighted interpolation by angle of current and neighbour vertex normals
glm::vec3 current_normal = this->vertex_normals[index];
glm::vec3 neighbour_normal = this->vertex_normals[i];
GLfloat angle = glm::dot(current_normal, neighbour_normal);
angle = glm::clamp(angle/2, 0.0f, 1.0f);
this->vertex_colours[index] = glm::mix(current_colour, neighbour_colour, angle );
}
}
}
}
void Landscape::calculateNoise()
{
/* Create the array to store the noise values */
/* The size is the number of vertices * number of octaves */
noise = new GLfloat[xsize * zsize * perlin_octaves];
#pragma omp parallel for
for (int i = 0; i < (xsize * zsize * perlin_octaves); i++) noise[i] = 0;
GLfloat xfactor = 1.f / (xsize - 1);
GLfloat zfactor = 1.f / (zsize - 1);
GLfloat freq = perlin_freq;
GLfloat scale = perlin_scale;
#pragma omp parallel
{
for (GLuint row = 0; row < zsize; row++)
{
#pragma omp parallel for
for (GLuint col = 0; col < xsize; col++)
{
GLfloat x = xfactor * col;
GLfloat z = zfactor * row;
GLfloat sum = 0;
GLfloat curent_scale = scale;
GLfloat current_freq = freq;
#pragma omp parallel for
// Compute the sum for each octave
for (GLuint oct = 0; oct < perlin_octaves; oct++)
{
glm::vec2 p(x * current_freq, z * current_freq);
GLfloat val = perlin(p) / curent_scale;
sum += val;
GLfloat result = (sum + 1.f) / 2.f;
// Store the noise value in our noise array
this->noise[(row * xsize + col) * this->perlin_octaves + oct] = result;
// Move to the next frequency and scale
current_freq *= 2.f;
curent_scale *= scale;
}
}
}
}
}
void Landscape::stretchToRange(GLfloat min, GLfloat max)
{
/* Calculate min and max values */
GLfloat cmin, cmax;
cmin = cmax = this->vertex_positions[0].y;
for (GLuint v = 1; v < xsize * zsize; v++)
{
if (this->vertex_positions[v].y < cmin) cmin = this->vertex_positions[v].y;
if (this->vertex_positions[v].y > cmax) cmax = this->vertex_positions[v].y;
}
// Calculate stretch factor
GLfloat stretch_factor = (max - min) / (cmax - cmin);
GLfloat stretch_diff = cmin - min;
/* Rescale the vertices */
for (GLuint v = 0; v < xsize * zsize; v++)
{
this->vertex_positions[v].y = (this->vertex_positions[v].y - stretch_diff) * stretch_factor;
}
}
void Landscape::defineSeaLevel(const GLfloat s)
{
for (int v = 0; v < xsize * zsize; v++)
{
if (this->vertex_positions[v].y < s)
{
this->vertex_positions[v].y = s;
}
}
}
void Landscape::calculateNormals()
{
GLuint element_pos = 0;
glm::vec3 AB, AC, cross_product;
// Loop through each triangle strip
for (GLuint x = 0; x < xsize - 1; x++)
{
// Loop along the strip
for (GLuint tri = 0; tri < zsize * 2 - 2; tri++)
{
// Extract the vertex indices from the element array
GLuint v1 = this->indices[element_pos];
GLuint v2 = this->indices[element_pos + 1];
GLuint v3 = this->indices[element_pos + 2];
// Define the two vectors for the triangle
AB = this->vertex_positions[v2] - this->vertex_positions[v1];
AC = this->vertex_positions[v3] - this->vertex_positions[v1];
// Calculate the cross product
// We have to change the winding for every second triangle to ensure the normals
// are the correct diections. See what happens if we don't do this by using the
// commented out line of code below instead?
// cross_product = normalize(cross(AC, AB)); // Incorrect winding
if (tri % 2 == 0)
cross_product = normalize(cross(AC, AB));
else
cross_product = normalize(cross(AB, AC));
// Add this normal to the vertex normal for all three vertices in the triangle
this->vertex_normals[v1] += cross_product;
this->vertex_normals[v2] += cross_product;
this->vertex_normals[v3] += cross_product;
// Move on to the next vertex along the strip
element_pos++;
}
// Jump past the last two element positions to reach the start of the strip
element_pos += 2;
}
// Normalise the normals (this gives us averaged, vertex normals)
for (GLuint v = 0; v < xsize * zsize; v++)
{
this->vertex_normals[v] = glm::normalize(this->vertex_normals[v]);
}
}
void Landscape::computeUVS()
{
#pragma omp paralell
{
#pragma omp parallel for
for (size_t x = 0; x < xsize; x++)
{
#pragma omp parallel for
for (size_t y = 0; y < zsize; y++)
{
this->texture_coords[x + (y * zsize)] = { (x / static_cast<double>(xsize)), (y / static_cast<double>(zsize)) };
}
}
}
}