Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

I want to generate a terrain through Perlin noise and store it into a .raw file.

From Nehe's HeightMap tutorial I know the .raw file is read like this:

#define MAP_SIZE        1024    

void LoadRawFile(LPSTR strName, int nSize, BYTE *pHeightMap)
    FILE *pFile = NULL;

    // Let's open the file in Read/Binary mode.
    pFile = fopen( strName, "rb" );

    // Check to see if we found the file and could open it
    if ( pFile == NULL )    
        // Display our error message and stop the function
        MessageBox(NULL, "Can't find the height map!", "Error", MB_OK);

    // Here we load the .raw file into our pHeightMap data array.
    // We are only reading in '1', and the size is the (width * height)
    fread( pHeightMap, 1, nSize, pFile );

    // After we read the data, it's a good idea to check if everything read fine.
    int result = ferror( pFile );

    // Check if we received an error.
    if (result)
        MessageBox(NULL, "Can't get data!", "Error", MB_OK);

    // Close the file.


pHeightMap is one-dimensional, so I don't understand how I would write the x,y correspondence to a height value. I was planning to use either libnoise or the noise2 function on Ken Perlin's page, to make each value in a 1024x1024 matrix correspond to the height for the point, but the .raw file is stored in a single dimension, how can I make x,y correspondence work there?

share|improve this question
You may be interested in reading about how 2D arrays are stored in memory. C/C++, C# etc will use Row Major: en.wikipedia.org/wiki/Row-major_order –  John McDonald Feb 8 '12 at 19:26

1 Answer 1

up vote 2 down vote accepted

Depending on your map width, you can convert between (x,y) and pHeightMap[index] fairly simply:

int x, y, index; // assuming y is vertical, x is horizontal

// converting from x,y to index
index = y * MAP_WIDTH + x;
BYTE valueAtXY = pHeightMap[index]; 

// converting from index to x,y
for(index = 0; index < nSize; index++) { 
    x = index % MAP_WIDTH;
    y = index / MAP_WIDTH;
    printf("We are at point %d, %d", x, y);

Alternatively, you can cast from a BYTE* to a BYTE(*)[<width>] . C is row-major, so the row-index will come first.

BYTE * pHeightMap;
BYTE (* pHeightMap2D ) [MAP_WIDTH] = (BYTE(*)[MAP_WIDTH]) pHeightMap;

for(index = 0; index < nSize; index++) { 
    x = index % MAP_WIDTH;
    y = index / MAP_WIDTH;
    // y comes first, because the row-index comes first.
    assert(pHeightMap2D[y][x] == pHeightMap[index]);
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.