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)
            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
            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);

            return t;            

  1. #1 by what is the best car insurance coverage on 27 de setembro de 2016 - 7:44 pm

    You’ve got it in one. Couldn’t have put it better.

  2. #2 by how to clean a shower head without removing on 27 de setembro de 2016 - 7:58 pm

    I truly appreciate this post.Really looking forward to read more. Awesome.

  3. #3 by apply pr singapore on 27 de setembro de 2016 - 8:46 pm

    Great post!

  4. #4 by motor traders insurance comparison on 27 de setembro de 2016 - 9:07 pm

    What a great site indeed comments content news constantly up to date and quality,this site now and much faster high-quality and fast site that comments are always up to date, admin really want to thank us, it's thanks to such a beautiful site comments we gain knowledge we and listen from this site music

  5. #5 by Ask A Lawyer on 27 de setembro de 2016 - 9:10 pm

    just beneath, are many absolutely not associated sites to ours, nonetheless, they are surely worth going over

  6. #6 by levitra online on 27 de setembro de 2016 - 10:26 pm

    sure how to take it to the…next level and actually begin to write for profit. it’s not as difficult as you might think to go from amateur to professional writer.start by thinking about what type of writing you would want to do if you were writing professionally….

  7. #7 by safe auto car insurance quotes on 27 de setembro de 2016 - 11:01 pm

    铭盛卡行(QQ1228557129)所出售卡均为一级卡源,全新无任何交易记录,资料齐全,真实身份办理,亦可指定名字办理,诚信淘宝担保交易! 例如—可以给你淘宝店刷提高您的淘宝信用记录。 例如—你想接受汇款,但又不想让对方知道自己的真实姓名。 例如—您想给领导送礼办点事情,但是又不想让自己的隐私暴露!这时您就需要到我们提供办理的卡,我们的卡可以让您随意的a转帐–送礼。给客户保密了隐私的同时也去除了客户的后顾之忧。本团队以真实代开卡【QQ:1228557129】办理、分别提供7大银行卡;中国银行—工商银行—建设银行—农业银行—交通银行—招商银行—邮政银行[网上银行(口令卡,电子证书,U盾)长期供应,保证全新开户,保证开户资料齐全,保证带真实有效开户原件,承接指定名字开户我们的宗旨是:质量+速度+信誉!我们希望与 有长期需要的客户建立长期合作关系,彼此信任,共同赢利。如有需要请联系!非诚勿扰! 客户的满意是我们的心愿欢迎光顾公司宗旨: 公司执行国家金融方针和政策,在法律、法规规定的范围内开展业务, 自主经营、自负盈亏、自我约束、自担风险、切实为小企业、农民、农业及农村经济的发展服务。公司文化: 诚信—用心做事,诚信为人 规范—规范管理,依法治企 高效—真诚服务,高效便捷 和谐—同舟共济,创建和谐公司口号: 以实力、效率立足于市场 用服务、便捷来赢得口碑 崇尚职业道德,遵守法律法规  急您所急、思您所思温馨提示:在本卡行购买的卡可用于收藏使用!

  8. #8 by on 27 de setembro de 2016 - 11:11 pm

    Located in Maine we love to our own mud foots. On behalf of me, that Adirondack passes the competition that is very much the same in style. It can be stylish and then decent, and consequently my very own foot or so never ever acquire one of a kind next time i in the morning putting it. I too passion simple fact We carry it by way of its polar environment slush, dirt, puddles, then truly wash that.

  9. #9 by business insurance on your car on 28 de setembro de 2016 - 12:14 am

    Following the anvil on a cable in space question. why not attach a couple of wires to a load of solar panels floating in orbit? solving all our energy problem needs. or cover the sahara with solar panels. aparts from a few scorpions and nomads who’s it gonna hurt?

  10. #10 by cheap car insurance for a 20 year old on 28 de setembro de 2016 - 12:45 am

    prowizje w niektórtych produkatch ubezpieczycieli sięgały kilkudziesięciuprocent. Niestety wielu pazernych agentów nie zadawalo sobie pytania, jak klient ma na tym zarobic, skoro tyle wedruje do kieszeni ich i firmy, która ich zatrudnia.Dopoki klient nie bedzie placil firmie doradczej za doradzanie, to na pewno nie bedzie doradca klienta

  11. #11 by published here on 28 de setembro de 2016 - 12:59 am

    confessions of a marriage counselor play

  12. #12 by sports car insurance rates young drivers on 28 de setembro de 2016 - 2:37 am

    that limiting child labor would “stop my machines”; another said “investors would never receive another dividend”; while a third said that ending child labor would “paralyze the country.”

  13. #13 by cheapest car insurance over 65 on 28 de setembro de 2016 - 3:23 am

    You’re on top of the game. Thanks for sharing.

  14. #14 by michael kors clothing on 28 de setembro de 2016 - 3:32 am

  15. #15 by 3d crystals on 28 de setembro de 2016 - 3:38 am

    Im grateful for the blog post.Really looking forward to read more. Will read on…

  16. #16 by best car insurance companies on 28 de setembro de 2016 - 3:53 am

    And I expect he’ll have to explain what he was doing in the car with Michele Brown.It’s a good thing his wife and kids were with him.The Christie campaign is dying the death of a thousand cuts.Like Humpty Dumpty, all the campaign managers and political advisors can’t put this campaign back together again.

  17. #17 by Yeezy Boost 350 V2 on 28 de setembro de 2016 - 4:26 am

  18. #18 by average car insurance deposit on 28 de setembro de 2016 - 4:26 am

    Next year I will be decorating my daugher’s ‘big girl room’ in preparation for her sibling (hopefully) joining us. I believe a chalkboard tree in yellow would match the whimsical, Alice in wonderland theme I plan on having for her room! :)

  19. #19 by finance with free insurance on 28 de setembro de 2016 - 4:48 am

    Carla, I originally saw this home in Cote Sud at the end of last year and I have to say that this tiny get away made me dream more than any mansion! I also love that you mention Elizabeth Minchilli’s amazing books. She has a fantastic blog too. Bon weekend!

  20. #20 by insurance auto on 28 de setembro de 2016 - 4:55 am

    Unparalleled accuracy, unequivocal clarity, and undeniable importance!

  21. #21 by naruto shippuden online on 28 de setembro de 2016 - 5:15 am

    Very neat article post. Really Great.

  22. #22 by the co-op car insurance reviews on 28 de setembro de 2016 - 5:22 am

    My prayers are with you Rich. Our Lord lets us go out on a limb sometimes and just because we fall sometimes doesn’t mean we’ll break. He asks not only mountain moving faith from us, but also simple trust for reasons known only to Him.Keep on with keeping on.Franc

  23. #23 by low insurance groups on 28 de setembro de 2016 - 5:59 am

    you are not eligble to be president, obvioulsy you shouldn't get taxpayer funds to run and you shouldn't even be allowed to pursue it. Its not discrimination its in the Constitution. Being 35 is also discriminatory, but thats the law as of now and until changed our Republic should follow that law.

  24. #24 by anime online latino on 28 de setembro de 2016 - 6:26 am

    Major thankies for the blog article.Thanks Again. Keep writing.

  25. #25 by best supplements on 28 de setembro de 2016 - 6:52 am

    I appreciate you sharing this blog post.Really looking forward to read more. Really Great.

  26. #26 by liberty mutual auto insurance toll free number on 28 de setembro de 2016 - 7:29 am

    Thank you for sharing superb informations. Your website is very cool. I am impressed by the details that you’ve on this website. It reveals how nicely you understand this subject. Bookmarked this web page, will come back for extra articles. You, my pal, ROCK! I found simply the info I already searched all over the place and simply couldn’t come across. What an ideal website.

  27. #27 by CA statute of limitations auto insurance claim on 28 de setembro de 2016 - 7:31 am

    Wow, marvelous blog layout! How long have you been blogging for? you made blogging look easy. The overall look of your site is fantastic, as well as the content!

  28. #28 by how to become an auto insurance agent in CA on 28 de setembro de 2016 - 8:23 am

    “We have dived with many different dive operations, but SCUBA Shack is now our favorite. It isn’t just the fast boat or great gear; it is the AWESOME people. Jim, Toby and Greg (the dive crew we had) were a lot of fun….”

  29. #29 by hastings direct premier car insurance on 28 de setembro de 2016 - 8:28 am

    that we would accidentally color the wood. We had to, instead, use crayons on the linolium floors in the kitchen. The problem with that was that we would leave crayons on the floor and mom or dad would step on them and smoosh them into the floor leaving more of a mess.

  30. #30 by contact progressive car insurance on 28 de setembro de 2016 - 8:36 am

    Excellent beat ! I would like to apprentice while you amend your web site, how could i subscribe for a blog web site? The account aided me a appropriate deal. I have been tiny bit acquainted of this your broadcast offered shiny transparent concept

  31. #31 by check these guys out on 28 de setembro de 2016 - 8:43 am

    here are some hyperlinks to web sites that we link to simply because we assume they may be worth visiting

  32. #32 by average auto insurance payout on 28 de setembro de 2016 - 9:56 am

    Gratulerer med et lite jubileum. I dag vant jeg i vinlotteriet på jobben så kanskje jeg har vinnerlykke denne uken. 3 lodd til meg. Goood helg skjønne du.

  33. #33 by do students get discount on car insurance on 28 de setembro de 2016 - 10:50 am

    Field,Here we go….. Another case of….Just blame the black man boogie man!Bullsh!t detectors went up right away with this sh!t. It didn’t pass the smell test!I’m so f-ing tired of these Susan Smith white ass women blaming the black man in their damn dirty schemes!I mean got dammit…LEAVE.THE.BROTHAS.ALONE.!

  34. #34 by top article on 28 de setembro de 2016 - 10:57 am

    marriage counseling edmond ok

  35. #35 by фонд за недвижими имоти българия адсиц on 28 de setembro de 2016 - 11:47 am

    WONDERFUL Post.thanks for share..more wait .. …

  36. #36 by high risk liability insurance on 28 de setembro de 2016 - 11:53 am

      LynneApril 22, 2012In real terms women in agriculture are forging new frontiers just like women all over the world, and come to think of it many other previously disadvantaged groups. Awards like this are an opportunity to create a platform to implement a community good project that is close to your heart. Whilst a group of sponsors are willing to back the award winner and she kicks goals for the beneficiaries of her project I say let the RIRDC award go on Ad infinitum.

1 120 121 122
(não será publicado)