本文实例主要是有关OPENGL绘制地形的,文本文件定义了地形数据,格式如下:
colour 0.1 0.2 0.3
size 4 4 1.0
v 1.56 2.34 3.45 4.56 5.89
v 2.12 3.45 4.55 5.67 6.88
v 3.23 4.34 5.67 6.78 7.44
v 4.34 5.66 6.22 7.34 8.12
v 5.12 6.23 7.44 8.12 9.11
colour定义了opengl的rgb颜色
size定义了大小,4*4,间隔1.0 ,所以是5*5的点数,后面的v都是每个点的高度。
<pre name="code" class="cpp">// ReadFileToArray.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <malloc.h>
#include <string>
using namespace std;
int width,depth;
int nrows=0,ncolums=0;
float wstep,dstep,step;
float r,g,b;
float **arr;
/*
定义的地形格式如下
colour 0.1 0.2 0.3
size 4 4 1.0
v 1.56 2.34 3.45 4.56 5.89
v 2.12 3.45 4.55 5.67 6.88
v 3.23 4.34 5.67 6.78 7.44
v 4.34 5.66 6.22 7.34 8.12
v 5.12 6.23 7.44 8.12 9.11
*/
void Init()
{
int j=0;
int k=0;
string str,str1;
ifstream file;
file.open("terrain.dat",ios::in);
if(!file)
{
cout<<"Can't open terrain.dat"<<endl;
}
else
{
while(!file.eof())
{
getline(file,str);
// printf("%s",str.c_str());
istringstream iss(str);
iss>>str1;
if(str1=="colour")
{
iss>>r>>g>>b;
}
else if(str1=="size")
{
iss>>width>>depth>>step;
}
}
}
// printf("r=%f,g=%f,b=%f\n",r,g,b);
file.close();
nrows=width/step+1;
ncolums=depth/step+1;
arr=(float**)malloc(sizeof(float)*nrows);
for(int i=0;i<nrows;i++)
arr[i]=(float*)malloc(sizeof(float)*ncolums);
file.open("terrain.dat",ios::in);
if(!file)
{
cout<<"Can't open terrain.dat"<<endl;
}
else
{
while(!file.eof())
{
getline(file,str);
istringstream iss(str);
iss>>str1;
if(str1=="v")
{
for(k=0;k<ncolums;k++)
iss>>arr[j][k];
j++;
}
}
}
file.close();
}
void printarr()
{
printf("r=%f,g=%f,b=%f\n",r,g,b);
printf("width=%d,depth=%d,step=%f,nrows=%d,ncolums=%d\n",width,depth,step,nrows,ncolums);
for(int i=0;i<nrows;i++)
{
for(int j=0;j<ncolums;j++)
printf("%f ",arr[i][j]);
printf("\n");
}
}
int _tmain(int argc, _TCHAR* argv[])
{
Init();
printarr();
free(arr);
arr=NULL;
return 0;
}