Source

BASIC-RoBots / src / noise.py

Full commit
##
## noise.py for BASIC-RoBots
##
## Copyright (C) 2012 Pierre Surply
## <pierre.surply@gmail.com>
##
## This file is part of BASIC-RoBots.
##
##    BASIC-RoBots is free software: you can redistribute it and/or modify
##    it under the terms of the GNU General Public License as published by
##    the Free Software Foundation, either version 3 of the License, or
##    (at your option) any later version.
##
##    BASIC-RoBots is distributed in the hope that it will be useful,
##    but WITHOUT ANY WARRANTY; without even the implied warranty of
##    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
##    GNU General Public License for more details.
##
##    You should have received a copy of the GNU General Public License
##    along with BASIC-RoBots.  If not, see <http://www.gnu.org/licenses/>.
##  
## Started on  Thu Jun 28 17:06:53 2012 Pierre Surply
## Last update Wed Aug  1 17:49:37 2012 Pierre Surply
##

import random
import math

class Noise:
    def __init__(self, w, h, p, n):
        self.w = w
        self.h = h
        self.p = p
        self.n = n
        self.w_max = int(math.ceil(w * pow(2, n-1) / p))
        self.h_max = int(math.ceil(h * pow(2, n-1) / p))
        
        self.values = [0] * (self.w_max * self.h_max + 1)
        
        for i in range(len(self.values)):
            self.values[i] = random.random()

    def get_noise(self, x, y):
        return self.values[x * self.w_max + y]

    def inter_cos1D(self, a, b, x):
        k = (1 - math.cos(x * math.pi)) / 2
        return a * (1-k) + b*k

    def inter_cos2D(self, a, b, c, d, x, y):
        y1 = self.inter_cos1D(a, b, x)
        y2 = self.inter_cos1D(c, d, x)
        return self.inter_cos1D(y1, y2, y)

    def noise_func(self, x, y):
        i = int(x / self.p)
        j = int(y / self.p)
        return self.inter_cos2D(self.get_noise(i, j), \
                                    self.get_noise(i+1, j), \
                                    self.get_noise(i, j+1), \
                                    self.get_noise(i+1, j+1),\
                                    math.fmod(x / self.p, 1),\
                                    math.fmod(y / self.p, 1))

    def smooth_noise(self, x, y, persistance):
        somme = 0
        p = 1
        f = 1
        for i in range(self.n-1):
            somme += p*self.noise_func(x*f, y*f)
            p *= persistance
            f *= 2
        return somme * (1 - persistance) / (1 - p)