00001 #include <stdio.h>
00002 #include <math.h>
00003 #include "PerlinTexture.h"
00004
00005 PerlinTexture::PerlinTexture() {
00006 scale = NONE;
00007 int t = PERLINTEXTURE_BASE_SIZE * PERLINTEXTURE_BASE_SIZE;
00008 data = new unsigned char[t];
00009 };
00010
00011 void PerlinTexture::refresh() {
00012 unsigned char i, j;
00013 int corners, sides, total;
00014 for (i=0; i <= PERLINTEXTURE_BASE_SIZE; i++) {
00015 for (j=0;j <= PERLINTEXTURE_BASE_SIZE; j++) {
00016 *get_scaled(i,j) = _gen_noise(i,j);
00017 }
00018 }
00019 unsigned char* tmpdata;
00020 int t = PERLINTEXTURE_BASE_SIZE * PERLINTEXTURE_BASE_SIZE;
00021 tmpdata = new unsigned char[t];
00022 unsigned char k,l;
00023 for (i=0; i <= PERLINTEXTURE_BASE_SIZE; i++) {
00024 for (j=0;j <= PERLINTEXTURE_BASE_SIZE; j++) {
00025 *(tmpdata + i * j + i) = _smooth(i, j);
00026 }
00027 }
00028 delete data;
00029 data = tmpdata;
00030 tmpdata = NULL;
00031 }
00032
00033 unsigned char PerlinTexture::_gen_noise(unsigned char x, unsigned char y) {
00034 unsigned int n;
00035 n = x + y * 57;
00036 n = (unsigned int)pow((n << 13), n);
00037 n = n * (n * n * 15731 + 789221) + 1376312589;
00038 n = n & 0x7fffffff;
00039 n = (unsigned int) n / 1073741824.0;
00040 return((unsigned char)(1-n));
00041 }
00042
00043
00044 unsigned char PerlinTexture::_smooth(unsigned char x, unsigned char y) {
00045 int corners, sides, total;
00046 corners = (*get_scaled(x - 1, y - 1) +
00047 *get_scaled(x + 1, y - 1) + *get_scaled(x - 1, y + 1) +
00048 *get_scaled(x + 1, y + 1)) / 16;
00049 sides = (*get_scaled(x - 1, y) + *get_scaled(x + 1, y) +
00050 *get_scaled(x, y - 1) + *get_scaled(x, y + 1)) / 8;
00051 total = *get_scaled(x, y) / 4 + sides + corners;
00052 return total;
00053 }