class Perlin::GradientTable

Public Class Methods

new(dim, interval = 256, seed = nil) click to toggle source

Bit-wise AND operation is not any faster than MOD in Ruby MOD operation returns positive number for negative input

# File lib/perlin/gradient_table.rb, line 22
def initialize dim, interval = 256, seed = nil
  @dim = dim
  @interval = interval
  @random = Random.new(*[seed].compact)

  @table   = Array.new(interval) { @random.rand @interval }
  @vectors = Array.new(interval) { random_unit_vector }
end

Public Instance Methods

[](*coords) click to toggle source
# File lib/perlin/gradient_table.rb, line 31
def [](*coords)
  @vectors[index(*coords)]
end

Private Instance Methods

index(*coords) click to toggle source

A simple hashing

# File lib/perlin/gradient_table.rb, line 38
def index(*coords)
  s = coords.last
  coords.reverse[1..-1].each do |c|
    s = perm(s) + c
  end
  perm(s)
end
perm(s) click to toggle source
# File lib/perlin/gradient_table.rb, line 46
def perm(s)
  @table[s % @interval]
end
random_unit_vector() click to toggle source
# File lib/perlin/gradient_table.rb, line 50
def random_unit_vector
  while true
    v = Vector[*Array.new(@dim) { @random.rand * 2 - 1 }]
    # Discards vectors whose length greater than 1 to avoid bias in
    # distribution
    break if v.r > 0 && v.r <= 1
  end
  v.map { |e| e / v.r }
end