Search code examples
algorithmmathrandomterrainlevel-of-detail

Pseudo random number generator from two inputs


I need a pseudo random number generator that gives me a number from the range [-1, 1] (range is optional) from two inputs of the type float.

I'll also try to explain why I need it:

I'm using the Diamond-Square algorithm to create a height map for my terrain engine. The terrain is split into patches (Chunked LOD).

The problem with Diamond-Square is that it uses the random function, so let's say two neighbor patches are sharing same point (x, z) then I want the height to be the same for them all so that I won't get some crack effect.

Some may say I could fetch the height information from the neighbor patch, but then the result could be different after which patch was created first.

So that's why I need a pseudo number generator that returns an unique number given two inputs which are the (x, z).

(I'm not asking someone to write such function, I just need a general feedback and or known algorithms that do something similar).


Solution

  • You need something similar to a hash function on the pair (x, z).

    I would suggest something like

    (a * x + b * z + c) ^ d

    where all numbers are integers, a and b are big primes so that the integer multiplications overflow, and c and d are some random integers. ^ is bitwise exclusive or. The result is a random integer which you can scale to the desired range.

    This assumes that the map is not used in a game where knowing the terrain is of substantial value, as such a function is not secure for keeping it a secret. In that case you'd better use some cryptographic function.