3 Copyright (C) 2010-2011 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23 #define NOISE_MAGIC_X 1619
24 #define NOISE_MAGIC_Y 31337
25 #define NOISE_MAGIC_SEED 1013
27 double cos_lookup[16] = {
28 1.0,0.9238,0.7071,0.3826,0,-0.3826,-0.7071,-0.9238,
29 1.0,-0.9238,-0.7071,-0.3826,0,0.3826,0.7071,0.9238
32 double dotProduct(double vx, double vy, double wx, double wy){
36 double easeCurve(double t){
37 return 6*pow(t,5)-15*pow(t,4)+10*pow(t,3);
40 double linearInterpolation(double x0, double x1, double t){
44 double biLinearInterpolation(double x0y0, double x1y0, double x0y1, double x1y1, double x, double y){
45 double tx = easeCurve(x);
46 double ty = easeCurve(y);
47 double u = linearInterpolation(x0y0,x1y0,tx);
48 double v = linearInterpolation(x0y1,x1y1,tx);
49 return linearInterpolation(u,v,ty);
52 double noise2d(int x, int y, int seed)
54 int n = (NOISE_MAGIC_X * x + NOISE_MAGIC_Y * y
55 + NOISE_MAGIC_SEED * seed) & 0x7fffffff;
57 n = (n * (n*n*60493+19990303) + 1376312589) & 0x7fffffff;
58 return 1.0 - (double)n/1073741824;
61 double noise2d_gradient(double x, double y, int seed)
63 int x0 = (x > 0.0 ? (int)x : (int)x - 1);
64 int y0 = (y > 0.0 ? (int)y : (int)y - 1);
67 int n00 = (int)((noise2d(x0, y0, seed)+1)*8);
68 int n10 = (int)((noise2d(x0+1, y0, seed)+1)*8);
69 int n01 = (int)((noise2d(x0, y0+1, seed)+1)*8);
70 int n11 = (int)((noise2d(x0+1, y0+1, seed)+1)*8);
71 double s = dotProduct(cos_lookup[n00], cos_lookup[(n00-4)%16], xl, yl);
72 double u = dotProduct(-cos_lookup[n10], cos_lookup[(n10-4)%16], 1.-xl, yl);
73 double v = dotProduct(cos_lookup[n01], -cos_lookup[(n01-4)%16], xl, 1.-yl);
74 double w = dotProduct(-cos_lookup[n11], -cos_lookup[(n11-4)%16], 1.-xl, 1.-yl);
75 return biLinearInterpolation(s,u,v,w,xl,yl);
78 double noise2d_perlin(double x, double y, int seed,
79 int octaves, double persistence)
84 for(int i=0; i<octaves; i++)
86 a += g * noise2d_gradient(x*f, y*f, seed+i);