views:

324

answers:

3

I'm trying to make the Perlin noise algorithm described at http://freespace.virgin.net/hugo.elias/models/m_perlin.htm using Lua. However, it doesn't work properly since Lua doesn't support bitwise operators, which are necessary for the pseudorandom number function on that page. I tried messing around with randomseed() but everything I could come up with just made really bizarre patterns. I need a pseudorandom number generator that will generate numbers between -1 and 1 when given the parameters x, y, and a random seed. Pseudocode is fine.

Thanks!

+5  A: 

There have been lua libraries made for this, one I found is: lrandom

It uses the Mersenne Twister algorithm which may suit your needs better.

NWCoder
I couldn't find the link for that. Also, this is just script for a game (side project) so I don't have access to install C libraries.
phpscriptcoder
The link is there: http://www.tecgraf.puc-rio.br/~lhf/ftp/lua/5.1/lrandom.tar.gz but it won't help you if you can't use C libraries.
lhf
A: 

I don't know of any pure Lua solution for the pseudorandom number issue, but you could try to write the algorithm you mention using some pure Lua bit libraries.

I found these in the Wiki:

  • LuaBit is a bitwise operation lib totally written in Lua. The bitwise operations supported are: not, and, or, xor, right shift and left shift. Several utilities: hex to dec, utf8 to usc2 and nokia .nfb to txt.
  • BitUtils are bitwise operations implemented entirely in Lua.
  • Module Compress Deflate includes bit.numberlua, which implements bitwise operations in pure Lua as numbers.
Ignacio
I got LuaBit to work. Another problem though...function noise1(x, y) n = x + y * 57 n = bit.blshift(n, 13) ^ n; n2 = ( 1.0 - ( bit.band(round((n * (n * n * 15731 + 789221) + 1376312589)), 2147483647)) / 1073741824.0) return n2;endn by itself is already quite large. Then it's bitshifted 13 to the left. At this point it is 8 or 9 digits... then it is raised to the nth power. The resulting number is so large that it is turned into infinity, so the final output of the function is always 1 except for very low values of x and y
phpscriptcoder
A: 

It is easy to make a linear congruential random number generator in Lua. A simple one is Park-Miller

function pmrng (x) return math.fmod(x * 16807, 2147483647) end

This will give you the next random integer [1..2147483646] after x, the seed. Use this integer to make a float by dividing by the modulus, 2147483647 in this case.

prng_seed = 13579
function upmrng () prng_seed = pmrng(prng_seed); return prng_seed / 2147483647 end

To scale this to -1 .. +1 do

upmrng() * 2 - 1
Doug Currie