水波模仿的实现要领
副标题#e#
在一个波长范畴内,任意点的位移disp=sin(dist)*force+disp_center;
这里设水波为正弦波,振幅为force,disp_center为振中的位移。
推广到任何点,disp=sin(dist%wave_length)*force+disp_center;
这里wave_length为波长。可以看出,在离散的数据中,任何点的位移是有限的荟萃。我们先结构出这个荟萃,在运算进程中,从荟萃中选取一个位移值就行了,而不消及时计较每个点的位移。
措施设计如下:取波长为12,任何点的位移由一个12个元素的数组。
int disp[12];
成立一个数构成存贮各点来振中的间隔
int dist[600][800];
下面生成一个水波
inline void Build_Disp_Matrix() { for(int i = 0; i < 12; ++i) disp = static_cast<int>(sin((double)i*30*DXPI/360)*PRECISION); } void Create_Ripple(int center_x, int center_y, int force, int damp, int wave_length) { for(int i = 0 ; i < wave_length; ++i) { disp = force * disp / PRECISION; } int dist_x, dist_y; for(i = 0; i < SCREEN_HEIGHT; ++i) { for(int j = 0; j< SCREEN_WIDTH; ++j) { dist_y = i - center_y; dist_x = j - center_x; dist[j] = static_cast<int>(sqrt(dist_x*dist_x + dist_y*dist_y) + 0.5) % wave_length; } } }
#p#副标题#e#
渲染水波的代码与本来的代码一样。
void Render_Ripple(LPDIRECTDRAWSURFACE7 lpdds) { DDSURFACEDESC2 ddsd = { sizeof(ddsd) }; if(disp_index < 0) disp_index = 12; --disp_index; lpdds->Lock(NULL,&ddsd, DDLOCK_WAIT | DDLOCK_SURFACEMEMORYPTR, NULL); short* lpSrcBuffer = static_cast<short*>(pBmpBack->GetBitmapBuffer()); int pitch = (ddsd.lPitch) >> 1; short* lpBuffer = static_cast<short*>(ddsd.lpSurface); int left,right,bottom,top; int k = 0,l = 0; int index_x,index_y; int x_off,y_off; int pos1,pos2; for(int i = 1; i < SCREEN_HEIGHT - 2; ++i) for( int j = 1; j < SCREEN_WIDTH - 2; ++j) { left = right = bottom = top = disp_index; left += dist[j -1]; if(left > 12) left -= 12; right += dist[j+1]; if(right >12) right -= 12; bottom += dist[i+1][j]; if(bottom > 12) bottom -= 12; top += dist[i-1][j]; if(top >12 ) top -= 12; x_off = disp[left] - disp[right]; y_off = disp[top] - disp[bottom]; index_x = j + x_off; index_y = i + y_off; pos1 = i*pitch +j; pos2 = index_y * 800 + index_x; if(pos2 < 0 || pos2 > 479999) break; lpBuffer[pos1] = lpSrcBuffer[pos2]; } pBmpBack->ReleaseBuffer(); lpdds->Unlock(NULL); }