为什么80%的码农都做不了架构师?>>>   

//==============================================================
//==============================================================
//= terrain.cpp ================================================
//= Original coders: Trent Polack (trent@voxelsoft.com)          =
//==============================================================
//= This file contains the information for the "parent" terrain=
//= class, which all specific implementations are derived from,=
//= also contains other general data structures and constants. =
//==============================================================
//==============================================================//--------------------------------------------------------------
//--------------------------------------------------------------
//- HEADERS AND LIBRARIES --------------------------------------
//--------------------------------------------------------------
//--------------------------------------------------------------
#include <stdio.h>
#include <math.h>#include "../Base Code/gl_app.h"#include "terrain.h"//--------------------------------------------------------------
//--------------------------------------------------------------
//- DEFINITIONS ------------------------------------------------
//--------------------------------------------------------------
//--------------------------------------------------------------//--------------------------------------------------------------
// Name:            CTERRAIN::LoadHeightMap - public
// Description:     Load a grayscale RAW height map
// Arguments:       -szFilename: the file name of the height map
//                  -im_iSize: the m_iSize (power of 2) of the map
// Return Value:    A boolean value: -true: successful load
//                                   -false: unsuccessful load
//--------------------------------------------------------------
bool CTERRAIN::LoadHeightMap( char* szFilename, int iSize )
{FILE* pFile;//check to see if the data has been setif( m_heightData.m_ucpData )UnloadHeightMap( );//open the RAW height map datasetpFile= fopen( szFilename, "rb" );if( pFile==NULL ){//bad filenameg_log.Write( LOG_FAILURE, "Could not load %s\n", szFilename );return false;}//allocate the memory for our height datam_heightData.m_ucpData= new unsigned char [iSize*iSize];//check to see if memory was successfully allocatedif( m_heightData.m_ucpData==NULL ){//the memory could not be allocated something is seriously wrong hereg_log.Write( LOG_FAILURE, "Could not allocate memory for%s\n", szFilename );return false;}//read the heightmap into contextfread( m_heightData.m_ucpData, 1, iSize*iSize, pFile );//Close the filefclose( pFile );//set the m_iSize datam_iSize= iSize;//yahoo! The heightmap has been successfully loadedg_log.Write( LOG_SUCCESS, "Loaded %s\n", szFilename );return true;
}//--------------------------------------------------------------
// Name:            CTERRAIN::SaveHeightMap - public
// Description:     Save a grayscale RAW height map
// Arguments:       -szFilename: the file name of the height map
// Return Value:    A boolean value: -true: successful save
//                                   -false: unsuccessful save
//--------------------------------------------------------------
bool CTERRAIN::SaveHeightMap( char* szFilename )
{FILE* pFile;//open a file to write topFile= fopen( szFilename, "wb" );if( pFile==NULL ){//bad filenameg_log.Write( LOG_FAILURE, "Could not create %s\n", szFilename );return false;}//check to see if our height map actually has data in itif( m_heightData.m_ucpData==NULL ){//something is seriously wrong hereg_log.Write( LOG_FAILURE, "The height data buffer for %s is empty\n", szFilename );return false;}//write the data to the filefwrite( m_heightData.m_ucpData, 1, m_iSize*m_iSize, pFile );//Close the filefclose( pFile );//w00t w00t! The heightmap has been successfully savedg_log.Write( LOG_SUCCESS, "Saved %s\n", szFilename );return true;
}//--------------------------------------------------------------
// Name:            CTERRAIN::UnloadHeightMap - public
// Description:     Unload the class's height map (if there is one)
// Arguments:       None
// Return Value:    A boolean value: -true: successful load
//                                   -false: unsuccessful load
//--------------------------------------------------------------
bool CTERRAIN::UnloadHeightMap( void )
{//check to see if the data has been setif( m_heightData.m_ucpData ){//delete the datadelete[] m_heightData.m_ucpData;//reset the map dimensions alsom_iSize= 0;}//the height map has been unloadedg_log.Write( LOG_SUCCESS, "Successfully unloaded the height map\n" );return true;
}//--------------------------------------------------------------
// Name:            CTERRAIN::NormalizeTerrain - private
// Description:     Scale the terrain height values to a range of
//                  0-255
// Arguments:       -fpHeightData: the height data buffer
// Return Value:    None
//--------------------------------------------------------------
void CTERRAIN::NormalizeTerrain( float* fpHeightData )
{float fMin, fMax;float fHeight;int i;fMin= fpHeightData[0];fMax= fpHeightData[0];//find the min/max values of the height fTempBufferfor( i=1; i<m_iSize*m_iSize; i++ ){if( fpHeightData[i]>fMax ) fMax= fpHeightData[i];else if( fpHeightData[i]<fMin ) fMin= fpHeightData[i];}//find the range of the altitudeif( fMax<=fMin )return;fHeight= fMax-fMin;//scale the values to a range of 0-255 (because I like things that way)for( i=0; i<m_iSize*m_iSize; i++ )fpHeightData[i]= ( ( fpHeightData[i]-fMin )/fHeight )*255.0f;
}//--------------------------------------------------------------
// Name:            CTERRAIN::FilterHeightBand - private
// Description:     Apply the erosion filter to an individual
//                  band of height values
// Arguments:       -fpBand: the band to be filtered
//                  -iStride: how far to advance per pass
//                  -iCount: Number of passes to make
//                  -fFilter: the filter strength
// Return Value:    None
//--------------------------------------------------------------
void CTERRAIN::FilterHeightBand( float* fpBand, int iStride, int iCount, float fFilter )
{float v= fpBand[0];int j  = iStride;int i;//go through the height band and apply the erosion filterfor( i=0; i<iCount-1; i++ ){fpBand[j]= fFilter*v + ( 1-fFilter )*fpBand[j];v = fpBand[j];j+= iStride;}
}//--------------------------------------------------------------
// Name:            CTERRAIN::FilterHeightfTempBuffer - private
// Description:     Apply the erosion filter to an entire buffer
//                  of height values
// Arguments:       -fpHeightData: the height values to be filtered
//                  -fFilter: the filter strength
// Return Value:    None
//--------------------------------------------------------------
void CTERRAIN::FilterHeightField( float* fpHeightData, float fFilter )
{int i;//erode left to rightfor( i=0; i<m_iSize; i++ )FilterHeightBand( &fpHeightData[m_iSize*i], 1, m_iSize, fFilter );//erode right to leftfor( i=0; i<m_iSize; i++ )FilterHeightBand( &fpHeightData[m_iSize*i+m_iSize-1], -1, m_iSize, fFilter );//erode top to bottomfor( i=0; i<m_iSize; i++ )FilterHeightBand( &fpHeightData[i], m_iSize, m_iSize, fFilter);//erode from bottom to topfor( i=0; i<m_iSize; i++ )FilterHeightBand( &fpHeightData[m_iSize*(m_iSize-1)+i], -m_iSize, m_iSize, fFilter );
}//--------------------------------------------------------------
// Name:            CTERRAIN::MakeTerrainFault - public
// Description:     Create a height data set using the "Fault Formation"
//                  algorithm.  Thanks a lot to Jason Shankel for this code!
// Arguments:       -iSize: Desired size of the height map
//                  -iIterations: Number of detail passes to make
//                  -iMinDelta, iMaxDelta: the desired min/max heights
//                  -iIterationsPerFilter: Number of passes per filter
//                  -fFilter: Strength of the filter
// Return Value:    A boolean value: -true: successful creation
//                                   -false: unsuccessful creation
//--------------------------------------------------------------
bool CTERRAIN::MakeTerrainFault( int iSize, int iIterations, int iMinDelta, int iMaxDelta, float fFilter )
{float* fTempBuffer;int iCurrentIteration;int iHeight;int iRandX1, iRandZ1;int iRandX2, iRandZ2;int iDirX1, iDirZ1;int iDirX2, iDirZ2;int x, z;int i;if( m_heightData.m_ucpData )UnloadHeightMap( );m_iSize= iSize;//allocate the memory for our height datam_heightData.m_ucpData= new unsigned char [m_iSize*m_iSize];fTempBuffer= new float [m_iSize*m_iSize];//check to see if memory was successfully allocatedif( m_heightData.m_ucpData==NULL ){//something is seriously wrong hereg_log.Write( LOG_FAILURE, "Could not allocate memory for height map" );return false;}//check to see if memory was successfully allocatedif( fTempBuffer==NULL ){//something is seriously wrong hereg_log.Write( LOG_FAILURE, "Could not allocate memory for height map" );return false;}//clear the height fTempBufferfor( i=0; i<m_iSize*m_iSize; i++ )fTempBuffer[i]= 0;for( iCurrentIteration=0; iCurrentIteration<iIterations; iCurrentIteration++ ){//calculate the height range (linear interpolation from iMaxDelta to//iMinDelta) for this fault-passiHeight= iMaxDelta - ( ( iMaxDelta-iMinDelta )*iCurrentIteration )/iIterations;//pick two points at random from the entire height mapiRandX1= rand( )%m_iSize;iRandZ1= rand( )%m_iSize;//check to make sure that the points are not the samedo{iRandX2= rand( )%m_iSize;iRandZ2= rand( )%m_iSize;} while ( iRandX2==iRandX1 && iRandZ2==iRandZ1 );//iDirX1, iDirZ1 is a vector going the same direction as the lineiDirX1= iRandX2-iRandX1;iDirZ1= iRandZ2-iRandZ1;for( z=0; z<m_iSize; z++ ){for( x=0; x<m_iSize; x++ ){//iDirX2, iDirZ2 is a vector from iRandX1, iRandZ1 to the current point (in the loop)iDirX2= x-iRandX1;iDirZ2= z-iRandZ1;//if the result of ( iDirX2*iDirZ1 - iDirX1*iDirZ2 ) is "up" (above 0), //then raise this point by iHeightif( ( iDirX2*iDirZ1 - iDirX1*iDirZ2 )>0 )fTempBuffer[( z*m_iSize )+x]+= ( float )iHeight;}}//erode terrainFilterHeightField( fTempBuffer, fFilter );}//normalize the terrain for our purposesNormalizeTerrain( fTempBuffer );//transfer the terrain into our class's unsigned char height bufferfor( z=0; z<m_iSize; z++ ){for( x=0; x<m_iSize; x++ )SetHeightAtPoint( ( unsigned char )fTempBuffer[( z*m_iSize )+x], x, z );}//delete temporary bufferif( fTempBuffer ){//delete the datadelete[] fTempBuffer;}return true;
}//--------------------------------------------------------------
// Name:            CTERRAIN::MakeTerrainPlasma - public
// Description:     Create a height data set using the "Midpoint
//                  Displacement" algorithm.  Thanks a lot to
//                  Jason Shankel for this code!
//                  Note: this algorithm has limited use, since
//                  CLOD algorithms usually require a height map
//                  size of (n^2)+1 x (n^2)+1, and this algorithm
//                  can only generate (n^2) x (n^2) maps
// Arguments:       -iSize: Desired size of the height map
//                  -fRoughness: Desired roughness of the created map
// Return Value:    A boolean value: -true: successful creation
//                                   -false: unsuccessful creation
//--------------------------------------------------------------
bool CTERRAIN::MakeTerrainPlasma( int iSize, float fRoughness )
{float* fTempBuffer;float fHeight, fHeightReducer;int iRectSize= iSize;int ni, nj;int mi, mj;int pmi, pmj;int i, j;int x, z;if( m_heightData.m_ucpData )UnloadHeightMap( );if( fRoughness<0 )fRoughness*= -1;fHeight         = ( float )iRectSize/2;fHeightReducer= ( float )pow(2, -1*fRoughness);m_iSize= iSize;//allocate the memory for our height datam_heightData.m_ucpData= new unsigned char [m_iSize*m_iSize];fTempBuffer= new float [m_iSize*m_iSize];memset(fTempBuffer,4.0,sizeof(float)*m_iSize*m_iSize);//check to see if memory was successfully allocatedif( m_heightData.m_ucpData==NULL ){//something is seriously wrong hereg_log.Write( LOG_FAILURE, "Could not allocate memory for height map" );return false;}//check to see if memory was successfully allocatedif( fTempBuffer==NULL ){//something is seriously wrong hereg_log.Write( LOG_FAILURE, "Could not allocate memory for height map" );return false;}//set the first value in the height fieldfTempBuffer[0]= 0.0f;//being the displacement processwhile( iRectSize>0 ){/*Diamond step -Find the values at the center of the retangles by averaging the values at the corners and adding a random offset:a.....b.     .  .  e  ..     .c.....d   e  = (a+b+c+d)/4 + randomIn the code below:a = (i,j)b = (ni,j)c = (i,nj)d = (ni,nj)e = (mi,mj)   */for( i=0; i<m_iSize; i+=iRectSize ){for( j=0; j<m_iSize; j+=iRectSize ){ni= ( i+iRectSize )%m_iSize;nj= ( j+iRectSize )%m_iSize;mi= ( i+iRectSize/2 );mj= ( j+iRectSize/2 );fTempBuffer[mi+mj*m_iSize]= ( float )( (fTempBuffer[i+j*m_iSize] + fTempBuffer[ni+j*m_iSize] + fTempBuffer[i+nj*m_iSize] + fTempBuffer[ni+nj*m_iSize] )/4 + RangedRandom( -fHeight/2, fHeight/2 ) );}}/*Square step -Find the values on the left and top sides of each rectangleThe right and bottom sides are the left and top sides of the neighboring rectangles,so we don't need to calculate themThe height m_heightData.m_ucpData wraps, so we're never left hanging.  The right side of the lastrectangle in a row is the left side of the first rectangle in the row.  The bottomside of the last rectangle in a column is the top side of the first rectangle inthe column........     ..     ..  d  ..     ..     .......a..g..b.     .     ..     .     ..  e  h  f  ..     .     ..     .     .......c......g = (d+f+a+b)/4 + randomh = (a+c+e+f)/4 + randomIn the code below:a = (i,j) b = (ni,j) c = (i,nj) d = (mi,pmj) e = (pmi,mj) f = (mi,mj) g = (mi,j)h = (i,mj)*/for( i=0; i<m_iSize; i+=iRectSize ){for( j=0; j<m_iSize; j+=iRectSize ){ni= (i+iRectSize)%m_iSize;nj= (j+iRectSize)%m_iSize;mi= (i+iRectSize/2);mj= (j+iRectSize/2);pmi= (i-iRectSize/2+m_iSize)%m_iSize;pmj= (j-iRectSize/2+m_iSize)%m_iSize;//Calculate the square value for the top side of the rectanglefTempBuffer[mi+j*m_iSize]= ( float )( ( fTempBuffer[i+j*m_iSize]     +fTempBuffer[ni+j*m_iSize]    +fTempBuffer[mi+pmj*m_iSize]      +fTempBuffer[mi+mj*m_iSize] )/4+RangedRandom( -fHeight/2, fHeight/2 ) );//Calculate the square value for the left side of the rectanglefTempBuffer[i+mj*m_iSize]= ( float )( ( fTempBuffer[i+j*m_iSize]   +fTempBuffer[i+nj*m_iSize]    +fTempBuffer[pmi+mj*m_iSize]      +fTempBuffer[mi+mj*m_iSize] )/4+ RangedRandom( -fHeight/2, fHeight/2 ) );}}//reduce the rectangle size by two to prepare for the next//displacement stageiRectSize/= 2;//reduce the height by the height reducerfHeight*= fHeightReducer;}//normalize the terrain for our purposesNormalizeTerrain( fTempBuffer );//transfer the terrain into our class's unsigned char height bufferfor( z=0; z<m_iSize; z++ ){for( x=0; x<m_iSize; x++ )SetHeightAtPoint( ( unsigned char )fTempBuffer[( z*m_iSize )+x], x, z );}//delete temporary bufferif( fTempBuffer ){//delete the datadelete[] fTempBuffer;}return true;
}

转载于:https://my.oschina.net/lyr/blog/98008

midpoint displacement相关推荐

  1. js输出一个菱形_Threejs使用菱形正方形算法,中点替换算法生成随机地形

    源码: https://github.com/srchea/Terrain-Generation https://github.com/IceCreamYou/THREE.Terrain 菱形正方形算 ...

  2. 聚焦3D地形编程第五章GeomipMapping for the CLOD

    第二部分高级地形编程 聚焦3D地形编程第五章GeomipMapping for the CLOD 译者: 神杀中龙 邵小宁 microsoftxiao@163.com 翻译的烂请见谅 原著 <F ...

  3. 使用Managed DirectX编写游戏

    转自  http://dev.gameres.com/Program/Visual/DirectX/ManagedDirectX9Game_01.htm http://dev.gameres.com/ ...

  4. 【Visual C++】游戏开发四十八 浅墨DirectX教程十六 三维地形系统的实现

    分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.csdn.net/jiangjunshow 也欢迎大家转载本篇文章.分享知识,造福人民,实现我们中华民族伟大复兴! 本系列文 ...

  5. DirectX3D游戏制作之---3D场景的渲染及人物动画的显示

    前言: 无所谓好或不好,人生一场虚空大梦,韶华白首,不够转瞬. ----慕容紫英<仙剑奇侠传四> PS:为了方便大家阅读,个人认为比较重要的内容-------红色字体显示 个人认为可以了解 ...

  6. 【转】游戏开发高度图有关资料与Balder中的相关支持

    2019独角兽企业重金招聘Python工程师标准>>> 资料一:使用Managed DirectX创建三维地形 来源:GameRes网站 内容: 使用Height Map作为输入 首 ...

  7. 游戏开发高度图有关资料与Balder中的相关支持

    资料一:使用Managed DirectX创建三维地形 来源:GameRes网站 内容: 使用Height Map作为输入 首先,什么是高度图(Height Map)呢?所谓高度图实际上就是一个2维数 ...

  8. 分形在山地生成中的应用[1]---中点位移法

      分形在山地生成中的应用[1]---中点位移法             EmilMatthew (EmilMatthew@126.com)       06/07/18 [  类别  ]算法实现   ...

  9. Generating fantasy maps——来生成虚拟地图吧!【未完】

    英文教程(作者著):https://mewo2.com/notes/terrain/ GitHub地址:https://github.com/mewo2/terrain 对特定段落的描述,在英文教程页 ...

最新文章

  1. Exchange2010 初始化失败
  2. A % B Problem
  3. getopt()和getopt_long()用法
  4. 一个web项目在myeclipse中add deployment时无法被识别出来的原因
  5. 今天读了JDK1.8源码,知道了并行迭代器Spliterator
  6. 人工智能TensorFlow工作笔记007---认识张量
  7. UVA10023 Square root【大数】
  8. Harmony OS — PageSlider滑动页面
  9. ios开发学习-指示器(HUD)效果源码分享
  10. 音频格式G711转PCM的代码
  11. spss数据预处理步骤_2. SPSS基本使用:数据清洗
  12. 同一文件夹下的excel文件合并成一个总excel
  13. NPN与PNP三极管
  14. 普物期末题型总结题解
  15. SuperMap iObjects C++之缓冲区
  16. python实现 pdf转png格式
  17. 知名云计算厂商云宏加入龙蜥社区,共同打造信息安全坚实“地基”
  18. 使用ffmpeg 提取视频关键帧
  19. iOS-Core-Animation-Advanced-Techniques(一)
  20. cnpm的安装(超级详细版)

热门文章

  1. oppor9android6.0版本,好消息!OPPO R9 Plus能升级至安卓6.0
  2. NUC980 PWM驱动配置与测试
  3. NKOI 3124 珍珠吊坠
  4. 第7周-项目1-完整实现复数类中的运算符重载-扩展+、-、*、/运算符的功能
  5. 地震勘探基础(十二)之地震偏移处理
  6. 文通表格票据识别系统介绍
  7. poi导出excel 损坏_急!!!java用poi导出excel文件,打开导出的文件时报错“文件错误,数据可能丢失”...
  8. 360第三季营收21亿:净亏近16亿 财务负责人离职
  9. 服务机器人有关的计算机技术,《服务机器人科技发展“十二五”专项规划》解读...
  10. 多线程入门级教学!!!