Generating Perlin Noise in C#


Noise textures are often very important in lots of algorithms used in computer graphics.

This post will show a simple implementation of the classic Perlin Noise technique.

The code below shows a class responsible for generating each point of the noise texture. The implementation is simple, we used the perlin formula to generate the point, and after we make a bilinear interpolation to smooth a little the sample:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PloobsEngine.Utils
{
    /// Perlin Noise
    public class PerlinNoise
    {
        /// Perlin Noise Constructot
        public PerlinNoise(int width, int height)
        {
            this.MAX_WIDTH = width;
            this.MAX_HEIGHT = height;                
        }

        public int MAX_WIDTH = 256;
        public int MAX_HEIGHT = 256;
                
        /// Gets the value for a specific X and Y coordinate
        /// results in range [-1, 1] * maxHeight
        public float GetRandomHeight(float X, float Y, float MaxHeight,
            float Frequency, float Amplitude, float Persistance,
            int Octaves)
        {
            GenerateNoise();
            float FinalValue = 0.0f;
            for (int i = 0; i < Octaves; ++i)
            {
                FinalValue += GetSmoothNoise(X * Frequency, Y * Frequency) * Amplitude;
                Frequency *= 2.0f;
                Amplitude *= Persistance;
            }
            if (FinalValue < -1.0f)
            {
                FinalValue = -1.0f;
            }
            else if (FinalValue > 1.0f)
            {
                FinalValue = 1.0f;
            }
            return FinalValue * MaxHeight;
        }

        //This function is a simple bilinear filtering function which is good (and easy) enough.        
        private float GetSmoothNoise(float X, float Y)
        {
            float FractionX = X - (int)X;
            float FractionY = Y - (int)Y;
            int X1 = ((int)X + MAX_WIDTH) % MAX_WIDTH;
            int Y1 = ((int)Y + MAX_HEIGHT) % MAX_HEIGHT;
            //for cool art deco looking images, do +1 for X2 and Y2 instead of -1...
            int X2 = ((int)X + MAX_WIDTH - 1) % MAX_WIDTH;
            int Y2 = ((int)Y + MAX_HEIGHT - 1) % MAX_HEIGHT;
            float FinalValue = 0.0f;
            FinalValue += FractionX * FractionY * Noise[X1, Y1];
            FinalValue += FractionX * (1 - FractionY) * Noise[X1, Y2];
            FinalValue += (1 - FractionX) * FractionY * Noise[X2, Y1];
            FinalValue += (1 - FractionX) * (1 - FractionY) * Noise[X2, Y2];
            return FinalValue;
        }

        float[,] Noise;
        bool NoiseInitialized = false;
        /// create a array of randoms
        private void GenerateNoise()
        {
            if (NoiseInitialized)                //A boolean variable in the class to make sure we only do this once
                return;
            Noise = new float[MAX_WIDTH, MAX_HEIGHT];    //Create the noise table where MAX_WIDTH and MAX_HEIGHT are set to some value>0            
            for (int x = 0; x < MAX_WIDTH; ++x)
            {
                for (int y = 0; y < MAX_HEIGHT; ++y)
                {
                    Noise[x, y] = ((float)(StaticRandom.Random()) - 0.5f) * 2.0f;  //Generate noise between -1 and 1
                }
            }
            NoiseInitialized = true;
        }

    }
}

To transform the sampled points in a texture you could use the following code:

public Texture2D CreatePerlinNoiseTexture(int sizex, int sizey,float frequencia, float amplitude, float persistence, int octave,bool mipmap = false)
        {
            PerlinNoise pn = new PerlinNoise(sizex, sizey);
            Texture2D t = factory.CreateTexture2D(sizex, sizey,mipmap); ///helper that creates a simple empty texture
            Color[] cor = new Color[sizex * sizey];
            for (int i = 0; i < sizex; i++)
            {
                for (int j = 0; j < sizey; j++)
                {
                    float value = pn.GetRandomHeight(i, j, 1, frequencia, amplitude, persistence, octave);
                    value =  0.5f * (1 + value);
                    cor[i + j * sizex] = new Color(value,value,value);
                }
            }

            t.SetData(cor);
            return t;            
        }

  1. #1 by agen poker on 27 de junho de 2017 - 7:07 am

    Hey there. I discovered your site by the use of Google even as searching for a comparable matter, your web site came up. It seems to be good. I have bookmarked it in my google bookmarks to come back then.

  2. #2 by katie on 27 de junho de 2017 - 8:14 am

    diet pills quad a lean mean team rocket

  3. #3 by free download for windows 10 on 27 de junho de 2017 - 9:09 am

    we like to honor quite a few other online web-sites around the internet, even though they arent linked to us, by linking to them. Beneath are some webpages worth checking out

  4. #4 by Download Video Bokep on 27 de junho de 2017 - 1:36 pm

    Hey there. I found your site via Google at the same time as searching for a similar matter, your website got here up. It looks good. I have bookmarked it in my google bookmarks to visit then.

  5. #5 by storagesolutions-selfstorage.ca on 27 de junho de 2017 - 1:57 pm

    Right now, more than 10 online rummy corporations
    are competing for a slice of the pie. With Adda52 Stay, Rockets Poker
    Room is now dwelling to a very powerful tourneys within the
    nation providing giant assure tournaments on a weekly
    foundation with loads of cash sport action. I would like to reiterate that there may be punishment of upto
    2 years and/or high-quality of few thousand rupees for any form
    of unauthorised gambling, including card games the place there’s talent (poker and so forth.) Even if certain types of gambling are prevalent doesn’t mean that you may escape liabilty if
    it comes to the discover of the authorities.

    Along with maintaining discipline in all of the things you do in on-line poker, becoming a
    successful poker participant additionally involves study. You might want to play
    your hand because the state of affairs dictates and never get married to a hand just because it’s
    a lengthy-term winner. Low variations of other poker variants can also be played, and additionally
    it is attainable to play that there are two winners, the holders of the very best and lowest arms splitting the pot.
    There’s also one other act which could be thought-about to relate to online betting and gaming:
    The Data Expertise Act of 2000. Marginal poker fingers come in all dimensions and shapes but are largely good drawing hands similar to connectors,
    suited playing cards, smaller pairs, and even two gapped cards
    like J9, T8, fifty three, and so on.

    Holding Two Pair gives a participant extra weight within the sport as it’s
    one step greater than Pair. Poker odds is a really concerned matter and never one thing
    that you’ll discover straightforward to master without assist.
    Sure, there are some unhealthy beats during which
    despite all of the skill, a bad card can destroy your game.
    An avid poker player, he give up his plush, handsomely rewarding funding
    banking job and took to enjoying poker professionally, for a
    living. Texas Holdem, Omaha, Blaze Poker, Sit within the exceedingly unlikely event that two players
    both have a straight flush, their rank is decided by the best card
    within the straight, with an ace-excessive straight flush being the strongest possible hand in poker
    (referred to as a royal flush). http://storagesolutions-selfstorage.ca/user-profile/userid/634606.aspx

  6. #6 by travel Asia on 27 de junho de 2017 - 2:43 pm

    Your place is valueble for me. Thanks!…

  7. #7 by ac Miami on 27 de junho de 2017 - 2:57 pm

    that would be the end of this article. Right here you will locate some websites that we believe you will enjoy, just click the links over

  8. #8 by qiu qiu online on 27 de junho de 2017 - 3:03 pm

    Hiya, I am really glad I’ve found this information. Today bloggers publish only about gossip and net stuff and this is actually annoying. A good blog with interesting content, this is what I need. Thank you for making this site, and I will be visiting again. Do you do newsletters by email?

  9. #9 by real sword on 27 de junho de 2017 - 3:12 pm

    Exceptional sword i have too look up a sharpening stone to

  10. #10 by samurai katana sword on 27 de junho de 2017 - 3:24 pm

    This is a pretty nice sword however for the money there are better swords. When i received mine i saw on the blade that it appeared to have 2 hamons… yeah one was much more prominent than the other and its hardly noticeable and blade also looks scratchy. the tsuka was very nice and all the fittings were nice. All in all this is a good buy, you will be satisfied

  11. #11 by pc app on 27 de junho de 2017 - 3:39 pm

    below you will come across the link to some web-sites that we assume you ought to visit

  12. #12 by Pet Care Services on 27 de junho de 2017 - 3:48 pm

    I would like to thank you for the efforts you have put in writing this website. I’m hoping the same high-grade blog post from you in the upcoming also. In fact your creative writing abilities has inspired me to get my own website now. Actually the blogging is spreading its wings quickly. Your write up is a great example of it.

  13. #13 by iphone reviews on 27 de junho de 2017 - 4:17 pm

    Hey there. I found your website by the use of Google while looking for a related subject, your web site came up. It seems good. I have bookmarked it in my google bookmarks to visit then.

  14. #14 by nonton bokep on 27 de junho de 2017 - 6:14 pm

    Awesome write-up. I’m a normal visitor of your site and appreciate you taking the time to maintain the nice site. I will be a regular visitor for a long time.

  15. #15 by Poker Online on 27 de junho de 2017 - 6:58 pm

    Many of us stumbled over here originating from a diverse website along with believed I may verify points out there. I love what I observe Perlin noise implementation in c# | Ploobs thus i’m right after an individual. Enjoy covering your internet web page once again. Poker Online http://www.feraripoker.org/

  16. #16 by self catering accommodation in Kenya on 27 de junho de 2017 - 6:59 pm

    Greetings! I know this is somewhat off topic but I was wondering if you knew where I could locate a captcha plugin for my comment form? I’m using the same blog platform as yours and I’m having difficulty finding one? Thanks a lot!

  17. #17 by Rabbit vibrators on 27 de junho de 2017 - 8:24 pm

    just beneath, are numerous completely not related sites to ours, nevertheless, they are surely really worth going over

  18. #18 by Tsuka For Sale on 27 de junho de 2017 - 9:28 pm

    This sword is the best in my collection, and you can’t get a better sword made in Japan for this price!

  19. #19 by waterproof vibrator on 27 de junho de 2017 - 10:48 pm

    please stop by the sites we stick to, like this 1, as it represents our picks in the web

  20. #20 by http://carreleasedatereview.com on 27 de junho de 2017 - 10:49 pm

    Hey there. I found your site by way of Google at the same time as searching for a related topic, your web site got here up. It looks great. I’ve bookmarked it in my google bookmarks to come back then.

  21. #21 by self catering accommodation in Nampula on 27 de junho de 2017 - 11:12 pm

    Merely a smiling visitant here to share the love (:, btw great style. “The price one pays for pursuing a profession, or calling, is an intimate knowledge of its ugly side.” by James Arthur Baldwin.

  22. #22 by pass drug test on 28 de junho de 2017 - 2:16 am

    Attractive portion of content. I simply stumbled upon your website and in accession capital to assert that I acquire actually enjoyed account your blog posts. Any way I’ll be subscribing to your feeds and even I achievement you access constantly rapidly.|

  23. #23 by nutrition facts on 28 de junho de 2017 - 3:08 am

    Hiya, I am really glad I have found this info. Today bloggers publish just about gossip and net stuff and this is really frustrating. A good web site with interesting content, this is what I need. Thanks for making this web site, and I will be visiting again. Do you do newsletters by email?

  24. #24 by Alberto on 28 de junho de 2017 - 4:33 am

    Hello, yeah this paragraph is truly nice and I have learned
    lot of things from it about blogging. thanks.

  25. #25 by Coach Outlet Store Online on 28 de junho de 2017 - 4:59 am

    Hey there. I found your website by the use of Google while looking for a related subject, your web site got here up. It seems to be great. I’ve bookmarked it in my google bookmarks to come back then.

  26. #26 by Poker online uang asli on 28 de junho de 2017 - 6:59 am

    Good splendid submitting! I must say i appreciated reading it, you could be an excellent creator.I’ll ensure that Perlin noise implementation in c# | Ploobs My partner and i save your website and could revisit in the future. I must motivate a person carry on your wonderful writing, have a very good nighttime!. Poker online uang asli http://www.feraripoker.org/

  27. #27 by self catering accommodation in Botswana on 28 de junho de 2017 - 7:50 am

    I will immediately seize your rss feed as I can’t in finding your email subscription hyperlink or newsletter service. Do you’ve any? Kindly permit me recognise so that I could subscribe. Thanks.

  28. #28 by best auto insurance reviews on 28 de junho de 2017 - 7:51 am

    Hello there. I found your site by means of Google while looking for a related topic, your website got here up. It seems good. I have bookmarked it in my google bookmarks to come back then.

1 373 374 375
(não será publicado)