A place to store little code jewels

September 6, 2015November 29, 2015

Potential Energy field

Hello All!

As my first post, I will realize an ASP.NET web page which show an image with a potential energy field from different charges. This generates a very nice effect that can be translated to somewhat psychedelic pictures, and as well, what will be discused in next posts, can be used for example to know the most efficient path for go from a point to another avoiding charged obstacles. Using this code theme, this post will cover:

Generating online web images in ASP.NET

Partial web rendering

Use of MemoryStream to work with bitmaps

First of all, we are going to use codebehind: so, will define our web page schema and then we will work on it. We will need : some text boxs to indicate image size, a textbox that indicate parameter analog to Coulombs constant (K) and as well the maximum / 2 value of a charge can be. As well, we will put an asp:Button and a asp:Image objects in an UpdatePanel (in need of a ScriptManager) object, so this way any image reload, by a postback call by tbGenerate button, will not force all whole page to reload. This little trick will avoid flickering when generating new field images, and can be used for a lot of purposes without really lack of performance of the whole web page.

Once we got the page template, let’s going to fill it with code. The main purpose it’s very simple: a click of tbGenerate button will generate an image with the calculated field. First of all, we will abstract a charge with a class :

Due each charge, with a value q, does a potential contribution to a point x,y by V = KQ/r², where r its module distance from that point to the location of the charge, then the function to get V potential at a point will be:

Finally, there’s no more than, in btGenerate click event, realize a bitmap, calculating value at each x,y pixel, and mapping it to a color. For simplicity, we get the value of field V(x,y) to a byte (that way there’s an automatic 0xff modulus) and then, translate that value to an RGB gray color. When got the bitmap generated, we simply save it to a memory stream bitmap, and then, encoded as a Base64 string, we add it to the asp:Image url we got in our UpdatePanel object:

So that’s all! Got a random, beauty, and consistent image from physics of each day. Don’t hesitate to play with values and of course, with the mapping to a color (try for example different FromARgb(r,g,b) percentages). As well, you can play with K and Max Charges and so on, and you will found some different (and real) behaviours of the potential field.