lighter Random function

Started by
7 comments, last by Dan Violet Sagmiller 11 years ago

This is related to C#/Unity, but it boils down to simple math/loops/shifts.

Here is the basic idea of the random functions I have:

public float GetRand(int seed, int x, int y) {

return (float)(new Random(seed + x + (y <<16)).NextDouble();

}

public int GetRand(int seed, int x, int y, int range) {

return (new Random(seed + x + (y <<16)).Next(range);

}

The problem is that when the client side starts, its calling both these functions about a million times (1024x1024 tile buffer), which means that I generate 1,048,576 new random objects that are immediately discarded.

I'm using this to determine the height and tile type of each tile on a game map. The server and the client will need to know the same information, but from the map sizes, that is easily 50 megs of data. Instead of transferring this data from server to client, and requiring the server to maintain this data for every user, when I need to know a tile height/position, I simply rely on this.

The client needs to do this in bulk, to preload an area of the map. The server is a restful API, and usually doesn't care about specific terrain. but when it does, I simply have it request a rectangle of the height map or a region of the tile type map, which is generated on the fly by these functions.

What I would like, is to reduce the function down to a smaller math example to get a pseudo random value instead of producing/depending on new random objects.

So far, my existing functions work, and the speed is not bad on client or server, but it seems like an area that could get a quick boost in speed, and I'll need that as I add more features.

Moltar - "Do you even know how to use that?"

Space Ghost - “Moltar, I have a giant brain that is able to reduce any complex machine into a simple yes or no answer."

Dan - "Best Description of AI ever."

Advertisement

You're using the Random class wrong. You should create an instance once, at startup, with a seed, and then continously call next on that instance, instead of creating a new one for each call.

You are not supposed to change the seed each call, and the coordinates you send in will just mess up the sequence for the random number generator, and make it produce less wellbehaved random result.

Using it properly should speed it up a lot

If you want reproducable result, you just need to save one seed for each level

What Olof said. Also, if you want to be able to compute the number for each x, y without going through the whole sequence (which your current code allows but Olof's suggestion wouldn't), what you want is a hash function. Your current code is abusing the PRNG as a hash function, which is less than ideal (and probably very slow).

See if this is fast enough and random enough for you:
public uint GetHash(int seed, int x, int y) {
  uint hash = seed;
  hash ^= x;
  hash *= 0x51d7348d;
  hash ^= 0x85dbdda2;
  hash = (hash << 16) ^ (hash >> 16);
  hash *= 0x7588f287;
  hash ^= y;
  hash *= 0x487a5559;
  hash ^= 0x64887219;
  hash = (hash << 16) ^ (hash >> 16);
  hash *= 0x63288691;
  return hash;
}

public float GetRand(int seed, int x, int y) {
  return (float)GetHash(seed, x, y) / 4294967296.0f;
}

public int GetRand(int seed, int x, int y, int range) {
  return GetHash(seed, x, y) % range;
}

@olof Hedman:

- I would agree, accept that you should think of this more like Minecraft on a restful service. The world map is virtually infinite (2 billion tiles in any direction) . I.e. it is not a level. I could section it off. but this is ultimately more effective. If the server has to pull up data to figure something out, I don't want to have to pull entire sections, especially if something is on the kusp, and in order to validate the position of 4 tiles, it has to pull up 4 maps of 64x64. In this case, most of the processing will be for 12 tiles at a time or less on the server. I want the server to be able to handle hundreds of clients. Since it is a restful service, it won't be retaining live connections or session data for anyone. The only thing the server holds in memory is a single sessionkey/id to make sure the source is valid and maintain a single sign in.

Also, Microsoft's Random, uses math code that loops an equation 110 times, half of which contain an if statement. seems horribly inefficient to use random even the way you suggest.

@Alvaro:

THANK YOU!!!! This code does exactly what I need, and is more efficient than Microsoft's.

Moltar - "Do you even know how to use that?"

Space Ghost - “Moltar, I have a giant brain that is able to reduce any complex machine into a simple yes or no answer."

Dan - "Best Description of AI ever."

@olof Hedman:

- I would agree, accept that you should think of this more like Minecraft on a restful service. The world map is virtually infinite (2 billion tiles in any direction) . I.e. it is not a level. I could section it off. but this is ultimately more effective. If the server has to pull up data to figure something out, I don't want to have to pull entire sections, especially if something is on the kusp, and in order to validate the position of 4 tiles, it has to pull up 4 maps of 64x64. In this case, most of the processing will be for 12 tiles at a time or less on the server. I want the server to be able to handle hundreds of clients. Since it is a restful service, it won't be retaining live connections or session data for anyone. The only thing the server holds in memory is a single sessionkey/id to make sure the source is valid and maintain a single sign in.

Also, Microsoft's Random, uses math code that loops an equation 110 times, half of which contain an if statement. seems horribly inefficient to use random even the way you suggest.

@Alvaro:

THANK YOU!!!! This code does exactly what I need, and is more efficient than Microsoft's.

Well, the way you use random makes it much less random (if random at all - your GetRand() is basically a simple f(x,y) ).

You're seeding every time you create a new Random object.

As far as i know, adding up seeds seeds and using the first result makes the result more predictable than following a sequence (Like alvaro said; "a less wellbehaved random result").

Regardless, the Random object could be allocated once, and then re-seeded later.

This alone would speed up things a lot.

Also, try storing the random bits of your world in larger chunks, if they really need to divert in seed.

I think you shouldn't need that many seeds, though - Think it through again.

(Alvaro's approach is very nice for addressing, but its usage in your code should be founded on a solid address-value principle. You want to be able to fetch the values dynamically, even from places far away. The addressing has little to do with randomization. (And therefore has nothing to do with Microsoft's random being "slow".))

On time tests between Random, and the code @Alvaro provided:

1,000,000 loops

new Random(seed).NextDouble() = 3900+ ms constantly

Alvaro's float GetRand = < 67 ms constantly

Much better perf.

Moltar - "Do you even know how to use that?"

Space Ghost - “Moltar, I have a giant brain that is able to reduce any complex machine into a simple yes or no answer."

Dan - "Best Description of AI ever."

here is the random code I use for this:


        public static uint GetHash(int seed, int x, int y)
        {
            uint hash = (uint)seed;
            hash ^= (uint)x;
            hash *= 0x51d7348d;
            hash += 0x85dbdda2;
            hash = (hash << 16) ^ (hash >> 16);
            hash *= 0x7588f287;
            hash ^= (uint)y;
            hash *= 0x487a5559;
            hash += 0x64887219;
            hash = (hash << 16) ^ (hash >> 16);
            hash *= 0x63288691;
            return hash;
        }


        public static float GetRand(int seed, int x, int y)
        {
            return (float)GetHash(seed, x, y) / 4294967296.0f;
        }


        public static int GetRand(int seed, int x, int y, int range)
        {
            return (int)(GetHash(seed, x, y) % range);
        }
 

It doesn't actually need to be as Random as provided by System.Random. I need it to have the general shift to disguise obvious patterns related to X and Y coordinates. I just wasn't finding the best way to describe that.
A point we have to ask our selves, is how "random" do we need it to be? I've looked through the results I've gotten back, and so far, everything appears nice and random, without a significantly noticable pattern. Once I apply this to the X/Y grid, that might change though.
Thanks for your assistance.

Moltar - "Do you even know how to use that?"

Space Ghost - “Moltar, I have a giant brain that is able to reduce any complex machine into a simple yes or no answer."

Dan - "Best Description of AI ever."

It looks like you copied my code immediately after I posted it. I realized then that I accidentally posted "+=" in a couple of lines where I means "^=". I have some evidence to believe that "^=" makes the generated numbers much more random looking, and the performance shouldn't be much slower.

I just wanted to say this before someone posts a picture showing obvious patterns in the numbers generated with that code (which do exist).

actually, the pattern works pretty well in my case, I'm using the int range to select the tile image, and I'm using the float to set the height.

*please note: this texture setup is does not have setups smooth transitions yet. This is only intended to show the randomization via the new code.

03.27.2013-13.30.png

Moltar - "Do you even know how to use that?"

Space Ghost - “Moltar, I have a giant brain that is able to reduce any complex machine into a simple yes or no answer."

Dan - "Best Description of AI ever."

This topic is closed to new replies.

Advertisement