Generation of height maps based on diamond-square-algorithm in C++

In fact, many times we see these renderings are really amazing things, such as some terrain seems to be three-dimensional, but in fact can be generated by two-dimensional, that is, for each pixel point to give a height value, these height values constitute a column of points and can be converted into a two-dimensional image to store, when needed, the corresponding terrain can be generated from this picture.

As for the introduction, we are only concerned with using normal distribution or diamond square to assign values, terrain generator about color and normal value images we will talk about later.

Here is the code:

  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

#include <iostream>
#include <tchar.h>
#include <winnt.rh>

#include <sstream>
#include <random>

#include <SimpleImage.h>
#include <TextureGenerator.h>
#include <time.h>



#include <vector>

//#pragma comment(lib, "GEDUtilsd.lib")

//Declare functions
float squareStep(float* field, int x, int y, int reach, int width);
float diamondStep(float* field, int x, int y, int reach, int width);
float random(float min, float max);
//GEDUtils::SimpleImage transfer(float* field, int width);
void smoothArray(float* field, int64_t width, int64_t height);
void diamondSquare(float* field, int size, int width, float roughness);


using namespace std;

// Define a macro for easier access to a flattened 2D array
#define IDX(x, y, w) ((x) + (y) * (w))
//Define the size of an array
#define ARR_LEN(array, length){length = sizeof(array)/sizeof(array[0]);}

/*
int main()
{
    std::cout << "Hello World!\n";
}
*/

//use for debugging
void printArray(float* field, uint64_t width, uint64_t height)
{
    for (uint64_t y = 0; y < height; y++)
    {
        for (uint64_t x = 0; x < width; x++)
            std::cout << field[IDX(x, y, width)] << " ";

        std::cout << std::endl;
    }
}


int _tmain(int argc, _TCHAR* argv[]) {


    //int len;
    /*
    ARR_LEN(argv, len);
    if (argc != len) {
        throw "invalid length";
    }
    */


    cout << endl << "argc = " << argc << endl;
    cout << "Command line arguments received are:" << endl;
    for (int i = 0; i < argc; i++)
        cout << "argument " << (i + 1) << ": " << argv[i] << endl;


    if (_tcscmp(argv[1], TEXT("-r")) != 0 || _tcscmp(argv[3], TEXT("-o_height")) != 0 || _tcscmp(argv[5], TEXT("-o_color")) != 0 || _tcscmp(argv[7], TEXT("-o_normal")) != 0) {
        throw "do not match '-r' or '-o's";
    }

    //alternative way for resolution
    //std::wstringstream wsstream;
    //wsstream << argv[2];
    //int resolution;
    //wsstream >> resolution;

    int resolution = _tstoi(argv[2]);

    if (resolution <= 0) {
        throw "<= 0 for resolution";
    }

    //preparation for normal mapping
    std::default_random_engine e;
    std::normal_distribution<float> n(0, 1);

    int length = resolution * resolution;

    float* field = new float[length];

    //mapping normal distribution
    for (int y = 0; y < resolution; y++) {
        for (int x = 0; x < resolution; x++) {
            float value = n(e);
            while (value < 0.0f || value > 1.0f) {
                value = n(e);
            }

            field[IDX(x, y, resolution)] = value >= 0 ? value : -value;
        }
    }

    //name of height file
    wstring wsh(argv[4]);
    const wchar_t* cstrh = wsh.c_str();

    //name of color file
    wstring wsc(argv[6]);
    const wchar_t* cstrc = wsc.c_str();

    //name of normal file
    wstring wsn(argv[8]);
    const wchar_t* cstrn = wsn.c_str();


    //generate a texture generator
    GEDUtils::TextureGenerator texGen(L"..\\..\\..\\..\\external\\textures\\gras15.jpg", L"..\\..\\..\\..\\external\\textures\\ground02.jpg", L"..\\..\\..\\..\\external/textures/kork02.jpg", L"..\\..\\..\\..\\external\\textures\\rock1.jpg");


    try {

        //this is for normal distribution
        /*
        //copy the created normal distribution values to the heightfield
        GEDUtils::SimpleImage heightImage = GEDUtils::SimpleImage::SimpleImage((UINT)resolution, (UINT)resolution);

        for (int y = 0; y < resolution; y++) {
            for (int x = 0; x < resolution; x++) {
                heightImage.setPixel(x, y, field[IDX(x, y, resolution)]);
            }
        }


        //save the generated heightField
        if (!heightImage.save(cstrh)) {
            throw "Could not save heightField image";
        }



        // Load height image into the image test
        //GEDUtils::SimpleImage test(cstrh);

        //create a vector to store
        vector<float> vectorHeight(field, field + length);


        //this is for normal distribution
        //texGen.generateAndStoreImages(vectorHeight,resolution - 1,cstrc,cstrn);


        delete[] field;
        */


        //this is for diamond square
        int length2 = (resolution + 1) * (resolution + 1);

        float* field2 = new float[length2];

        //assign random value to the corners
        field2[IDX(0, 0, resolution + 1)] = random(0, 1);
        field2[IDX(0, resolution, resolution + 1)] = random(0, 1);
        field2[IDX(resolution, 0, resolution + 1)] = random(0, 1);
        field2[IDX(resolution, resolution, resolution + 1)] = random(0, 1);

        //give a initial roughness
        float roughness = random(0,1);

        //diamond squre
        diamondSquare(field2, resolution, resolution + 1, roughness);


        //mapping values to a smaller array
        float* field3 = new float[length];

        for (int y = 0; y < resolution; y++) {
            for (int x = 0; x < resolution; x++) {
               //field3[IDX(x, y, resolution)] = diamondHeight.getPixel(x, y);
                field3[IDX(x, y, resolution)] = field2[IDX(x , y , resolution + 1)];

            }
        }
         delete[] field2;

         //smooth array, times can be changed
         for (int i = 1; i < 100; i++) {
             smoothArray(field3, resolution, resolution);
         }


        //copy the created normal distribution values to the heightfield
        GEDUtils::SimpleImage heightImage2 = GEDUtils::SimpleImage::SimpleImage((UINT)resolution, (UINT)resolution);

        for (int y = 0; y < resolution; y++) {
            for (int x = 0; x < resolution; x++) {
                heightImage2.setPixel(x, y, field3[IDX(x, y, resolution)]);
            }
        }

        //save the generated heightField
        if (!heightImage2.save(cstrh)) {
            throw "Could not save heightField image";
        }

        //create a vector to store
        vector<float> vectorHeight2(field3, field3 + length);

        texGen.generateAndStoreImages(vectorHeight2, resolution - 1, cstrc, cstrn);

        delete[] field3;
    }
    catch (char* exception) {
        printf("Error: %s\n", exception);
    }

    //delete[] field;

    return EXIT_SUCCESS;
}



//smooth array
void smoothArray(float* field, int64_t width, int64_t height)
{
    // Allocate a temporary new array
    float* tmp_field = new float[width * height];

    for (int64_t y = 0; y < height; y++)
        for (int64_t x = 0; x < width; x++)
        {
            // Start with the value at the current position
            float value = field[IDX(x, y, width)];

            // Add values around the current position, clamped to [0, length - 1]
            value += field[IDX(min(x + 1, width - 1), y, width)];
            value += field[IDX(min(x + 1, width - 1), max(y - 1, 0ll), width)];
            value += field[IDX(x, max(y - 1, 0ll), width)];
            value += field[IDX(max(x - 1, 0ll), max(y - 1, 0ll), width)];
            value += field[IDX(max(x - 1, 0ll), y, width)];
            value += field[IDX(max(x - 1, 0ll), min(y + 1, height - 1), width)];
            value += field[IDX(x, min(y + 1, height - 1), width)];
            value += field[IDX(min(x + 1, width - 1), min(y + 1, height - 1), width)];

            // Save the computed value in the temporary array
            tmp_field[IDX(x, y, width)] = value / 9.0f;
        }

    // Copy the values of the temporary array to the array we weant to modify
    for (uint64_t y = 0; y < height; y++)
        for (uint64_t x = 0; x < width; x++)
            field[IDX(x, y, width)] = tmp_field[IDX(x, y, width)];

    // Free the memory of our temporary array
    delete[] tmp_field;
}


//body part of diamond square
void diamondSquare(float* field, int size, int width,float roughness)
{
    int half = size / 2;
    if (half < 1)
        return;

    //square steps
    for (int y = half; y < width; y += size) {
        for (int x = half; x < width; x += size) {
            field[IDX(x, y, width)] = squareStep(field, x % width, y % width, half, width); + random(-roughness,roughness);
        }
    }


    // diamond steps
    int col = 0;
    for (int y = 0; y < width; y += half)
    {
        col++;
        //If this is an odd column.
        if (col % 2 == 1) {
            for (int x = half; x < width; x += size) {

                field[IDX(x, y, width)] = diamondStep(field, x % width, y % width, half, width); + random(-roughness, roughness);
            }
        }
        else {
            for (int x = 0; x < width; x += size) {
                field[IDX(x, y, width)] = diamondStep(field, x % width, y % width, half, width); +random(-roughness, roughness);
            }
        }
    }

    //iteration on roughness
    roughness = roughness * roughness;

    diamondSquare(field, size / 2, width, roughness);
}


//reach is the distance away from the place we are seeking for average
float squareStep(float* field, int x, int y, int reach, int width)
{
    float count = 0;
    float avg = 0.;
    if (x - reach >= 0 && y - reach >= 0)
    {
        avg = avg + field[IDX(x - reach, y - reach, width)];
        count++;
    }
    if (x - reach >= 0 && y + reach < width)
    {
        avg = avg + field[IDX(x - reach, y + reach, width)];
        count++;
    }
    if (x + reach < width && y - reach >= 0)
    {
        avg = avg + field[IDX(x + reach, y - reach, width)];
        count++;
    }
    if (x + reach < width && y + reach < width)
    {
        avg =avg + field[IDX(x + reach, y + reach, width)];
        count++;
    }

    avg = avg / (float)count;

    //field[IDX(x, y, width)] = avg;
    return avg;
}


float diamondStep(float* field, int x, int y, int reach, int width)
{
    float count = 0;
    float avg = 0;
    if (x - reach >= 0)
    {
        avg = avg +  field[IDX(x - reach, y, width)];
        count++;
    }
    if (x + reach < width)
    {
        avg = avg + field[IDX(x + reach, y, width)];
        count++;
    }
    if (y - reach >= 0)
    {
        avg = avg + field[IDX(x, y - reach, width)];
        count++;
    }
    if (y + reach < width)
    {
        avg = avg + field[IDX(x, y + reach, width)];
        count++;
    }
    avg = avg / (float)count;

    return avg;
    //field[x, y, width] = avg;
}


//generate random number in a range
float random(float min, float max) {

    float random = min + (float)(rand()) / ((float)(RAND_MAX) / (max - min));
    return random;
}


/*
//store the generated field to a simple image
GEDUtils::SimpleImage transfer(float* field, int width) {
    GEDUtils::SimpleImage diamond(width - 1, width - 1);
    for (int j = 0;j < width; j++) {
        for (int i = 0; j < width; i++) {
            diamond.setPixel(i, j, field[i, j, width]);
        }
    }
    return diamond;
}
*/