Jump to content

  • Log In with Google      Sign In   
  • Create Account

Ramblings of a partialy sane programmer

Current OpenGL Progress and other stuff

Posted by , 31 December 2012 - - - - - - · 821 views

Well my current prog ress state on learning OpenGL is that I currently have gone nowhere. Essentially it is at a stand still. There are a few reasons for this.

First reason is procrastination.
Second reason is more or less the cause of the First.

Right now I am really tied up with another project that I am trying to get off the ground. The project is a web development Project using Java EE which really needs to get moving. Essentially this project is meant to make me money down the road when it is finished as a sort of Corporate startup endeavor. This is not the typical hipster startup trend BS that is all over the place. A friend of mine and I have wanted to start a Software company for a long time and this is the project that could get it off it's feet. Essentially it is a web tool for small businesses that allows for Order Processing, Inventory tracking, etc..... which is run for them off site in a cloud like setting and they can use the WebFrontend or the Thin Client to work with the system. Hard to really explain the software unless you have used some of the systems already r out there that make you want to blow your brains out because of how disfunctional they really are.

So right now I have been brushing up on my Java and crash coursing some Java EE to give me a base to work off of. Beleive it or not everything people say is false. Java is actually quite a awesome language and it is really fast. Could get a bit verbose at times but it is very nice to work with and I am comming to the point where I am growing quite fond of it again. I have not touched java since version 1.5 and Java was the second programming language I learned after Visual Basic 5 and before C.

If and when I get a chance to spend some time learning OpenGL I might try porting the Arcsynthesis tutorials to Java with LWJGL because quite honestly the SuperBible 5th edition is a sad excuse for a book from what I experienced so far.

Preparing to Learn OpenGL (Toolchain Setup)

Posted by , 16 December 2012 - - - - - - · 1,145 views

Hello again everyone.

I am finally after a very long time going to be diving into 3D for my next project.
In order to do this I obviously need to learn a 3D api and after much evaluation I have
decided to learn OpenGL. The main reason for this is not because of its cross platform
support but because the style of the api melds with my brain much better then the COM based
Direct3D api. This is probably due to my strong roots and love for the C language but either
way I have made my choice.

I am going to be learning the Modern OpenGL style obviously starting with OpenGL 3.3.
There really is not many books out there on modern opengl so I will resort to using the
OpenGL Superbible 5th edition to get my feet wet. Sure it uses a GLTools wrapper library
but from what I can tell is eventually they teach you the stuff under that library so I will
be using it as a stepping stone to get a understanding and then supplement it with the more
advanced arcsynthesis tutorial and maybe the OpenGL 4.0 Shader Cookbook. I am hoping this will
give me a solid foundation to build off of.

With that in mind I need to configure the OpenGL Superbible to work with my Toolchain I have set up.
The superbible assumes use of Visual Studio, XCode, or Linux Makefiles. I currently don't use any of these.
First I am not on Linux even though I have strong roots with linux (My server runs on it) and development on
Linux my current laptop uses the Nvidia Optimus technology which currently has very poor Linux support.
So instead I put together a toolchain on Windows 8 in which I am somewhat comfortable with which I may adapt
in the future.

The current toolchain consists of MinGW/MSYS, CMake, Subversion and Sublime Text 2. MinGW is a gcc compiler for windows.
CMake is a cross platform build generator and Sublime Text 2 is a Non Free cross platform text editor that integrates
with TextMate bundles and is extensible through Python. Subversion is obviously a version control system. I could use git
or Mercurial but I am still having a hard time with the concept of DVCS so this is subject to change as well.

To use the OpenGL Superbible we have a few dependencies which are needed. The first is FreeGlut and the second is the
GLTools library. I got the code for the Superbible from the googlecode svn repo so I can get the source for GLTools.
I downloaded a newer version of FreeGlut from the website 2.8 the repo came with 2.6. I needed to build these with my
compiler so that they can properly link so I threw together 2 cmake files to do this. I made 4 directories under my
Documents folder 1 for FreeGlut's source, 1 for GLTools source, and 1 out of source build directory for each library.
The CMakeLists.txt file for each library went under the source directories. Then I ran cmake to generate MSYS Makefiles.
Then ran make. The make file places the libraries under a central C:\libs folder and also moves the headers there as well.
If you are interested here is the content of the CMakeLists.txt files. I used globbing for the source files which is bad
practice but in this case it does not matter because I will not be adding any more source files to the CMake projects.

GLTools CMakeLists.txt
cmake_minimum_required(VERSION 2.6)
set(SRC_DIR "src/")
set(INC_DIR "include/")
file(GLOB SRC_CPP ${SRC_DIR}*.cpp)
file(GLOB SRC_C ${SRC_DIR}*.c)
add_library(GLTools ${SRC_CPP} ${SRC_C})
set_target_properties(GLTools PROPERTIES
target_link_libraries(GLTools Winmm Gdi32 OpenGL32)

FreeGlut CMakeLists.txt
cmake_minimum_required(VERSION 2.6)
set(SRC_DIR "src/")
set(INC_DIR "include/")
set(BUILD_DIR ${PROJECT_BINARY_DIRECTORY}/libs/freeglut-2.8.0/libs)
file(GLOB SRC_C ${SRC_DIR}*.c)
add_library(freeglut32_static ${SRC_C})
set_target_properties(freeglut32_static PROPERTIES

I don't think the FreeGlut one is optimal because of the complexity of building the library.
It has been tested and does work so it should be fine. If I encounter any issues with the way
the library is built I will make sure to post and update.
So after running make under C:\libs I have the following structure

This structure will allow me to easily create CMake build for all of the chapters in the book as
I complete them. I know where the libraries are so I can easily link them and bring in the headers.
Kind of hackish but being that this is not a custom project it is the easiest way to ensure I can get
build up and running quickly.
That is all for this post hopefully it was helpful cya next time.

Fun with ANSI C and Binary Files

Posted by , 09 December 2012 - - - - - - · 2,085 views

Hello Everyone,

After that last rant post I felt obligated to actually post something useful. I feel horrible when I rant like that but sometimes it just feels necessary.
On a side note however, yes I still hate VS 2012 Express. After all these years you think Microsoft would Update their damn C compiler ugh.

Ok so on to the meat of the post. Though my various browsings of the forums I have seen people with an interest in pure C programming. It really makes me feel good inside because it really is a nice language. So many people say it is ugly and hackish and very error prone. I tend to disagree I actually feel it is much less error prone then C++. We will get into why in a few moments. First before I get into code let me explain a bit why I love Pure C despite its age.

The first thing I really like about C is the simplicity. It is a procedural language which makes you think in steps instead of abstractions and objects. In other words it causes you to think more like the actual computer thinks in a general perspective. I think this is great for beginners because it forces you to think in algorithms which are nothing but a series of steps.

The next part I like about it is the very tiny standard library. It is so small you can actually wrap your head around it without a reference manual. This does come with some downfalls as you don't get the robust containers and other things C++ comes with esenssially in C you have to write your own ( Not as bad as it sounds ).

Lastly raw memory management. No worrying about whether or not you are using the right smart pointer or not etc... Now I know what people are going to say that C is more prone to memory leaks then C++ becuase of the lack of smart pointers. Sure you can leak memory but it is a lot harder to do so in C IMHO. The thing is again C is procedural without OOP. This means when programming in a procedural way you are not going to be accidentally copying your raw pointers. So the only way really to leak is to forget to free the memory. Which under standard C idiom is rather hard to do. In C the moto goes what creates the memory frees the memory. What this mean is if you have a module say a storage module that dynamically allocates with malloc that module must be responsible for cleaning up the memory it created. You will see this in action next.

As I said ANSI C allows you to think in the terms of algorithms without the sense of having to abstract everything.
To provide an example I created a very basic .tga image loader based off of nothing but the Specification.

Keep in mind this is simple particularly for using in a texture. Basically I skipped a bunch of uneeded header elements and extension elements because they are not needed as I am not saving a new copy of the file so I just grab the useful bits.

So from a design perspective this is what we need.
A structure that will store our image data.
A function to load the data
Finally a Function to clean up our dynamically allocated memory (Due to the above best practice)

From this we get the following header file.
#ifndef TGAIMAGE_H
#define TGAIMAGE_H

* Useful data macros for the TGA image data.
* The data format is layed out by the number of bytes
* each entry takes up in memory where
* 1 BYTE takes up 8 bits.
#define BYTE unsigned char /* 1 BYTE 8 bits */
#define SHORT short int    /* 2 BYTES 16 bits */

* TGA image data structure
* This structure contains the .tga file header
* as well as the actual image data.
* You can find out more about the data this contains
* from the TGA 2.0 image specification at
* http://www.ludorg.net/amnesia/TGA_File_Format_Spec.html
typedef struct _tgadata {
    SHORT width;
    SHORT height;
    BYTE depth;
    BYTE *imgData;

* Load .tga data into structure
* params: Location of TGA image to load
* return: pointer to TGADATA structure
TGADATA* load_tga_data(char *file);

* Free allocated TGADATA structure
* return 0 on success return -1 on error
int free_tga_data(TGADATA *tgadata);

The above should be self explanitory due to the comments provided.
I created 2 #define Macros to make it easier to manage the typing. The specification defines the size of the data at each offset which all revolves around either 8 or 16 bits.

Now we have the implementation of our functions. Here is that file.
#include <stdlib.h>
#include <stdio.h>
#include "tgaimage.h"

TGADATA* load_tga_data(char *file)
    TGADATA *data = NULL;
    FILE *handle = NULL;
    int mode = 0;
    int size = 0;

    handle = fopen(file, "rb");

    if (handle == NULL) {
	    fprintf(stderr, "Error: Cannot find file %s\n", file);
	    return NULL;
    } else {
	    data = malloc(sizeof(TGADATA));

	    /* load header data */
	    fseek(handle, 12, SEEK_SET);
	    fread(&data->width, sizeof(SHORT), 1, handle);
	    fread(&data->height, sizeof(SHORT), 1, handle);
	    fread(&data->depth, sizeof(BYTE), 1, handle);

	    /* set mode variable = components per pixel */
	    mode = data->depth / 8;

	    /* set size variable = total bytes */
	    size = data->width * data->height * mode;

	    /* allocate space for the image data */
	    data->imgData = malloc(sizeof(BYTE) * size);

	    /* load image data */
	    fseek(handle, 18, SEEK_SET);
	    fread(data->imgData, sizeof(BYTE), size, handle);

	    * check mode 3 = RGB, 4 = RGBA
	    * RGB and RGBA data is stored as BGR
	    * or BGRA so the red and blue bits need
	    * to be flipped.
	    if (mode >= 3) {
		    BYTE tmp = 0;
		    int i;
		    for (i = 0; i < size; i += mode) {
			    tmp = data->imgData[i];
			    data->imgData[i] = data->imgData[i + 2];
			    data->imgData[i + 2] = tmp;
    return data;

int free_tga_data(TGADATA *tgadata)
    if (tgadata == NULL) {
	    return -1;
    } else {
	    return 0;

Lets start at the top with the tga_load_image function.

In C the first thing we need to do is set up a few variables.
We have one for our structure, the file, the mode and the size. More on the mode and size later.

We use fopen with "rb" to open up the file to read binary data.
If the file open was successful we can go ahead and start getting data.

The first thing we do here is use malloc to reserve memory for our structure and use sizeof so we know how much memory we need.

Now we load the header data. I use the fseek function to get in position for the first read.
fseek in the first arument takes a pointer to our opened file. The second argument is actually the first offset we want to read from and SEEK_SET says to count that offset from the beginning of the file. An offset is the number of bytes into a file. The specification for the tga file tells us that the width of the image starts at offset 12. It is two bytes in size so we ensure we only read 2 bytes from the file with sizeof(SHORT) and tell it to do 1 read of that size. Then the internal pointer for file position is now at offset 14 which is where our hight is. We do the same then finally read the depth which is one byte in size placing us at offset 17.

Now that the header data we need is read and stored we need to handle that actual image data which is tricky. This is where our mode and size variables come into play.

You find the mode of the image data by dividing the depth by 8. So if you have a 24 bit depth and divide it by 8 you get a mode of 3.
This mode is actually the number of components each pixel in the data has. The tga spec defines a mode of 3 as BGR and a mode of 4 as BGRA. Blue Green Red and Blue Green Red Alpha respectivly. Now the actual size of the section of image data varies depending on the image so we need to calculate the size of that section so we don't read to far into the file corrupting our data. To do this we need the width, height, and mode. By multiplying them together we get the size of the section. 3 bytes per pixel for each pixel defined by width and height. Hope that makes sense.

Now that we have the size of this image data section we can dynamically allocate our imgData section of the structure to the appropriate memory size.

We then need to fseek to the appropriate section of the file which is offset 18 for this data and we read in the full section because it is defined as a run of bytes.

Now we have the data ensure the file is closed to free the memory allocated by fopen.

Ok remember just above I said mode 3 and 4 are BGR and BGRA respectivly. This is not good because if we use this as a texture is say OpenGL it needs to be in RGB or RGBA format. So we ensure the mode here and we need to flip the red and blue bytes around in the data.
To flip the bytes we are doing some very basic index math because the data in the pointer is technically an array it allows us to hop the right number of indicies in this case 2 because RGB will always be a triplet and we don't care about A or G because the are in the proper location. If you don't understand the pointer and array nomenclature feel free to ask in the comments or read the K&R book if you can get a hold of a copy.
Finally we return our structure to the caller.

Our last function is free_tga_data this one is important due to the rules above. The tgaimage module allocated data so it is it's responsibility to provide the means to clean it up.

Here is really simple we take in the structure as an argument and make sure it is not NULL as calling free on a NULL pointer is undefined and will likley segfault the application. If all is good we FIRST clean up the imgData portion of the structure. If we don't do this it will leak as it was a separate malloc. Then we free the rest of the tgadata structure from memory.

Hopefully this post was helpful to some of the C programmers out there. This is a very nice example to demonstrate how clean a solution in C can be as well as allows for a nice demonstration on how best to avoid memory leaks in C applications due to various best practices. Not only this but it also demonstrates how to traverse a binary file using the files Offsets from nothing more then the specification.

That is all for now have a great day.

Microsoft what are you doing?

Posted by , 02 December 2012 - - - - - - · 856 views

Interesting state of affairs I have come across today. So lets just get into it and try to be short and sweet.

Today I have been doing some research on graphics API's. For the longest time I have been wanting to move to the 3D end of computer graphics. As everyone knows there are 2 API's for this D3D and OpenGL. I don't really want to get into flame war's over the two API because it really does not matter they both do the same thing in different ways.

So ultimatly my choice that I made after my research was to use D3D. The reasoning behind this was the superior quality of Luna's books over the SuperBible of OpenGL. Luna really gets into interesting stuff like water rendering examples and terrain rendering examples where the SuperBible spends the entire book rendering tea pots. This is not really and issue but the state of the book is rather lacking due to the fact that so many pages are wasted using his pre canned fixed function api instead of just getting down to the nitty gritty. I am not a fan of the beat around the bush style and prefur the jump right in mentality. I am a competant programmer there is no need for the wrapper api it is just extra dead trees. So this is the main reasoning behind the D3D choice just shear quality of resources available.

Then I came across the current Microsoft debachal. Not sure what they are thinking. First off yes I am running Windows 8 and I really love it. Nice and easy to use once you get use to it and I like the clean style it presents. I think the new version of visual studio could use some UI work but who cares. The real issue comes into play with the Express 2012 Edition because I don't have $500 to drop on an IDE. Actually I prefur no IDE but again that is another gripe. When Microsoft moved the D3D SDK into the Windows 8 SDK the removed some API functionality (not a big deal) but they also removed PIX. They rolled PIX and the shader debugger into Visual Studio and made it only available in the Pro + versions. NOT COOL. NOT COOL AT ALL. Not only this but they on top of it removed the cmd line compilers.
So in order to get those you need to install visual studio first.

So basically they want me to use the IDE or at least install it and then remove the standalone debuggers meaning I can't properly debug shaders as I am learning unless I shell out $500. Not cool again not at all.

So right now I am leaning towards having to use OpenGL and avoiding potential Windows 8 store development just so that I can properly adapt my work flow to the standalone tools they provide.

Not sure what Microsoft is thinking here but it really feels like they are trying to alienate the Indy style of development for the sake of a few bucks. Really wish they still had the $100 standard edition sku I would buy it in a heartbeat if it got me the tools they took away.

Sorry for the little rant not usually like me at all.

If anyone knows about any potential work arounds (NOT PIRACY I HATE PIRACY) feel free to clue me in.

December 2012 »


Recent Comments

Recent Comments