# How can I write a terrain into a .raw file?

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);
return;
}

// 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.
fclose(pFile);


}

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?

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]);
}