SharePoint Foundation 2010 on Windows 7


This MSDN article describes in detail how to install SharePoint Foundation 2010 for development purposes on Windows Vista, Windows 7 and Windows Server 2008. The purpose of this post is to focus on the SharePoint installation on Window 7 only and clear out all the details for the other operating systems.

  1. Download SharePoint Foundation 2010 x64 for free. Note that there is no x86 version of SharePoint Server, so don’t bother setting it up if you have a 32-bit machine.
  2. Create a new folder “C:\SharePointFiles” and copy “SharePointFoundation.exe” to it.
  3. Start command prompt, change directory to C:\SharePointFiles and run the following command to extract the “SharePointFoundation.exe” to C:\SharePointFiles
    SharePointFoundation.exe /extract:C:\SharePointFiles
  4. Open C:\SharePointFiles\files\Setup\config.xml, add a new <Setting> tag under the <Configuration> element, then save the file. Make sure you copy the below element as is since all of the text in the configuration file is case-sensitive.
    <Setting Id=”AllowWindowsClientInstall” Value=”True”/>
  5. Install the following Prerequisites:
  6. Enable the required windows features by running this batch file: http://cid-e38f9fc6490b29d9.skydrive.live.com/self.aspx/Public/Scripts/EnableSPWinFeatures.bat
  7. Restart your computer to complete the changes that you made to Windows Features.
  8. Install SharePoint 2010
    • Run Setup.exe under C:\SharePointFiles
    • Select standalone (Windows 7 can’t be used for production deployments of SharePoint 2010 and it’s recommended that you use Standalone only)
    • After the installation is complete, you will be prompted to start the SharePoint Products and Technologies Configuration Wizard.
      InstallSP
  9. After a SharePoint solution (.wsp file) is deployed, it recycles the application pool. To improve the initial page load times, set the optimizeCompilations property of the <compilation> tag in your web.config file (C:\inetpub\wwwroot\wss\VirtualDirectories\80\web.config) to true.
    <compilation optimizeCompilations=”true”>

SharePoint Designer 2010 is also free and can help you better design your SharePoint site(s). You can download it here.

OpenGL Camera


The concept of a camera in a Graphics application is simple. Just imagine that what you see is the view of the camera. So adjusting the camera lens or moving\rotating it should affect your view. In the base OpenGL library, there is no concept of a camera. However, it can be simulated by applying the inverse of the camera transformation on the objects\pixels in the scene. Instead of having to build the matrix and invert it ourselves, the GLU library provides the gluLookAt function, which would do the work for us. This function takes as a parameter the location (x, y, z) of the camera\eye, the location (x, y, z) of the point to look at, and the coordinates (x, y, z) of the Up vector (rotation of the camera around its origin). Note that this function should be called on the ModelView matrix before any transformation is applied on objects in the scene. Avoid calling this function on the Projection matrix (more details here).

Given the description above, after specifying the camera attributes with a call to gluLookAt then drawing the objects in the scene, one would expect to see the objects in the scene based on the view of the camera. This expectation is completely valid, however, there is one more variable that affects what we see: the viewing volume (similar to real-world camera focus), which is controlled by calls on the projection matrix. Try to imagine what you’ll see if you run the code below:

GLdouble eyeX = 0, eyeY = 0, eyeZ = 2;
GLdouble centerX = 0, centerY = 0, centerZ = 0;
GLdouble upX = 0, upY = 1, pZ = 0;

void display()
{
    //  Set up camera properties
    glMatrixMode (GL_MODELVIEW);
    gluLookAt (eyeX, eyeY, eyeZ,
               centerX, centerY, centerZ,
               upX, upY, upZ);

    //  Draw an Object at the origin
    drawObject ();
}

The answer to the question above is that you’ll see nothing! The reason is that eyeZ = 2, the viewing volume is glOrtho(-1, 1, -1, 1, -1, 1) by default, and the object is drawn at the origin. Here is a visual demonstration using Nate Robin’s interactive OpenGL tutorial (projection.exe).

If we change zFar (last parameter of glOrtho) of projection to 3 or if we change eyeZ of the camera to 0.5, then we’ll be able to see the object.

To summarize all of this, I am taking advantage of one of the slides of the Siggraph OpenGL tutorial.

If you’ve used one of those 3D modeling software out there (like 3ds Max, Maya, etc…), then you’ve certainly seen multiple orthogonal views (Front, Back, Top, Bottom, Left, Right) of your 3D drawing. Here is a screenshot from 3ds Max.

Using the OpenGL camera, I’m going to create an OpenGL app that has 6 sub-windows each displaying the same object, but from a different camera angle. The world coordinates will be glOrtho(-1, 1, -1, 1, -2, 2) and the views will be: Front, Back, Top, Bottom, Left, and Right. The parameters that are going to be passed to gluLookAt will vary based on the view:

The program looks as follows.

Note that you can use the left mouse button to rotate the object, right mouse button to translate the object, and middle mouse button to scale it. Also, the ‘r’ key will reset the object transformations in the scene. You can find the full source code 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.

GLUT Menu World


This post demonstrates how to create a GLUT menu and add to it sub-menus and menu items.

In the above sample app, clicking on a menu item in the popup menu will log that menu item’s ID to the console window. Below is the function setupMenus() that creates the main menu and adds to it all the sub-menus and menu items. You can change it based on your needs then call it in the init() method.

//-------------------------------------------------------------------------
//  Set up the GLUT Menus.
//-------------------------------------------------------------------------
void setupMenus ()
{
    int subMenuCount;  //  Count of sub menus
    int menuItemCount; //  Count of menu items in a submenu
    int *menuIds;      //  Submenu IDs
    char str[256];     //  The string of the current menu item
    int i, j;          //  Iterators

    //  Generate a random value for submenu count
    subMenuCount = rand() % 20;

    //  Allocate memory for the submenu IDs
    menuIds = (int *) xmalloc (subMenuCount * sizeof (int));

    //  Create all the sub menus
    for (i = 0; i < subMenuCount; i++)
        menuIds[i] = glutCreateMenu (showMenuItem);

    for (i = 1; i < subMenuCount; i++)
    {
        //  Set sub menu string
        sprintf (str, "SubMenu %d", i);

        //  Add the current submenu to previous submenu
        glutSetMenu (menuIds[i-1]);
        glutAddSubMenu (str, menuIds[i]);

        //  New menu item count for the new submenu
        menuItemCount = rand () % 20;

        //  Add menu items to the current submenu
        for (j = 1; j < menuItemCount; j++)
        {
            sprintf (str, "Menu Item %d", j);
            glutAddMenuEntry (str, j);
        }
    }

    //  Set main menu as the current menu
    glutSetMenu (menuIds[0]);

    //  Attach the menu to the RMB
    glutAttachMenu(GLUT_RIGHT_BUTTON);
}

Major GLUT functions briefly explained:

  • glutCreateMenu creates the main menu or sub-menu and returns its ID. It takes as a parameter a pointer to a function with the signature void func (int menuItemId). This function is called every time the  user clicks a menu item in the menu and the parameter menuItemId passed to it represents the id of the menu item.
  • glutAddSubMenu adds another menu to current menu.
  • glutAddMenuEntry adds a menu item to the current menu.
  • glutSetMenu sets the current menu. So when we call glutAddSubMenu or glutAddMenuEntry, they get added to the current menu.
  • glutAttachMenu(GLUT_RIGHT_BUTTON) attaches the “current” menu to the right click button. So when you right click the mouse, the popup menu will show up.

This is the function that we are passing to glutCreateMenu in our sample app. Every time the user clicks on a menu item, this function is called and it will simply display the menu item id on the console window.

//-------------------------------------------------------------------------
//  Displays the menu item id on the console window
//-------------------------------------------------------------------------
void showMenuItem (int val)
{
    printf ("Menu Item: %d\n", val);
}

Download the full source code here.

Dynamic Three Dimensional Arrays in C\C++\C#\Java


If you come from a Java or C# perspective and want to create a multi-dimensional array in C or C++, you’ll soon figure out that multi-dimensional array allocation in C\C++ is not as simple, plus you’ll have to worry about deallocation since there is no garbage collector to do the work for you. Below I’ll show four different sample codes showing how to work with a three dimensional array in Java, C#, C++ and C, respectively.

Java 3D Array

In Java, creating a 3-dimensional array is as simple as saying

int[][][] array3D = new int[x][y][z];

You can then access the elements of the 3-dimensional array at array3D[i][j][k].

Sample Code

public static void main(String[] args)
{
    //  Array 3 Dimensions
    int x = 4, y = 5, z = 6;

    //  Array Iterators
    int i, j, k;

    //  Allocate 3D Array
    int[][][] array3D = new int[x][y][z];

    //  Access array elements
    for (i = 0; i < x; i++)
    {
        System.out.println(i);

        for (j = 0; j < y; j++)
        {
            System.out.println();

            for (k = 0; k < z; k++)
            {
                array3D[i][j][k] = (i * y * z) + (j * z) + k;
                System.out.print("\t" + array3D[i][j][k]);
            }
        }

        System.out.println('\n');
    }
}

C# 3D Array

In C#, the concept is almost the same as in Java. However, C# makes the distinction between jagged and multi-dimensional arrays. Elements of a multi-dimensional array are stored in a contiguous block in memory while elements of a jagged array are not. Java arrays are actually jagged arrays, while C# supports both and allows you to choose which one you want based on the syntax of your code. Note that multi-dimensional arrays are better (in most cases) than jagged arrays, and that is considered a minus point for Java.

Using jagged arrays in C# is not as simple as in Java. It’s almost like the way we would implement it in C++.

int[][] jaggedArray = new int[2][];
jaggedArray[0] = new int[4];
jaggedArray[1] = new int[3];

However, multi-dimensional arrays in C# are very simply to use. You can create a 3 dimensional array as follows

int[,,] array3D = new int[x, y, z];

then access its elements at array3D[i][j][k].

Sample Code

static void Main(string[] args)
{
    //  Array 3 Dimensions
    int x = 4, y = 5, z = 6;

    //  Array Iterators
    int i, j, k;

    //  Allocate 3D Array
    int[,,] array3D = new int[x, y, z];

    //  Access array elements
    for (i = 0; i < x; i++)
    {
        Console.WriteLine(i);

        for (j = 0; j < y; j++)
        {
            Console.WriteLine();

            for (k = 0; k < z; k++)
            {
                array3D[i, j, k] = (i * y * z) + (j * z) + k;
                Console.Write("\t{0}", array3D[i, j, k]);
            }
        }

        Console.WriteLine('\n');
    }
}

C++ 3D Array

To create a multi-dimensional array in C++, we should change perspective a little bit and think of creating arrays that point to other arrays, which point to other arrays, and so on. For example, to create a 2x3x4 array in C++, we should imagine the implementation as follows:

For simplicity, we are doing the jagged implementation of the multi-dimensional array (address of array3d[0][1][0] is not directly after array3d[0][0][3] in memory representation above). In the next section, we will implement it in C the contiguous way. To allocate a jagged 2D array in C++, one can write the following (compare to C# jagged above):

int** jaggedArray = new int*[2];
jaggedArray[0] = new int[4];
jaggedArray[1] = new int[3];

The elements can be accessed as usual: jaggedArray[i][j]. The extra work we have to do in C++ is to explicitly deallocate the array.

delete[] jaggedArray[0];
delete[] jaggedArray[1];
delete[] jaggedArray;

See the code sample below to understand how we allocate and deallocate a 3 dimensional array in C++.

Sample Code

#include <iostream>

using namespace std;

void main()
{
    //  Array 3 Dimensions
    int x = 4, y = 5, z = 6;

    //  Array Iterators
    int i, j, k;

    //  Allocate 3D Array
    int ***array3D = new int**[x];

    for(i = 0; i < x; i++)
    {
        array3D[i] = new int*[y];

        for(j = 0; j < y; j++)
        {
            array3D[i][j] = new int[z];
        }
    }

    //  Access array elements
    for(i = 0; i < x; i++)
    {
        cout << i << endl;

        for(j = 0; j < y; j++)
        {
            cout << endl;

            for(k = 0; k < z; k++)
            {
                array3D[i][j][k] = (i * y * z) + (j * z) + k;
                cout << '\t' << array3D[i][j][k];
            }
        }

        cout << endl << endl;
    }

    //  Deallocate 3D array
    for(i = 0; i < x; i++)
    {
        for(j = 0; j < y; j++)
        {
            delete[] array3D[i][j];
        }

        delete[] array3D[i];
    }
    delete[] array3D;
}

C 3D Array

Implementing multi-dimensional arrays in C is very similar to C++, except that we use malloc()\free()  stdlib methods instead of the new\delete keywords. The memory representation below is the same, but we are going to focus in this section on making the elements of the 3 dimensional array contiguous.

To do so, we start by allocating space for all array elements in one call to malloc.

int *allElements = malloc(x * y * z * sizeof(int));

Next, we create the arrays of pointers, and point to the contiguous elements we’ve already allocated.

int ***array3D = malloc(x * sizeof(int **));
for(i = 0; i < x; i++)
{
    array3D[i] = malloc(y * sizeof(int *));

    for(j = 0; j < y; j++)
    {
        array3D[i][j] = allElements + (i * y * z) + (j * z);
    }
}

Note that if we wanted the same jagged implementation as in the C++ example above, we could ignore the allocation of allElements and change the line of code array3D[i][j] = allElements + (i * y * z) + (j * z); to array3D[i][j] = malloc(z * sizeof(int)). Below is a sample code for allocating, accessing and deallocating a 3 dimensional array in C.

#include <stdio.h>
#include <stdlib.h>

void main()
{
    //  Array 3 Dimensions
    int x = 4, y = 5, z = 6;

    //  Array Iterators
    int i, j, k;

    //  Allocate 3D Array
    int *allElements = malloc(x * y * z * sizeof(int));
    int ***array3D = malloc(x * sizeof(int **));

    for(i = 0; i < x; i++)
    {
        array3D[i] = malloc(y * sizeof(int *));

        for(j = 0; j < y; j++)
        {
            array3D[i][j] = allElements + (i * y * z) + (j * z);
        }
    }

    //  Access array elements
    for(i = 0; i < x; i++)
    {
        printf("%d\n", i);

        for(j = 0; j < y; j++)
        {
            printf("\n");

            for(k = 0; k < z; k++)
            {
                array3D[i][j][k] = (i * y * z) + (j * z) + k;
                printf("\t%d", array3D[i][j][k]);
            }
        }

        printf("\n\n");
    }

    //  Deallocate 3D array
    free(allElements);
    for(i = 0; i < x; i++)
    {
        free(array3D[i]);
    }
    free (array3D);
}

Source Code

Full source code for the above 4 samples is available here.

C Pointer Tricks


I’ve been exploring\reading more about C pointers (mostly from this source) and I’ve found the following interesting tricks.

Trick 1 – Pointer Arithmetics

Question

What is the result of running the following code?

void trick1()
{
    int arr[] = {1, 2, 3};
    int *ptr;

    ptr = arr;

    printf("arr[0] = %d, arr[1] = %d, arr[2] = %d, ptr = %p, *ptr = %d\n",
            arr[0], arr[1], arr[2], ptr, *ptr);
    *ptr++ = -1;
    printf("arr[0] = %d, arr[1] = %d, arr[2] = %d, ptr = %p, *ptr = %d\n",
            arr[0], arr[1], arr[2], ptr, *ptr);
    *++ptr = -2;
    printf("arr[0] = %d, arr[1] = %d, arr[2] = %d, ptr = %p, *ptr = %d\n",
            arr[0], arr[1], arr[2], ptr, *ptr);
    (*ptr)++;
    printf("arr[0] = %d, arr[1] = %d, arr[2] = %d, ptr = %p, *ptr = %d\n",
            arr[0], arr[1], arr[2], ptr, *ptr);
}

Solution

  • ptr = arr
    • This will make the pointer ptr point to the first element in the array arr.
  • *ptr++ = -1
    • There are two operators (* and ++) to be applied on a single operand (ptr). We have to know which one takes precedence. The answer is that the post-increment (++) will be applied first. Once it’s applied, it will not affect the value of ptr until the statement completes execution.  So as we are evaluating the current statement, ptr is still pointing to the first element of the array (arr[0]). Now, we apply the * operator to the ptr operand. This will dereference the pointer and will let us access the content it points to. Since it’s pointing to arr[0], *ptr = -1 will set the value of arr[0] to -1. After the statement completes execution, the pointer ptr is incremented and thus will point to the next element in the array (arr[1]).
  • *++ptr = -2
    • As we mentioned previously, the increment operator (++) takes precedence over the dereference operator (*). Since this is a pre-increment operator, ++ptr will make the pointer point to the next element in the array arr[2]. *ptr = -2 will then set the value of arr[2] to -2.
  • (*ptr)++
    • This one should be clear by now. *ptr will point us to arr[2] and thus running (*ptr)++ will increment the value of the integer that ptr is pointing to. So the value of arr[2] will  be incremented by 1 once the statement completes execution and the pointer ptr will still point to arr[2].
    • If we try to compile (*ptr)++ = 0 we will get the following compilation error:  “error C2106: ‘=’ : left operand must be l-value”.

The result would look like this:

arr[0] = 1, arr[1] = 2, arr[2] = 3, ptr = 0043FE44, *ptr = 1
arr[0] = -1, arr[1] = 2, arr[2] = 3, ptr = 0043FE48, *ptr = 2
arr[0] = -1, arr[1] = 2, arr[2] = -2, ptr = 0043FE4C, *ptr = -2
arr[0] = -1, arr[1] = 2, arr[2] = -1, ptr = 0043FE4C, *ptr = -1

Trick 2 – Array Indexing

Question

What is the result of running the following code?

void trick2()
{
    int arr[] = {1, 2, 3};

    *arr = 5;
    printf("arr[0] = %d, arr[1] = %d, arr[2] = %d\n",
           arr[0], arr[1], arr[2]);
    *(arr + 1) = 10;
    printf("arr[0] = %d, arr[1] = %d, arr[2] = %d\n",
           arr[0], arr[1], arr[2]);
    2[arr] = 15;
    printf("0[arr] = %d, 1[arr] = %d, 2[arr] = %d\n",
           0[arr], 1[arr], 2[arr]);
}

Solution

  • *arr = 5
    • An array variable can be used as a pointer, but its value can’t be changed. Think of it as a constant pointer, though they’re not quite the same. Throughout the array’s life cycle on the stack, it will always point to the first element it pointed to when it was initialized. If we try to compile arr = &i or arr = arr2 or arr = ptr, we will get a compilation error: “error C2106: ‘=’ : left operand must be l-value”.
    • So back to the statement we are trying to evaluate, this will simply set the value of the first element in the array to 5. So now arr[0] = 5.
  • *(arr + 1) = 10
    • arr is a pointer to a value of type int. Running arr + 1 would actually result in arr + 1 * sizeof(int). Assuming that arr represents address 2500 and sizeof(int) is 4, arr + 1 will actually represent address 2504 and not 2501. This is called pointer arithmetics, where the type of the object the pointer points to is taken into consideration when incrementing or decrementing the pointer.
    • *(arr + 1) is like saying arr[1] so it will let as access the second element of the array. Thus, the statement will set arr[1] to 10.
  • 2[arr] = 15
    • This is the weirdest thing I’ve learned in C, but it does make sense after all. At first you’d think this will result in a compilation error, but when compiling 2[arr], C compiler will convert it to *(2 + arr), which is the same as *(arr + 2) since addition is commutative.
    • So 2[arr] = 15 is like saying arr[2] = 15 and this the third element in the array will be set to 15.

The result would look like this:

arr[0] = 5, arr[1] = 2, arr[2] = 3
arr[0] = 5, arr[1] = 10, arr[2] = 3
0[arr] = 5, 1[arr] = 10, 2[arr] = 15

Trick 3 – Pointers to Arrays

Question

What’s the difference between str1, str2str3 and cPtr? What is the difference between sArr, sArr2DsPtr1, sPtr2 and SPtr3? What will be the result of running the code below?

void trick3()
{
    char str1[] = { 'A', 'B', 'C', 'D', 'E' };
    char str2[] = "ABCDE";
    char *str3 = "ABCDE";
    char  *cPtr = str1;

    short sArr[] = {1, 2, 3, 4, 5};
    short sArr2D[][5] = { {1, 2, 3, 4, 5},
                          {6, 7, 8, 9, 10} };
    short *sPtr1 = sArr;
    short (*sPtr2)[5] = sArr2D;
    short *sPtr3[5];

    printf("sizeof(str1) = %u\n", sizeof(str1));
    printf("sizeof(str2) = %u\n", sizeof(str2));
    printf("sizeof(str3) = %u\n", sizeof(str3));
    printf("sizeof(cPtr) = %u\n", sizeof(cPtr));
    printf("\n");

    printf("sizeof(sArr) = %u\n", sizeof(sArr));
    printf("sizeof(sPtr1) = %u\n", sizeof(sPtr1));
    printf("sizeof(sArr2D) = %u\n", sizeof(sArr2D));
    printf("sizeof(sPtr2) = %u\n", sizeof(sPtr2));
    printf("sizeof(*sPtr2) = %u\n", sizeof(*sPtr2));
    printf("sizeof(sPtr3) = %u\n", sizeof(sPtr3));
    printf("\n");

    printf("sArr2D[1][2] = %d\n", sArr2D[1][2]);
    printf("sPtr2[0][0] = %d, sPtr2[1][2] = %d\n", sPtr2[0][0], sPtr2[1][2]);
    printf("*(* (sArr2D + 1) + 2) = %d\n", *(* (sArr2D + 1) + 2));
    printf("*(*(sArr2D) + 1*5 + 2) = %d\n\n", *(*(sArr2D) + 1*5 + 2));
}

Solution

  • str1 is a char array with 5 elements: ‘A’, ‘B’, ‘C’, ‘D’, ‘E’. str2 is a char array with 6 elements ‘A’, ‘B’, ‘C’, ‘D’, ‘E’ and ”. str3 is a pointer to an array of 6 elements ‘A’, ‘B’, ‘C’, ‘D’, ‘E’ and ”. str2 and str3 seem to mean the same thing, but actually they are different. str2 is not stored on the stack (from symbol table, it directly refers to the first element in the array) while str3 is stored on the stack and contains the value of the address of the first element of the array. In other words, str3 is storing an extra pointer of size sizeof(char *), which is 4 bytes on a 32-bit system and 8 bytes on a 64-bit system. cPtr and str3 are the same in that they are pointers that point to a char array, though they are not pointing to the same array.
  • There is one additional difference between pointers and arrays. If we run sizeof on an array, we’ll get the full size of the array. However, if we run sizeof on a pointer, it will return the size of the pointer only and not the content it refers to.
    • So sizeof(str1) is 5 * sizeof(char), which is 5 * 1 = 5. sizeof(str2) is 6.
    • sizeof(str3) is the size of the pointer sizeof(char *), which is 4 bytes. sizeof(cPtr) is also 4 bytes.
  • sArr is an array of 5 short numbers. Thus, its size is 5 * sizeof(short) = 10. sPtr is a pointer that points to sArr[0]. sizeof(sPtr) is 4 bytes. sArr2D is a 2×5 2-dimensional array with size = 2 * 5 * sizeof(short) = 20. The short (*sPtr2)[5] = sArr2D will declare a pointer to an array of 2 dimensions where dimension 2 has a size of 5 then make the pointer point to the 2-dimensional array sArr2D. It does not do any allocation. So sizeof(sPtr2) is 4 bytes since it’s a pointer. The sizeof(*sPtr2) is the 5 * sizeof(short) = 10. short *sPtr3[5] creates an array of 5 pointers to short values. The array contains pointers and not short values. So sizeof(sPtr3) = 5 * sizeof(short *) = 20.
  • Multi-dimensional Array
    • sArr2D[1][2] simply tries to access the third element of the second array in the 2-dimensional array sArr2D. Think of sArr2D as an array of 2 arrays of 5 int values. So sArr2D[1][2] = 8.
    • sPtr2 is a pointer to the 2-dimensional array sArr2D and thus can be used in the same way as variable sArr2D. So sPtr2[1][2] is the same as sArr2D[1][2].
    • * (sArr2D + 1) is like sArr2D[1] which points us to the first element in the 2nd array sArr2D[1][0]. *(* (sArr2D + 1) + 2) is like *(sArr2D[1] + 2), which is like *(&sArr2D[1][0] + 2), which is like *(&sArr2D[1][1]), which is sArr2D[1][2].
    • *(sArr2D) + 1 * (column count) is the same as sArr2D[1]. So *(*(sArr2D) + 1*5 + 2) is *(&sArr2D[1][0] + 2), which is sArr2D[1][2].

The full result of the above code would look like this:

sizeof(str1) = 5
sizeof(str2) = 6
sizeof(str3) = 4
sizeof(cPtr) = 4

sizeof(sArr) = 10
sizeof(sPtr1) = 4
sizeof(sArr2D) = 20
sizeof(sPtr2) = 4
sizeof(*sPtr2) = 10
sizeof(sPtr3) = 20

sArr2D[1][2] = 8
sPtr2[0][0] = 1, sPtr2[1][2] = 8
*(* (sArr2D + 1) + 2) = 8
*(*(sArr2D) + 1*5 + 2) = 8

Source Code

Full source code for the above tricks is available here.

OpenGL Color Interpolation


Using the GL_LINES mode, OpenGL will draw for us a line for every two vertices we specify.

glBegin (GL_LINES);

    glColor3f  (1, 0, 0);
    glVertex2f (x0, y0);
    glColor3f  (0, 0, 1);
    glVertex2f (x1, y1);

glEnd ();

Behind the scenes, OpenGL is using interpolation to draw the line. That is, given 2 points, OpenGL will determine the set of pixels that the line would cross through and then change their color based on the color of the line. Bresenham‘s algorithm is a famous algorithm for drawing lines, and it (or some extension of it) is probably the one used internally by OpenGL.

Using the basic linear equation we all learned in school (y = ax + b), we should be able to get to an algorithm that draws the points across the lines. We are drawing a line segment from vertex v0 (x0, y0) to vertex v1 (x1, y1). Let’s denote any point across the line as vertex v with coordinates (x, y). Given those three vertices, we can build the following 3 independent equations.

Now, we should try to create some relationship between those 3 independent equations and try to get rid of the unknowns a and b. Let’s first try to get rid of b.

Let’s try y – y0 and y1 – y0, we will get the following two independent equations.

Now, let’s try to create a relationship between those 2 independent equations and at the same time try to get rid of a.

We can now sample some values of x between x0 and x1 and get the value of y using the above equation. This is the basic idea behind drawing a line. In addition to drawing the line, OpenGL is also doing something else behind the scenes: Color Interpolation. If you run the above code sample in OpenGL, you’ll see the following line:

As points are moving from vertex v0 to vertex v1, their color is also transitioning from v0 color to v1 color. This is handled by the OpenGL Smooth shading model. OpenGL supports two shading models: Smooth and Flat. Flat shading means that no shading calculations are performed on the interior of the primitives. The color of the interiors is the color of the last vertex specified. You can set it by calling glShadeModel (GL_FLAT). Smooth shading is thedefault shading model in OpenGL and you can explicitly set it by calling glShadeModel (GL_SMOOTH).

Even though OpenGL automatically does color interpolation (in case of smooth shading), it would be interesting if we try to implement it and experiment a little bit with it.

To implement the linear interpolation of the points and their colors, we are going to use the below generic linear interpolation method, where u is any value we select from 0 to 1.

First, let’s define the point data structure.

//  Define the point data structure
typedef struct Point
{
    float x;                  //  x position of the point
    float y;                  //  y position of the point
    float z;                  //  z position of the point
    float r;                  //  red color component of the point
    float g;                  //  green color component of the point
    float b;                  //  blue color component of the point
    float a;                  //  alpha color component of the point
} Point;

Next we set the number N of how many points we want to sample on the line, and initialize the array that will hold the points.

//  represents the number of points the line consists of
#define N 250

//  Declare the array of points
Point linePoints[N];

Now, we generate the location and color components for the points on the line using the above linear interpolation formula.

//  Location and color interpolation
for (i = 0; i < N; i++)
{
    u = (float)i/(N - 1);

    linePoints[i].x = v0.x * (1.0 - u) + v1.x * u;
    linePoints[i].y = v0.y * (1.0 - u) + v1.y * u;
    linePoints[i].z = v0.z * (1.0 - u) + v1.z * u;
    linePoints[i].r = v0.r * (1.0 - u) + v1.r * u;
    linePoints[i].g = v0.g * (1.0 - u) + v1.g * u;
    linePoints[i].b = v0.b * (1.0 - u) + v1.b * u;
    linePoints[i].a = v0.a * (1.0 - u) + v1.a * u;
}

Finally, we draw this set of points.

glBegin (GL_POINTS);

for (i = 0; i < N; i++)
{
    glColor4f  (linePoints[i].r, linePoints[i].g, linePoints[i].b, linePoints[i].a);
    glVertex3f (linePoints[i].x, linePoints[i].y, linePoints[i].z);
}

glEnd ();

More implementation details are available in the full source code of this OpenGL app. You can use this app for experimenting with color interpolation and you might even notice how the OpenGL interpolation method is way faster than our simplistic implementation (if you have a machine with a relatively slow processor). 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.

OpenGL Resolution


This is a simple OpenGL app that runs in full screen (game mode), shows every other pixel in alternating color, and displays the screen resolution (m x n grid of pixels) and the screen dimension in millimeters.


Note: The pixels are actually black and white, but because this screenshot is reduced in size, you see a gray background. Click on this image to see the full sized one.

The implementation is very simple. We use glutGet (GLUT_SCREEN_WIDTH) to get the screen width in pixels and glutGet (GLUT_SCREEN_HEIGHT) to get the screen height. To get the width and height in millimeters, we use glutGet (GLUT_SCREEN_WIDTH_MM) and glutGet (GLUT_SCREEN_HEIGHT_MM) consecutively. This would even tell us the width and height of a single pixel in millimeters. For example, pixel width in millimeters is equal to screen width in millimeters divided by the screen width in pixels. Same can be done for the height.

//-------------------------------------------------------------------------
//  Draw string representing the resolution of your screen
//-------------------------------------------------------------------------
void drawResolutionStr ()
{
    glColor3f (0, 0, 1);

    printw (20, 20, 0,
            "Resolution: %d x %d pixels, %d x %d mm",
            glutGet (GLUT_SCREEN_WIDTH), glutGet (GLUT_SCREEN_HEIGHT),
            glutGet (GLUT_SCREEN_WIDTH_MM), glutGet (GLUT_SCREEN_HEIGHT_MM));

    glColor3f (1, 0, 0);

    printw (20, 45, 0,
            "Pixel Dimensions: %.4f x %.4f mm",
            (float)glutGet (GLUT_SCREEN_WIDTH_MM) / glutGet (GLUT_SCREEN_WIDTH),
            (float)glutGet (GLUT_SCREEN_HEIGHT_MM) / glutGet (GLUT_SCREEN_HEIGHT));
}

You can find the full source code 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.

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: