Month: July 2013

Animated surface ripple with OpenGL

In the previous article I wrote an example program that drew a 3D surface. Starting with a wireframe, and then progressing to a solid surface. This was a demonstration of my simple graphics library in C. I implemented a very basic drawing library using GDI for Windows and OpenGL for OSX and Linux. I then built the 3D surface using those primitives. In the course of writing the library I got to learn a little about OpenGL. My reason for choosing it in the first place was that it was available on OSX and has a C interface. Having seen some of the OpenGL interface I was keen to do a little bit more with it. In particular I wanted to animate the surface wave I had made, and wanted to render it with lighting effects. OpenGL is perfect for this task.

Windows also has OpenGL, it does not have GLUT though which comes with OSX. So I wrote a small wrapper library that provides a very basic windows creating API that works cross platform. On Windows it creates the Window and then attaches OpenGL to it and provides a message loop. For OSX and Linux it uses GLUT.

The library has one function called OpenGLRun

//////////////////////////////////////////////////////////////////////////////////
//  OpenGLRun
//
//  Starts the OpenGL module. This will create a window of the specified size 
//  which will be used for OpenGL operations. The DrawFunction will be called when//  it is time for the window to be drawn as well as each tick of the timer
//////////////////////////////////////////////////////////////////////////////////
bool
    OpenGLRun
    (
        uint16_t                ResolutionX,            // [in]
        uint16_t                ResolutionY,            // [in]
        char*                   Title,                  // [in]
        LibOpenGlFunction       DrawFunction,           // [in]
        int                     TimerElapseMilliseconds // [in]
    );

The prototype for LibOpenGlFunction is a functiont hat takes no parameters and returns no return code. This function is called every TimerElapseMilliseconds (and also other times it needs to redraw). This function can then use OpenGL drawing commands to draw the frame. When the function returns the library will call “SwapBuffers” to make the instant transition from the previous frame.

In my DrawFunction I drew the surface from the plot function (that made the ripple) out of triangles. OpenGL likes triangles in a 3D space.

//////////////////////////////////////////////////////////////////////////////////
//  DrawMesh
//
//  Draws the mesh using OpenGL functions
//////////////////////////////////////////////////////////////////////////////////
void
    DrawMesh
    (
        MeshPoints*     Mesh
    )
{
    int ix;
    int iy;
    double normalX;
    double normalY;
    double normalZ;

    // Draw two triangles between sets of 4 points
    for( iy=gNumMeshPoints; iy>0; iy-- )
    {
        for( ix=1; ix<=gNumMeshPoints; ix++ )
        {
            CalcSurfaceNormal(
        Mesh->meshX[ix-1][iy-1], Mesh->meshY[ix-1][iy-1], Mesh->meshZ[ix-1][iy-1],
        Mesh->meshX[ix-1][iy], Mesh->meshY[ix-1][iy], Mesh->meshZ[ix-1][iy],
        Mesh->meshX[ix][iy-1], Mesh->meshY[ix][iy-1], Mesh->meshZ[ix][iy-1],
        &normalX, &normalY, &normalZ );

            glBegin( GL_TRIANGLES );

            glNormal3d( normalX, normalY, normalZ );
            glVertex3d(
                Mesh->meshX[ix-1][iy-1], 
                Mesh->meshY[ix-1][iy-1],
                Mesh->meshZ[ix-1][iy-1] );
            glVertex3d(
                Mesh->meshX[ix-1][iy],
                Mesh->meshY[ix-1][iy],
                Mesh->meshZ[ix-1][iy] );
            glVertex3d(
                Mesh->meshX[ix][iy-1], 
                Mesh->meshY[ix][iy-1], 
                Mesh->meshZ[ix][iy-1] );

            glNormal3d( normalX, normalY, normalZ );
            glVertex3d(
                Mesh->meshX[ix][iy-1],
                Mesh->meshY[ix][iy-1],
                Mesh->meshZ[ix][iy-1] );
            glVertex3d(
                Mesh->meshX[ix-1][iy], 
                Mesh->meshY[ix-1][iy], 
                Mesh->meshZ[ix-1][iy] );
            glVertex3d( 
                Mesh->meshX[ix][iy],
                Mesh->meshY[ix][iy],
                Mesh->meshZ[ix][iy] );

            glEnd( );
        }
    }
}

I wanted to put some lighting effects in. I used the following

glClearColor( 0.0f, 0.0f, 0.0f, 0.0f );
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
glEnable(GL_DEPTH_TEST); 
glEnable(GL_POLYGON_SMOOTH);
glEnable( GL_LIGHTING );
glEnable( GL_LIGHT0 );
glShadeModel( GL_SMOOTH );

I also rotated the view point using

glRotated( angle, 1.0, 0.5, 0.0 );
glRotated( angle/2, 0.0, 0.0, 0.1 );

Where angle is 240 degrees.

One thing I found disappointing in OpenGL is that although you are providing it triangles which are therefore flat planes, it does not calculate the reflection angle of the plane itself. This probably makes sense for efficiency, but it seemed annoying that I had to provide the normals for each triangle where in my opinion it already had all the information it needed.

The following function calculates a normal vector for a triangle in 3D space

//////////////////////////////////////////////////////////////////////////////////
//  CalcSurfaceNormal
//
//  Calculates the surface normal of the triangle
//////////////////////////////////////////////////////////////////////////////////
void
    CalcSurfaceNormal
    (
        double      x1,
        double      y1,
        double      z1,
        double      x2,
        double      y2,
        double      z2,
        double      x3,
        double      y3,
        double      z3,
        double*     pNormalX,
        double*     pNormalY,
        double*     pNormalZ
    )
{
    double  d1x;
    double  d1y;
    double  d1z;
    double  d2x;
    double  d2y;
    double  d2z;
    double  crossx;
    double  crossy;
    double  crossz;
    double  dist;

    d1x = x2 - x1;
    d1y = y2 - y1;
    d1z = z2 - z1;

    d2x = x3 - x2;
    d2y = y3 - y2;
    d2z = z3 - z3;

    crossx = d1y*d2z - d1z*d2y;
    crossy = d1y*d2x - d1x*d2z;
    crossz = d1x*d2y - d1y*d2x;

    dist = sqrt( crossx*crossx + crossy*crossy + crossz*crossz );

    *pNormalX = crossx / dist;
    *pNormalY = crossy / dist;
    *pNormalZ = crossz / dist;
}

The end result looked like this
OpenGlExample_Frame_04Now I wanted to animate it. I did this by changing the plot function to name take a 3rd parameter which is time (in seconds). So it now takes an X and Y coordinate and a time value and returns a Z (height) value.

//////////////////////////////////////////////////////////////////////////////////
//  RippleFunction
//
//  This function is a 3d plot function. It provides a Z value for given X and Y.
//  All values are between 0 and 1
//////////////////////////////////////////////////////////////////////////////////
double
    RippleFunction
    (
        double  x,
        double  y,
        double  seconds
    )
{
    double pi = 3.14159265358979;
    double z;
    double dist;
    double wave;
    double posX;
    double posY;
    double factor;

    // Get distance of point from centre (0.5, 0.5)
    posX = 0.5;
    posY = 0.5;
    dist = sqrt( (posX-x)*(posX-x) + (posY-y)*(posY-y) );

    wave = sin( 4*(2*pi) * dist - (seconds/1.0) ) * 0.4;
    z = (wave / 2.0) + 0.5;
    z *= (1.0-dist*1.2);

    // Now calculate a second wave with a moving centre and a low amplitude and
    // low frequency wave.
    // Get Distance of point from moving centre
    posX = 0.8 * (sin( (2*pi)*seconds))*0.01;
    posY = 0.8 * (sin( (4*pi)*seconds/2))*0.01;
    dist = sqrt( (posX-x)*(posX-x) + (posY-y)*(posY-y) );
    wave = sin( 2*(2*pi) * dist - (seconds/2.0) ) * 0.05;

    // Apply the second wave to first as a factor that varies over a sine wave
    factor = 1.0 - (cos( ((2*pi) * seconds/40) ) + 1.0) / 2.0;
    z += (wave * factor);

    return z;
}

This has two ripples with different frequencies, and one which moves the centre of its origin.  Additionally the second ripple is applied to the first one using a scale factor that is attached to a sine wave based on time. When the factor is 0 only the first wave is seen, which is a nice uniform ripple. As time progresses it becomes more distorted with the second wave and then eventually that fades off again.

An example of it with the second wave distorting it:

OpenGlExample_Frame_21

The end result as a QuickTime .mov file is available here

I had quite a lot of fun playing with this. Small changes in the plot function can create interesting results. I have put the program that generates the above wave online for download. It contains the LibOpenGL library which is the small wrapper library I wrote. It should be noted that this is just quick and simple experimental code. My expertise is not in OpenGL or graphics programming. I did this just for fun, and if other people find it handy that is good. However it is most unlikely that this is the “proper” way of doing this sort of graphics.

OpenGLExample.zip – C Source code using OpenGL to draw an animated ripple on a surface. Includes binaries for Windows, OSX, and Linux. This is free and unencumbered software released into the public domain.

Advertisement

3D surface using simple graphics

In yesterday’s article I wrote a simple 2D graphics library that provided lines and quadrangles as primitives. My motivation for writing it was so I could then write what I really wanted to do, which was some 3D drawing. In particular I wanted to draw a 3D surface where a function is provided that returns a Z (height) value for supplied X and Y values. I wanted to draw a ripple and view in 3D.

The first part was to create a framework that could call the function for determining Z value. I used the following prototype for my plot function.

typedef 
double
    (*PlotFunction3D)
    (
        double  X,
        double  Y
    );

This takes X and Y values between 0 and 1 and returns a Z value between 0 and 1. For my ripple function I wrote the following:

double
    RippleFunction
    (
        double  x,
        double  y
    )
{
    double pi = 3.14159265358979;
    double z;
    double dist;
    double wave;

    // Get distance of point from centre (0.5, 0.5)
    dist = sqrt( (0.5-x)*(0.5-x) + (0.5-y)*(0.5-y) );

    wave = sin( 4*(2*pi) * dist ) * 0.4;
    z = (wave / 2.0) + 0.5;

    if( dist > 0.5 ) 
    {
        z = 0.5;
    }

    return z;
}

This calculates the Z (height) value using a sine wave on the distance from the centre of the range (0.5, 0.5). The part at the end prevents the ripple continuing to the full edge and constrains it to a circle. This function is all that defines the surface, the rest of the program is generic and can draw any surface just by providing a different plot function. It is a lot of fun to experiment with different functions and see what results you can get.

By calling this function at various points over the X and Y range, a height value for a surface is found. This now needs to be displayed. To start with I wanted to draw a wire frame. By taking X and Y points at even intervals across the range 0 – 1, I calculated a matrix of Z values. To draw as a wire frame these Z values (Along with their X and Y) are used as vertices between line segments. A line segment is drawn between each set of adjacent points. However first their 3 dimensional coordinates must be converted into a 2D set for the screen.

I used a very simple method for converting the 3D points to 2D. The following code takes X,Y,Z values between 0 and 1 and returns 2D coordinates in the integer range representing pixels in the window.

SgPoint
    GetPointFrom3D
    (
        double  x,
        double  y,
        double  z
    )
{
    SgPoint point;
    double X;
    double Y;

    X = (x*0.8) + (y*0.4);
    Y = (y*0.5) + (z*0.6);

    point.X = (uint16_t) (X * (double)WINDOW_SIZE_X * 0.8);
    point.Y = WINDOW_SIZE_Y - (uint16_t) (Y * (double)WINDOW_SIZE_Y * 0.8);

    return point;
}

In my example I had a window size of 600 x 600 pixels, So the X,Y coordinate returned (SgPoint is a struct containing an x and y integer value) was in the range 0 – 599.

This is a crude 3D conversion, as it does not take perspective into consideration, nor does it allow you to change the viewing angle. This function can be replaced with a better function that would allow for these and the rest of the program could stay the same.

So now I have my matrix of vertices converted to 2D space, it is just a matter of drawing the lines

#define MESH_GRID_POINTS    50

typedef struct
{
    double mesh [MESH_GRID_POINTS+1][MESH_GRID_POINTS+1];
} MeshPoints;

void
    DrawPlotFunction3DWireMesh
    (
        PlotFunction3D  Function
    )
{
    MeshPoints* meshXCoord;
    MeshPoints* meshYCoord;
    MeshPoints* meshZCoord;
    int ix;
    int iy;

    SgPoint prevPoint;
    SgPoint point;

    meshXCoord = malloc( sizeof(MeshPoints) );
    meshYCoord = malloc( sizeof(MeshPoints) );
    meshZCoord = malloc( sizeof(MeshPoints) );

    // Calculate mesh coordinates
    CalculateMeshCoordinates( Function, meshXCoord, meshYCoord, meshZCoord );

    // Draw mesh lines along X
    for( ix=0; ix<=MESH_GRID_POINTS; ix+=1 )
    {
        for( iy=1; iy<=MESH_GRID_POINTS; iy+=1 )
        {
            // Draw line segment from previous point to this one
            prevPoint = GetPointFrom3D(
                meshXCoord->mesh[ix][iy-1],
                meshYCoord->mesh[ix][iy-1],
                meshZCoord->mesh[ix][iy-1] );
            point = GetPointFrom3D(
                meshXCoord->mesh[ix][iy],
                meshYCoord->mesh[ix][iy],
                meshZCoord->mesh[ix][iy] );

            SgDrawLine( prevPoint, point, SgRGB(0,0,0) );
        }
    }

    // Draw mesh lines along Y
    for( iy=0; iy<=MESH_GRID_POINTS; iy+=1 )
    {
        for( ix=1; ix<=MESH_GRID_POINTS; ix+=1 )
        {
            // Draw line segment from previous point to this one
            prevPoint = GetPointFrom3D(
                meshXCoord->mesh[ix-1][iy],
                meshYCoord->mesh[ix-1][iy],
                meshZCoord->mesh[ix-1][iy] );
            point = GetPointFrom3D(
                meshXCoord->mesh[ix][iy],
                meshYCoord->mesh[ix][iy],
                meshZCoord->mesh[ix][iy] );

            SgDrawLine( prevPoint, point, SgRGB(0,0,0) );
        }
    }

    free( meshXCoord );
    free( meshYCoord );
    free( meshZCoord );
}

And now the result:

ripple_wireframe.png

This looks interesting, but rather messy because its a wireframe you can see through it. I wanted to have something that looked like a surface rather than something made of chicken wire. Instead of drawing lines between the vertices I drew quadrangles between sets of 4 vertices. The quadrangles were drawn as filled white quadrangles with black edges. By drawing the quadrangles starting from the back row and working forward, the front quadrangles overwrite the ones behind. By putting a delay in the drawing loop you could watch the surface being drawing which looked rather interesting.

I changed the above routine to use the following to draw the quadrangles

    // Draw quadrangles between sets of 4 points
    for( iy=MESH_GRID_POINTS; iy>1; iy-=1 )
    {
        for( ix=1; ix<=MESH_GRID_POINTS; ix+=1 )
        {
            points[0] = GetPointFrom3D(
                meshXCoord->mesh[ix-1][iy-1],
                meshYCoord->mesh[ix-1][iy-1],
                meshZCoord->mesh[ix-1][iy-1] );
            points[1] = GetPointFrom3D(
                meshXCoord->mesh[ix][iy-1],
                meshYCoord->mesh[ix][iy-1],
                meshZCoord->mesh[ix][iy-1] );
            points[2] = GetPointFrom3D(
                meshXCoord->mesh[ix][iy],
                meshYCoord->mesh[ix][iy],
                meshZCoord->mesh[ix][iy] );
            points[3] = GetPointFrom3D(
                meshXCoord->mesh[ix-1][iy],
                meshYCoord->mesh[ix-1][iy],
                meshZCoord->mesh[ix-1][iy] );

            SgFillQuadrangle(
                points[0], points[1], points[2], points[3],
                SgRGB(255,255,255) );
            SgDrawQuadrangle(
                points[0], points[1], points[2], points[3],
                SgRGB(0,0,0) );
        }
    }

The result looks much better than before:
ripple_surface.pngBy having smaller quadrangles a smoother effect is given, but if they are too small then the the lines get drawn too close or on top of each other and you can’t make out a shape. By getting rid of the edges and instead using shading it is possible to use much smaller quadrangles, as long as the shading makes them different colours, otherwise it will be a solid colour and no shape will be seen.

Ideally the shading would be based on some lighting effect using the angle of the quadrangles to the viewer. However I found I got quite reasonable effect just by using the Z value to determine the shading colour for each quadrangle.

By changing the SgFillQuadrant line with

colour = SgRGB(50+(double)meshZCoord->mesh[ix][iy]*255,0,0);
SgFillQuadrangle( points[0], points[1], points[2], points[3], colour );

and removing the SgDrawQuadrangle the surface could be quite nicely rendered using a much smaller quadrangles. I increased the number from 50 per row to 500.

The now for the final result:

ripple_solid.png

Finally, if you would like the source code to play around with it is available here

3dSurface.zip – Contains source code for the above examples along with LibSimpleGraphics (0.1.0 non stable version). As always this is free and unencumbered software released into the public domain.

I am planning on finishing the LibSimpleGraphics library sometime soon, at which point I’ll put it on GitHub.

Simple Graphics

SimpleGraphics.zip – Public domain C source code for SimpleGraphics library.

When I first started programming in DOS, the languages I used (Modula-2, and C) had basic graphics capabilities. My first C compiler was Microsoft Quick C, it had a graphics library “graph.h”. This provided a few basic primitives for drawing and changing the screen mode into graphics mode. As DOS was a single threaded operating system things were pretty easy. In your main function you could set the video mode to graphics and then draw some shapes with a few lines of code. There were no event loops and callbacks to worry about, and the graphics primitives were very simple.

With Windows (and other modern OSes) things become more difficult and easier at the same time. Doing complex things is easier because there are far more capabilities provided by the system. On the other hand however doing simple things takes longer to setup. With Quick C I could set video mode with one call and then draw a line with another call and my simple program was done. To write a Windows program that just draws one line takes a lot more setup.

I enjoyed playing around with the graphics functions back in the DOS days, and I sometimes feel nostalgic and want to relive some of those moments. I had a look around on the Internet for a very basic graphic library that was cross platform and did not require many dependencies. I wanted to be able to write a simple program that drew shapes with only a few lines of code. Unfortunately I could not find what I was looking for on the Internet. Typically the libraries out there are large and can do all sorts of fancy things. Also I did not find any that had a license I like (I like Public Domain). So I set about writing my own one.

I had the following goals for the library

  1. Must be contained within one single C file and one corresponding H file
  2. Must not required extra modules that do not come standard with a system
  3. Must work for Windows, OSX, and Linux
  4. Needs to provide basic drawing primitives: Lines, simple polygons both filled and non-filled.
  5. Public Domain!

Point 5 is pretty easy, I wrote it so I can do what I want with it and I only like public domain.

Drawing graphics in any system is not my speciality, in fact I have never done it in Windows nor OSX nor Linux before! For Windows I used GDI to do the drawing. I have written Win32 GUI apps before so am familiar with the windows message loop. I found OSX to be difficult because I wanted to write it only using C, and OSX likes to use Objective C as its main interfaces. However, OSX comes with OpenGL and GLUT standard, these have C interfaces. So I wrote the OSX version using OpenGL which I have never used before. I choose to use OpenGL for Linux too because I didn’t want to have to do a third implementation.

OSX has a limitation I found out which is the graphics calls all have to come from the main thread. This messed up my initial implementation design. I wanted the graphics library to create a thread to perform all the graphics functions in the background. So I redesigned it so that instead the main “run” function creates a thread for the main application to continue its work in, and it takes over the main thread. Its not as I would prefer it, and unnecessary for Windows, but I wanted it to be consistent across platforms.

I am quite pleased with the end result, not that it quite is an end result yet. It has been a lot of fun writing it, but the main reason I did it is because of the next thing I want to work on which needs this as base. I am releasing the source code of the library, but with a warning that it should not be consider complete or even stable. As I use it more I will fix it up more, but right now it works for the examples, but it has not been tested particularly well. It doesn’t really handle the window being closed particular well for example.

The following code is an example program which shows how simple it is to use.

////////////////////////////////////////////////////////////////////////////////
//  SimpleGraphicsTest
//
//  Test program for SimpleGraphics
//
//  This is free and unencumbered software released into the public domain
//  July 2013 waterjuice.org
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
//  IMPORTS
////////////////////////////////////////////////////////////////////////////////

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
#include "LibSimpleGraphics.h"

////////////////////////////////////////////////////////////////////////////////
//  FUNCTIONS
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
//  GraphicsMain
//
//  Graphics function
////////////////////////////////////////////////////////////////////////////////
void
    GraphicsMain
    (
        void*   Unused
    )
{
    char buffer [100];
    char* ptr;
    (void) Unused;

    SgFillRectangle( SgXY(100,100), SgXY(200, 200), SgRGB(250, 200, 0) );
    SgDrawRectangle( SgXY(100,100), SgXY(200, 200), SgRGB(0, 0, 0) );

    SgFillRectangle( SgXY(130, 130), SgXY(135, 135), SgRGB(100, 100, 240) );
    SgDrawRectangle( SgXY(130, 130), SgXY(135, 135), SgRGB(0, 0, 0) );

    SgFillRectangle( SgXY(165, 130), SgXY(170, 135), SgRGB(100, 100, 240) );
    SgDrawRectangle( SgXY(165, 130), SgXY(170, 135), SgRGB(0, 0, 0) );

    SgDrawLine( SgXY(120, 160), SgXY(130, 170), SgRGB(0, 0, 0) );
    SgDrawLine( SgXY(130, 170), SgXY(170, 170), SgRGB(0, 0, 0) );
    SgDrawLine( SgXY(170, 170), SgXY(180, 160), SgRGB(0, 0, 0) );

    // Wait for user to press enter before returning and closing window
    ptr = fgets( buffer, sizeof(buffer), stdin );
    (void)ptr;
}

////////////////////////////////////////////////////////////////////////////////
//  main
//
//  Entry point
////////////////////////////////////////////////////////////////////////////////
int
    main
    (
        void
    )
{
    SimpleGraphicsRun( 300, 300, "Hello World", GraphicsMain, 0 );

    return 0;
}

The function SimpleGraphicsRun needs to be run from the main thread (because of OSX requirements). The first 2 parameters are the window size, the third is the window title, the fourth is the function where execution will continue, the final parameter is a context pointer that is passed to the function specified before. SimpleGraphicsRun will create the window and create a new thread which is passed to the specified function. When that function returns the window will be closed.

The results of the above example are:

Example1_Windows-280x300.png
Windows

Example1_OSX-281x300.png

OSX

Example1_Linux-275x300.png

Linux (Ubuntu)

The results look the same in all three platforms. Goal achieved!

A fancier example:

example2

With this example I put delays into the drawing so that it looked more interesting.

SimpleGraphics.zip – This has the C source code for the SimpleGraphics library and the example code for the above two examples. SimpleGraphics is a cross platform very basic graphics library using GDI and OpenGL. The zip file also contains compiled binaries for Windows, OSX, and Linux. This is free and unencumbered software released into the public domain.

Be careful using MOD with random numbers

The C function rand is terrible source of random numbers for almost any application, just don’t use it ever. I’m particular fond of RC4 as a source as it is easy to implement and takes very little code. A simple method of generating random numbers with RC4 is to first gather some entropy values. These are values that should be different each time you gather them, and between computers. The nice property about entropy is that it only increases. So as long as you mix in some good high entropy values you can’t “dilute” it by mixing in low entropy ones (unless you do something stupid with the way you mix them). If you have less than 256 bytes of entropy values and you want to keep code size down to a minimum then you can feed those values in as the key to the RC4 stream. However it is better and more flexible to use a hash function on the entropy values and use the resulting hash as the key to the RC4 stream. High precision timers are a good source of entropy, as are various input sources such as mouse position, memory usage, process lists etc. Just keep on feeding more entropy values into the hash function. As long as you have some pretty good values in there you should be okay. For extra points run the hash function multiple times before using the final value as the key (ie hash the hash and repeat). This makes it much more difficult for someone to determine the initial state of the RC4 stream.

Now you have an RC4 stream that has been keyed by a random value. Remember to throw away the first 256 bytes and now you have a very good source of random bytes. RC4 produces one byte per iteration. This makes it very easy to get random values of bytes, or larger words. If you want a 32 bit random number, just output four bytes, you don’t even have to worry about endianness.

Sometimes, however, you need a range of random values that is not a multiple of bytes. If for example you need random numbers in the range 0-31, this is easily produced. For each value take an output byte from RC4 and then chop off the top 3 bits. This can be easily done with an AND operation (with value 0x1f), or alternatively a MOD 32 operation.

newValue = randValue & 0x1f;
newValue = randValue % 32;

The new value is now a random value in the range 0-31 and still has a nice flat distribution. This is because each bit in the RC4 stream has a random distribution and we can take any 5 bits out of the 8 bit output. Another (more complicated) method would be to treat the RC4 as a bitstream and take 5 bits at a time. This requires more both programatically and computationally and provides no advantage, its not as if you are “wasting” the 3 bits produced by the first method and this is more efficient!.

While in the above example using MOD is equivalent to using the AND function, it can give the wrong impression that you can use the MOD operation more flexibly to get ranges that are not a whole number of bits. For example if you want the range of values to be 0-29, it looks like this could easily be produced by using the MOD function with a value 30. Don’t do this, not ever. The problem is that the MOD function is a mapping of the 256 values into 30 values. 256 does not evenly divide into 30.

The following original 8 bit values become a 0 when MOD 30 is applied: 0, 30, 60, 90, 120, 150, 180, 210, 240. That is 9 original values map to a 0. Similarly there are 9 values that map to 1 (1, 31, 61, 91, 121, 151, 181, 211, 241). So far so good, but look what happens for the values that map to 16: 16, 46, 76, 106, 136, 166, 196, 226. This is only 8 values. So in the final output the values from 0-15 have 9 original input values, whereas the values 16-29 have 8 original input values. This is not a flat distribution, instead of each value 0-29 having a probability for selection of 3.3333%, half of them have a probability of 3.5156% and the other half have a lower probability of 3.125%. This is bad for any application, and tragic for encryption.

There is fortunately a very simple solution which will produce a flat distribution of any desired range. First truncate the value to the next whole number of bits for the range wanted. In the case of the range 0-29 this is 32 (5 bits). If the value is larger than 8 bits, then produce larger values by outputting multiple bytes at a time, filling the word, and then mask the required bits. Next check to see if the value is within the desired range (eg 0-29). If it is then output it, if it is not, then throw it away and repeat the process until one is found within the range. This will produce a flat distribution of values. The function will take a variable amount of time to process as it may have to repeat several times before it gets a value within the range, however because we have truncated the bits to start with, there will always be more than a 50% chance of a value being in the range desired on each try, so it shouldn’t have to repeat much. You could skip the first step, but then you would be throwing away a lot more values and therefore repeating a lot more, but the output will still be just as good.