00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00033
00034 #include "platform/heightmap.hpp"
00035
00036 #include <cmath>
00037
00038 namespace gsgl
00039 {
00040
00041 using namespace data;
00042
00043 namespace platform
00044 {
00045
00046 heightmap::heightmap(const gsgl::index_t & width, const gsgl::index_t & height, gsgl::real_t *data)
00047 : width(width), height(height), data(data), own_pointer(!data)
00048 {
00049 if (!data)
00050 data = new gsgl::real_t[width*height];
00051 }
00052
00053
00054 heightmap::~heightmap()
00055 {
00056 if (own_pointer)
00057 delete [] data;
00058 }
00059
00060
00061 gsgl::real_t heightmap::interpolate(const gsgl::real_t & s, const gsgl::real_t & t, const interpolate_mode mode, const gsgl::flags_t flags)
00062 {
00063 gsgl::real_t result = 0;
00064
00065 if (mode == INTERPOLATE_BILINEAR)
00066 {
00067
00068 gsgl::real_t x_pixel = ::floor(s * width);
00069 gsgl::real_t x_diff = (s * width) - x_pixel;
00070 gsgl::real_t x = (x_diff >= 0.5f) ? x_diff - 0.5f : x_diff + 0.5f;
00071
00072 int x_index_0 = (x_diff < 0.5f) ? static_cast<int>(x_pixel-1) : static_cast<int>(x_pixel);
00073 int x_index_1 = x_index_0 + 1;
00074
00075 if (x_index_0 < 0)
00076 {
00077 if (flags & WRAP_S)
00078 x_index_0 = width + x_index_0;
00079 else
00080 x_index_0 = x_index_1;
00081 }
00082
00083 if (x_index_1 >= width)
00084 {
00085 if (flags & WRAP_S)
00086 x_index_1 = width - x_index_1;
00087 else
00088 x_index_1 = x_index_0;
00089 }
00090
00091
00092 gsgl::real_t y_pixel = ::floor(t * height);
00093 gsgl::real_t y_diff = (t * height) - y_pixel;
00094 gsgl::real_t y = (y_diff >= 0.5f) ? y_diff - 0.5f : y_diff + 0.5f;
00095
00096 int y_index_0 = (y_diff < 0.5) ? static_cast<int>(y_pixel-1) : static_cast<int>(y_pixel);
00097 int y_index_1 = y_index_0 + 1;
00098
00099 if (y_index_0 < 0)
00100 {
00101 if (flags & WRAP_T)
00102 y_index_0 = height + y_index_0;
00103 else
00104 y_index_0 = y_index_1;
00105 }
00106
00107 if (y_index_1 >= height)
00108 {
00109 if (flags & WRAP_T)
00110 y_index_1 = height - y_index_1;
00111 else
00112 y_index_1 = y_index_0;
00113 }
00114
00115
00116 gsgl::real_t f00 = data[ (y_index_0 * width) + x_index_0 ];
00117 gsgl::real_t f01 = data[ (y_index_1 * width) + x_index_0 ];
00118 gsgl::real_t f10 = data[ (y_index_0 * width) + x_index_1 ];
00119 gsgl::real_t f11 = data[ (y_index_1 * width) + x_index_1 ];
00120
00121
00122 result = f00*(1-x)*(1-y) + f10*x*(1-y) + f01*(1-x)*y + f11*x*y;
00123 }
00124 else
00125 {
00126 throw runtime_exception(L"Interpolation other than bilinear is not supported at this time.");
00127 }
00128
00129 return result;
00130 }
00131
00132
00133 }
00134
00135 }
00136