Archive for March, 2010

GLUT Geometric Shapes


This is a sample app that demonstrates GLUT geometric shapes. It allows you to go through all the shapes in wireframe and solid modes and lets you interact with the shape by rotating it, resizing it and changing its color.

See this document for a complete explanation of the functions that draw those shapes. Source code is available here. If you have any issues compiling or running the app, check out this section for details about compiling and running an OpenGL app that uses the GLUT library.

SQL Aggregates in C


For fun, I would like to implement some of the SQL aggregates in C: SUM (sum), AVG (average), MIN (minimum), MAX (maximum), STDEV (standard deviation), VAR (variance).

To do this in C, I’ll use functions with variable number of arguments instead of a function with an array and a count of the elements in that array. To do this, I need to have a special value for the last parameter in the variable list of arguments to know when to stop getting arguments in the list. For that, I’m going to use the INT_MIN macro in the <climits> C library. For example, to get the average of the numbers 6, 3, and 19, the call would look like AVG(6, 3, 19, INT_MIN).

SUM

Implementing this in C is lame, but I’ll use it as the starting point before getting to the other functions. I would definitely prefer to write 1 + 2 + 3 in C instead of SUM(1, 2, 3, INT_MIN).

Definition

int sum (int first, ...)
{
    register int i = first;
    int sum = 0;
   
    //  declare a variable argument list
    va_list arg_list;
   
    //  initialize the arglist
    va_start (arg_list, first);
   
    //  Sum all arguments
    while(i != INT_MIN)
    {
        sum += i;
        i = va_arg (arg_list, int);
    }
   
    //  End the argument list
    va_end(arg_list);
   
    return sum;
}

Usage

printf ("Sum of (1, 2, 3, 4, 5) = %d\n", sum (1, 2, 3 , 4, 5, INT_MIN));

Output

15

AVG

Instead of writing something like (1+2+3+4)/4 or (4 + 3 + 6 + 1 + 5 + 11 + 19 + 25 + 111 + 55 + 32 + 57)/ 12, I’d rather write AVG(1, 2, 3, 4, INT_MIN) or AVG(4, 3, 6, 1, 5, 11, 19, 25, 111, 55 , 32, 57, INT_MIN) without having to count the number of numbers I’m calculating the average for.

Definition

double avg (int first, ...)
{
    register int i = first;
    int sum = 0, count = 0;
   
    va_list arg_list;
    va_start (arg_list, first);
   
    //  sum and count all arguments
    while(i != INT_MIN)
    {
        sum += i;
        count++;
        i = va_arg (arg_list, int);
    }
   
    va_end(arg_list);
   
    return (double) sum / count;
}

Usage

printf ("Average of (1, 2, 3, 4, 5) = %.2f\n", avg (1, 2, 3 , 4, 5, INT_MIN));

Output

3.00

MIN

Instead of implementing MIN by passing an array and the count of numbers in that array , I’d rather just pass all the numbers to the function without having to worry about creating an array and counting the number of elements inside it.

Definition

int min (int first, ...)
{
    register int i = first;
    int min = first;
   
    va_list arg_list;
    va_start(arg_list, first);
   
    //  Search for any other argument that is less than the first
    //  If you find one, then assign it to min
    while(i != INT_MIN)
    {
        if(i < min)
            min = i;

        i = va_arg(arg_list, int);
    }
   
    va_end(arg_list);
   
    return min;
}

Usage

printf ("Minimum of (10, 23, 3, 41, 15) = %d\n", min (10, 23, 3, 41, 15, INT_MIN));

Output

3

MAX

Gets the maximum number in a set.

Definition

int max (int first, ...)
{
    register int i = first;
    int max = first;
   
    va_list arg_list;
    va_start(arg_list, first);
   
    //  Search for any other argument that is greater than the first
    //  If you find one, then assign it to max
    while(i != INT_MIN)
    {
        if(i > max)
            max = i;

        i = va_arg(arg_list, int);
    }
   
    va_end(arg_list);
   
    return max;
}

Usage

printf ("Maximum of (10, 23, 3, 41, 15) = %d\n", max (10, 23, 3, 41, 15, INT_MIN));

Output

41

STDEV

Calculates the standard deviation for a set of numbers.

Definition

double stdev (int first, ...)
{
    register int i = first;
    int count = 0;
    int sum = 0;
    double mean = 0;
    double deviation = 0;
    va_list arg_list;

    //  Calculate the mean (average)
    va_start(arg_list, first);
   
    while(i != INT_MIN)
    {
        sum += i;
        count++;
        i = va_arg (arg_list, int);
    }
   
    va_end(arg_list);
    mean = (float) sum / count;

    //  Calculate the standard deviation
    i = first;
    va_start(arg_list, first);
   
    while(i != INT_MIN)
    {
        deviation += pow((i - mean), 2);
        i = va_arg (arg_list, int);
    }

    deviation /= count;
    deviation = sqrt(deviation);

    va_end(arg_list);
   
    return deviation;
}

Usage

printf ("Standard Deviation of (2, 4, 4, 4, 5, 5, 7, 9) = %.2f\n", stdev (2, 4, 4, 4, 5, 5, 7, 9, INT_MIN));

Output

2.00

VAR

Calculates the variance for a set of numbers.

Definition

double var (int first, ...)
{
    register int i = first;
    int count = 0;
    int sum = 0;
    double mean = 0;
    double variance = 0;
    va_list arg_list;

    //  Calculate the mean (average)
    va_start(arg_list, first);
   
    while(i != INT_MIN)
    {
        sum += i;
        count++;
        i = va_arg (arg_list, int);
    }
   
    va_end(arg_list);
    mean = (float) sum / count;

    //  Calculate the variance
    i = first;
    va_start(arg_list, first);
   
    while(i != INT_MIN)
    {
        variance += pow((i - mean), 2);
        i = va_arg (arg_list, int);
    }

    variance /= (count - 1);

    va_end(arg_list);
   
    return variance;
}

Usage

printf ("Variance of (1, 2, 3, 4, 5, 6) = %.2f\n", var (1, 2, 3, 4, 5, 6, INT_MIN));

Output

3.50


Full source code is available here.

Visual Studio 2010 & SharePoint Server Code


You have downloaded Visual Studio 2010 RC and SharePoint 2010 Beta and now you’d like to use VS to develop on top of SharePoint. You can use one of the following approaches:

Approach Extension Usage VS Project Type
Solution Wsp Add functionality on top of SharePoint. Anything under the SharePoint template node (Web Part, List Definition, Content Type, etc…)
Client Application Exe, dll, xap End User Windows\Silverlight apps, Assemblies Anything that uses SharePoint Client OM, Web Services, RPCs
Server Application Exe, dll Admin tools Anything that uses SharePoint Server OM (Ex: referencing Microsoft.SharePoint.dll)

The point behind this blog post is to ensure that you have the right Visual Studio 2010 settings for compiling and running SharePoint Server applications or assemblies.

Compile Issue

Warning 1 The referenced assembly “Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c, processorArchitecture=MSIL” could not be resolved because it has a dependency on “System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a” which is not in the currently targeted framework “.NETFramework,Version=v4.0,Profile=Client”. Please remove references to assemblies not in the targeted framework or consider retargeting your project.

Resolution

SharePoint 2010 is built on top of .Net Framework 3.5. So make sure you have it as your targeted framework in VS. Go to project properties and change the target framework to “.Net Framework 3.5″.
Run Issue
The Web application at <url> could not be found. Verify that you have typed the URL correctly. If the URL should be serving existing content, the system administrator may need to add a new request URL mapping to the intended application.
Resolution
You have an x64 version of SharePoint Server installed, but VS 2010 is building your code as x86. So go to project properties \ Build and change platform target from x86 to x64.

OpenGL String (printw)


There are many ways for displaying text in OpenGL. In this post, I’ll use the glutBitmapCharacter function to draw characters, and then will extend it to a more generic function (printw), which will make drawing a string in OpenGL as simple as using printf.

First, I will start by defining the font to be used by the glutBitmapCharacter function. I will choose a 24-point proportional spaced Times Roman font as shown below:

//  A pointer to a font style..
//  Fonts supported by GLUT are: GLUT_BITMAP_8_BY_13,
//  GLUT_BITMAP_9_BY_15, GLUT_BITMAP_TIMES_ROMAN_10,
//  GLUT_BITMAP_TIMES_ROMAN_24, GLUT_BITMAP_HELVETICA_10,
//  GLUT_BITMAP_HELVETICA_12, and GLUT_BITMAP_HELVETICA_18.
GLvoid *font_style = GLUT_BITMAP_TIMES_ROMAN_24;

To draw a character, simply define the raster position using glRasterPos3f (x, y, z), then draw it using glutBitmapCharacter(font_style, character). To extend this to drawing a string at certain coordinates, loop over each character in the string and draw it with glutBitmapCharacter. The additional logic that goes below is in making this as pretty as printf.

This can be done by using C’s va_list type, which is C’s approach to defining functions with variables number of arguments.

  • In the function prototype, place ellipsis (…) as the last argument
  • Define a variable argument list: va_list args;
  • Call va_start on the args list and the first real argument in the function prototype preceding the ellipsis: va_start(args, format);
  • Use _vscprintf to get the number of characters that would be generated if the string pointed to by the list of arguments was printed using the specified format
  • Allocate memory for a string with the specified number of characters
  • Call vsprintf_s to build the string we want from the list of arguments
  • Call va_end to end the use of the variables argument list
  • Draw our beautified string
  • Free allocated memory

Function implementation with full comments shown below:

//-------------------------------------------------------------------------
//  Draws a string at the specified coordinates.
//-------------------------------------------------------------------------
void printw (float x, float y, float z, char* format, ...)
{
    va_list args;   //  Variable argument list
    int len;        // String length
    int i;          //  Iterator
    char * text;    // Text

    //  Initialize a variable argument list
    va_start(args, format);

    //  Return the number of characters in the string referenced the list of arguments.
    // _vscprintf doesn't count terminating '\0' (that's why +1)
    len = _vscprintf(format, args) + 1;

    //  Allocate memory for a string of the specified size
    text = malloc(len * sizeof(char));

    //  Write formatted output using a pointer to the list of arguments
    vsprintf_s(text, len, format, args);

    //  End using variable argument list
    va_end(args);

    //  Specify the raster position for pixel operations.
    glRasterPos3f (x, y, z);

    //  Draw the characters one by one
    for (i = 0; text[i] != '\0'; i++)
    glutBitmapCharacter(font_style, text[i]);

    //  Free the allocated memory for the string
    free(text);
}

Now that printw is defined, using it is similar to printf:

printf(         "char: %c, decimal: %d, float: %f, string: %s", 'X', 1618, 1.618, "text");
printw(x, y, z, "char: %c, decimal: %d, float: %f, string: %s", 'X', 1618, 1.618, "text");

Libraries to include before copying the function ;)

#include <stdio.h>    //  Standard Input\Output C Library
#include <stdarg.h>   //  To use functions with variables arguments
#include <stdlib.h>   //  for malloc
#include <gl/glut.h>  //  Include GLUT, OpenGL, and GLU libraries

Here is a sample source code that contains the printw function. If you have any issues compiling or running the app, check out this section for details about compiling and running an OpenGL app that uses the GLUT library. Below is a screen shot of the demo app:

OpenGL Oval


Knowing that OpenGL only comes with commands that draw simple geometric primitives such as points, lines and polygons (see OpenGL Geometric Shapes), it would be nice to extend over these and draw more complex structures, such as those supported by the Java AWT library. In this post, I’ll show the OpenGL implementation of the drawOval, fillOval, drawArc, fillArc methods of the Java Graphics class.

Before we get to drawing an oval or an arc, let’s first see how to draw a circle. We can use points, lines or polygons. To draw the outline of the circle, we can place points around the circle, then connect the consecutive points using lines. The more points we have, the more lines we would draw and the more realistic the circle would look like. Below are samples of a circle drawn using 3, 4, 5, 10 and 50 segments.

So if we figure out how to draw the points on the circle’s perimeter, we’ll be able to connect those points with lines and thus have a circle. To draw a point, all we need to know is its x and y coördinates (assuming z = 0). Relative to the center of the circle , the coördinates of a point at the circle’s perimiter are calculated as follows (rule in trigonometry):

x = r * cos θ

y = r * sin θ

where r is the radius and θ (theta) is the angle between the x-axis and the radius that connects the point to the center. So to draw a point, we need to know its angle θ. The angle θ of each point will depend on how many points we’ll use to draw the circle. As we know, the angle all around the circle is 360 degrees, which is equivalent to 2Π radians. If we are to use 10 points to draw the circle, the angle increment between each point and the next will be 2Π / 10. Thus, θ of point 1 is  0, θ of point 2 is 2Π / 10, θ of point 3 is 4Π / 10, …, and θ of point 10 is 18Π / 10. So here is how we can get the coördinates of all the points of a circle with radius r and segments n.

δ = 2Π / n;
for (θ = 0; θ< 2Π; θ+= δ)
{
x = r * cos (θ);
y = r * sin (θ);
}

To draw the circle from those points, we should use the GL_LINE_LOOP OpenGL mode, which will draw a connected group of line segments from the first vertex to the last, then back to the first. That’s how we draw the circle. To implement the more generic case of drawing an oval, all we have to do is make the trigonometric rule for the coordinates of a point more generic. In order to be able to derive such a rule, we should imagine a bounding rectangle around the oval. In the case of a circle, that bounding rectangle is a square with side s equal to the diameter of the circle, which is 2 * r. So r is equal to s / 2.

x = s/2 * cos θ
y = s/2 * sin θ

The bounding rectangle has a width w and height h. A bit of intuition leads us to the rule that defines the coordinates of a point on an oval:

x = w/2 * cos θ
y = h/2 * sin θ

The full source code of the drawOval function is shown below:

//-------------------------------------------------------------------------
//  Draws an oval centered at (x_center, y_center)
//
// The oval is bound inside a rectangle whose width is w
// and height is h.
//
// n represents the number of line segments used to draw the oval.
//-------------------------------------------------------------------------
void drawOval (float x_center, float y_center, float w, float h, int n)
{
    float theta, angle_increment;
    float x, y;

    if (n <= 0)
        n = 1;

    angle_increment = PI_2 / n;
    glPushMatrix ();

    //  center the oval at x_center, y_center
    glTranslatef (x_center, y_center, 0);

    //  draw the oval using line segments
    glBegin (GL_LINE_LOOP);

    for (theta = 0.0f; theta < PI_2; theta += angle_increment)
    {
        x = w/2 * cos (theta);
        y = h/2 * sin (theta);

        //  Color the vertices!
        if (color[currentShape])
            glColor3f (x, y, x*y);

        glVertex2f (x, y);
    }

    glEnd ();
    glPopMatrix ();
}

To fill the circle, instead of using lines, we need to use polygons. The best mode to use here is the GL_TRIANGLE_FAN, which draws a connected group of triangles. One triangle is defined for each vertex presented after the first two vertices.

To draw or fill an arc, we use the same rules for drawing an oval, except that we control the angles θ of the points based on the start angle and the arc angle.

δ = 2Π / n;
for (θ = startAngle; θ< startAngle + arcAngle; θ+= δ)
{
x = w/2 * cos (θ);
y = h/2 * sin (θ);
}

Here is the full source code of all the 4 functions. You can also use this demo exe to play around with shapes, segments, color, width and height… If you have any issues compiling or running the app, check out this section for details about compiling and running an OpenGL app that uses the GLUT library. Below is a screenshot from the demo app showing a circle with every vertex colored based on its coordinates. When you run the app, press the ‘h’ key for help on how to use it.

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: