First Impressions from the LEAP Device

by cpi.cecko on February 1, 2013

I have finally received the Leap Motion device. I am quite excited about it and I am ready to make some simple applications which would test its functionality. In this post I am going to make some quick analysis of the device and my first impressions.

The package comes with the device, a USB cable and a letter from the co-founder and CEO of the company. There are several revisions of the device. The Rev4 and Rev5 are without aluminium casing, just the developer board. I was lucky to have the revision 6 device with the casing. The USB cable is quite stylish but a little bit stubborn and sometimes it moves the device which makes the Leap little unstable. However, I think that is not a big issue, because for half an hour the device hasn’t moved once. The letter is quite charming and well-written.

The installation was very easy. There were small calibration issues, but with some little effort I managed to fix them. There is a Visualizer app in which you can test the finger detection and there are also few examples which could be downloaded from the company’s site. The interface with which you can access detected data and interpret it somehow is well documented and well written. There is also a sample code which shows you the main functionality in about 100 lines.

That is all for now. The next week I am going to develop a simple game which will exploit the features of this gadget. Of course, I will write another post on it and also I will provide the code.

That’s all. Happy developing :)

  

  

The Life of a Bug or Yet Another Reason to Use Version Control

by cpi.cecko on January 14, 2013

Bugs are strange creatures. They silently form in your code, feed with it, use it. If you are not careful, if you don’t test your application thoroughly, their quantity will grow and grow, and grow. Your code will get sadder and sadder, and sadder. In fact bugs are like AIDS – you could have had them for ages but they would show when you least expect them. And now I am going to tell you the story of a bug. Let us name him Sam.

One beautiful day a programmer who was developing a game decided to do some inheritance. He had created a tiny library for GUI rendering and handling. There was this root class TextControl which had some virtual functions and some members for text, control names and so on. The previous day the programmer had made a control which displayed images. This control was alone – no father, no mother, no hierarchy. So the developer decided to help him find his ancestors. He searched and searched, and out of laziness only found the TextControl class. “Well, that class was for text controls but it will do the trick, ” said the programmer. And the new ImageBox control now had its family. Despite feeling uncomfortable between his brothers and sisters who all handled only text, he was happy that he finally found some social contact. On that day – 15 December 2012 – two things happend. You already heard the first. The second is that Sam was born.

Days and weeks were passing by, the birds sung, the code was happy and ill. One day – 13 January 2013 – the programmer decided to record a new video about his new awesome feature in his game. While recording the video, something strange happened. He accidently resized the game’s window. The FPS dropped to zero. Everything became pretty f***ed up. “Strange,” the programmer thought, “Yesterday there wasn’t such an issue…” He was scared. For the first time in his life he had came across such a bug. He panicked for a second, but he got calm again fast. “Thank god I use git!”, thought the programmer. He checked out the yesterday’s commit. The bug was there again. He checked out the commit from five months ago. The bug wasn’t there. He checked out a commit from November – the bug wasn’t there. He checked out a commit from 1 December 2012 – the bug wasn’t there. He continued on with every commit until he reached the date 14 December – the bug wasn’t there. He tried with 15 December. The BUG! It was there. He read the commit message – “The ImageBox now inherits TextControl”. He stopped and thought for a second. “The bug appears on screen resize, so it must be connected with the Reshape function. But, what happens there? Aah! The controls’ Update methods get called. What were these for? For handling text size on screen resize. But the ImageBox doesn’t have text…” These thoughts ran through the programmer’s mind lighting fast. While thinking, he had managed to reset the code’s current version and to reach the TextControl’s Update method. It was virtual. He searched for the ImageBox’s Update function. There wasn’t such function. “So the ImageBox uses TextContol’s Update. And there the text gets resized and some other non-image related stuff happens. Aha!” He implemented the Update for the ImageBox. He started the game. He resized the screen. Voila! Bug fixed!

That day two things happend. The first is that Sam died but left tiny little eggs scattered through the code. The second – the programmer understood how lucky he was for using source control…

So that’s all folks.

This happened to me yesterday. Maybe the main reason for the bug is the messy big ball of mud my code had become over the months of development. But I am still learning. Refactoring is on the list of course, but I don’t have much time to finish the game, so I am trying to concentrate on implementing the actual working thing. When the first release is done I will give myself a week or a month and make everything work like I want it to. I also know that maybe even without source control, I would’ve fixed the problem. It is easy to figure out that something should happen in the Reshape function when you resize the screen. But many things happen in this function. And instead of less than an hour, I would have fixed the problem in a day or more.

The Leap Motion Controller

by cpi.cecko on January 11, 2013

So this is the “Leap Motion”. A thing which may be the next evolutionary step in human interface devices. It is capable of tracking even the slightest movement of your hand and interpreting it on your computer screen. There may be a few drawbacks though. For example, you may get tired after using it for couple of hours. Also, there is still small amount of applications which are integrating the device. However, when you plug it in you get instant support for mouse movement and some other basic actions.

The more interesting part, however, is the community campaign led by the company which develops the device. Firstly, they gather developers through a candidature which, if you get accepted, can supply you, as a programmer, with the device and an SDK for developing applications with it. And all of this is for free. The only thing you need to do is to fill in a form in which you write about your idea for an application which would use the device in some creative way. Then you wait. If you get approved, the “Leap Motion” should come to you in few weeks and you can start developing and contributing to the world’s history. Secondly, if you preorder the device you can get it for only $70. The cheap value combined with the fast growing variety of applications integrating the device gathers the needed support and popularity for this new technology.

As one of the developers who was approved I can proudly say that the “Leap Motion” would come to me in about 2 weeks. When I get it I am going to make a test video with the SDK and maybe start developing some tutorials on programming with this little thing.

Thoughts on Compile-Time Assertions

by cpi.cecko on August 17, 2012

Warning: This is just my knowledge here. I don’t assure you it’s correct. It is just how I understand this topic.

Continuing with the reading of Alexandrescu’s book I came across the Compile-Time assertions. Simply put these are used to make sure your code doesn’t have any errorenous parts during compile-time. This way you can be fast in detecting errors and fixing them before even running your application. There are some drawbacks though. Like the arguments to the assertion must be constant but, apart from that, this is a time-saving method for things like safe reinterpret casting (like the example in the book) and it sure has other applications of which I am not aware because my lack of experience.

So how are these implemented? Well, the first way which doesn’t tell you anything about the error is very simple:

#define STATIC_CHECK_NOINFO(expr)\
{\
    char unnamed[(expr) ? 1 : 0];\
}

If the expression is false we will be creating an array of zero length which is illegal in C/C++. As I said, its drawback is the lack of information.

The other technique provided in the book is little more informative. We create a template struct which is defined if the expression is true. Otherwise the compiler will throw a compile-time error. With this approach we can at least be sure that the error has been caused by our assertion and not by other code in our program.

template<bool> struct CompileTimeError;
template<> struct CompileTimeError<true> {};

#define STATIC_CHECK_SOMEINFO(expr)\
   (CompileTimeError<(expr) != 0>())

The final solution provided in the book, which I couldn’t make work and I am very curious to find out why, is to make a template structure which, when defined for true creates an ellipsis constructor which makes the program to run fine. Otherwise the compiler should output something like “Error: Cannot convert ERROR_##msg to CompileTimeChecker<false>”. Sadly, I can’t say what actually happens.

template<bool> struct CompileTimeChecker
{
    CompileTimeChecker(...);
};
template<> struct CompileTimeChecker<false> {};

#define STATIC_CHECK_INFO(expr, msg)\
{\
    class ERROR_##msg {};
    (void)sizeof(CompileTimeChecker<(expr) != 0>((ERROR_#msg())));\
}

Finally, there is another solution, which is working, that I found at StackOverflow. It is based on the first method, that array size can’t be zero. Also it is made to work on GCC, Cameau and Visual Studio C++ compilers.

#ifdef __GNUC__
#define STATIC_ASSERT_HELPER(expr, msg)\
	(!!sizeof \ (struct { unsigned int STATIC_ASSERTION__##msg: (expr) ? 1 : -1; }))
#define STATIC_ASSERT(expr, msg)\
	extern int (*assert_function__(void)) [STATIC_ASSERT_HELPER(expr, msg)]
#else
#define STATIC_ASSERT(expr, msg)\
	extern char ERROR_##msg[1];\
	extern char ERROR_##msg[(expr) ? 1 : 2]
#endif

That is all for these assertions. Everything could be tested with the `safe_reinterpret_cast` function. It simply checks whether the type to which you cast isn’t too narrow to hold the source type’s data.

template<class To, class From>
To safe_reinterpret_cast(From from)
{
	STATIC_ASSERT(sizeof(From) <= sizeof(To),
		Destination_Type_Too_Narrow);
	return reinterpret_cast<To>(from);
}
int main()
{
    int i = 4;
    void *toCast = &i;
    char casted = safe_reinterpret_cast<char>(toCast); // Should fail. If you cast to int it wouldn't.
}

How I understand policy-based design

by cpi.cecko on August 5, 2012

I said I am going to write and here it comes! Today I wish to form my knowledge for policy-based library design.

Warning: This is just my knowledge here. I don’t assure you it’s correct. It is just how I understand this topic.

So, what about it? Firstly, why there is a need for it. You see, when a software architect or someone who wants to write a library starts designing it, he/she is faced with numerous design decisions. Let’s take, for example, a particle system class. In this class you have number of particles you will emit and a pattern in which you will emit them. Based on this pattern different effects can be simulated. Here comes the question of how we can do that. Should we make a separate particle class for every effect or is there a way to have one, modifiable class, or is there some other way? The first way will break the DRY (Don’t repeat yourself) principle. And this is a bad thing because half of our code will be exactly the same and we can do nothing about it. Well that leads us to think how we can implement the modifiable class? Policy-based design comes to the rescue!

The principle of this class design is that you have a number of policies and based on them you generate a unique particle effect. For example: if you want to make your particles behave like a fire, you create the FirePolicy. You want other behavior – you create another policy. And if the class supports multiple policies, you can create a particle effect which, for example, simulates a laser beam which is surrounded by flying particles or something like that. What I want to say is that you basically can create almost every type of particle by having a small library code and few predefined policies. Even better, the user of your library can create his own policies by only following the semantics of your library. 

After all that writing, here is a little code which may not be the best example, but I think it illustrates the principle:

// The main class.
template<class ParticlePolicy>
class Particle
{
private:
   int count;
   std::vector<vec3> positions;
   std::vector<vec4> colors;
public:
   Particle(int newCount)
   {
       count = newCount;
       positions.resize(count);
       colors.resize(count);
   }

   void Update()
   {
       for(int i = 0; i < count; i++)
       {
           ParticlePolicy().Update(positions[i], colors[i]);
       }
   }
   void Render();
};

// The policy.
struct SimplePolicy
{
    void Update(vec3 &position, vec4 &color)
    {
        position += 1.0f;
        color.x += 0.01f;
        color.z += 0.01f;
    }
};

Based on this realization, the class can be used like that:

   Particle<SimplePolicy> simpleParticles(100);
   simpleParticles.Update();
   simpleParticles.Render();

So this is how I understand the policy-based class design. If you want to read more about it you can check it out on wikipedia or see Andrei Alexandresku’s ‘Modern C++ Design’.

Bye for now!

Continuing the life of this blog

by cpi.cecko on August 4, 2012

I haven’t written anything since ages. I don’t know how that happened but I am the kind of person who needs to get the muse for writing. Now, I hope I will start to deliberately write here. The topics would be more about the books I read recently, summarizing my knowledge. Also, I hope to get into the habbit of talking about life and fitness. If I succeed, this will soon be a blog where there are two or three posts a week. I hope I can find the time to do this :)

After this broad and somehow twisted introduction let me say about what I will write.

The first thing is the book Modern C++ Design. This book is an intermeadiate to advanced read for software engineers who want to improve their skills in C++ and programming in general.

The other book, about which I won’t write so occasionally, will be Anatomy and Physiology. This book is on human anatomy and I decided to read it because I want to improve my understanding of the human body and how we work. I read it slowly so don’t expect so many posts about it.

The next is Programming =++ Algorithms. Book on computer algorithms, as the name suggests, written in the C language.  It is not so well explained in places, but it is very good and detailed introduction (maybe) to algorithms.

The other books I read and may post about them are the Pragmatic Programmer and Pragmatic Thinking and Learning.

Enough about books. I said that I will also post something about my fitness philosophies and life in general. Also, I will soon read these books, so expect new things!

That is for now. I hope I will get into the habbit to post regularly here. I know I would benefit from it!

Blackflame Games is developing!

by cpi.cecko on March 18, 2012

Hi all!

Today we introduced our conception for the club’s site. It is very interesting and I think it will make the dudes write some code. It will have achievements, experience, levels and other really good stuff! Soon I will post some concept-art of it and more on the topic. And after a month or so it will be ready, so stay tuned!

Apart from that, we have a code repository now! It is on www.github.com and there you can find all the source we are working on!

Bye for now, wait for updates!

Blackflame Games is founded!

by cpi.cecko on February 20, 2012

Maybe a silly move of mine but me and my friend Vladi decided to create a game development studio. I hope some day that it will reach the top ones and we will create games that are going to be played worldwide!

So what we are doing now? We created a game dev club in our school(as you may recall from previous posts of mine) where young and open-minded people would share same interests and develop their skills in game engineering(tomorrow is the opening!). Also, we are working on a strategy game project which will include many new and not before-seen design and gaming experience features. But end of spoilers :) . And more, and more is up to come!

And happy birthday to my granddad, I love him!

Today is a good day :)

by cpi.cecko on January 18, 2012

18 Jan 2012. Wednesday. This is the most remarkable day in my life. I achieved the first real-life goal I really appreciate.

So, what actually happened? A week ago I came with the idea of making a game development club in the school I study in. In it students will exchange ideas, methodologies and techniques which would be useful in their developement as game engineers. Everyone would be given the chance to say something new. To present new concept or “gem” of this IT branch. We would get involved in projects, contests, olympiads, etc. And last, but not least, is the experience. The experience which students will gain in this club and the experience which would help them to develop a successful career. With this stuff in my mind I decided that this would be one of my main objectives to complete before I graduate. And the foundations were laid. Next minor objective – the approvement from the high-level school personnel e.g. the principal.

For this to be achieved I structured the “project”‘s ideas and wrote something like proposal. I wrote about the core of the “project”, about the participants, the necessary equipment and the plan for what is to be achieved. The structure was ready. The last thing which was remaining was the presentation of everything.

Firstly, I arranged a meeting with the deputy principal, who was my history teacher, in order to present her the proposal. Arrangment – check! And today was the day I introduced the blueprint of the club. Of course everything went smoothly. Me and the friend who is helping me with the NOIT project, held the negotiations and we got through them. There were some pitfails we avoided, some good things we said and some neat and clean arguments that made us successful. However, I think the proposal’s structure made everything look so good for us. The first impression is the most crucial one… :)

I hope you have the same remarkable day in your life!

OpenGL mouse ray picking.

by cpi.cecko on December 31, 2011

So, I have been struggling with this problem for many days and finally managed to find a solution. Well, you can only pick spheres but that is a start. You can find algorithms for the other intersections(ray-mesh, ray-AABB, ray-cone, etc.) Also, I don’t pretend that my code is the best. This is only one of the many solutions and I am posting it because it was very difficult for me to make it work, and I feel responsible for easing you in your code life :) So, code!

Well, the first thing we need is a class for our spheres. It should contain their radius, position and color(for identifying which sphere has been picked). That is for the variables. The functions should be a default constructor, one with params, function for getting the sphere’s position, one for setting its color, rendering func and method for checking the collision.


 class SPHERE_API Sphere
 {
 private:
      Vector3d position;
      float radius;  

      float colorR;
      float colorG;
      float colorB;  

 public:
      Sphere();
      Sphere(Vector3d position, float radius,
           float colorR, float colorG, float colorB);  

      Vector3d GetPosition();
      void SetColor(float r, float g, float b);  

      void RenderSphere();
      bool CheckRayCollision(Ray mouseRay);
 };

The implementation of the constructors, the GetPosition and SetColor are trivial tasks to do. The more interesting parts are the RenderSphere() and CheckRayCollision(…)

Firstly, we will start with the Render func:

 void Sphere::RenderSphere()
 {
      glPushMatrix();
           glColor3f(this->colorR, this->colorG, this->colorB);
           glTranslatef(this->position.GetX(), this->position.GetY(), this->position.GetZ());
           glutSolidSphere(this->radius, SPHERE_SLICES, SPHERE_STACKS);
      glPopMatrix();
 }

We start by setting the sphere’s color, then we position it, and finally we render it.

Now, the more interesting thing: the collision-detection. The equation(expanded to quadric) is:

rayDirection^2 + 2 * rayDirection * rayOrigin + rayOrigin ^ 2 - sphereRadius ^ 2 = 0

If the discriminant is positive, we have two collision points. If it equals zero, we have one collision point. If it is negative we don’t have collision.

 bool Sphere::CheckRayCollision(Ray mouseRay)
 {
      float a = DotProduct(mouseRay.GetDirection(), mouseRay.GetDirection());
      float b = 2 * DotProduct(mouseRay.GetOrigin(), mouseRay.GetDirection());
      float c = DotProduct(mouseRay.GetOrigin(), mouseRay.GetOrigin()) - this->radius * this->radius;  

      float discriminant = b * b - 4 * a * c;  

      if(discriminant == 0)
      {
           return false;
      }
      return true;
 }

That is all about the collision. The ray class is simple to be defined(I will put a download link for the whole source code, so you could view the implementation). The next thing we want to do is get the mouse ray to the far plane in OpenGL. We do this with gluUnProject(…). What we want to do is to obtain the viewport, projection and model matrices. Also, we need to substract the mouseY variable from our OpenGL window’s height, because OpenGL has inverted ‘y’ coordinate. And, at the end, we call gluUnProject.

 Vector3d MouseClass::ConvertMouseToOGLCoordinate(int mouseX, int mouseY, int mouseZ)
 {
      GLint viewport[4];
      GLdouble modelMatrix[16];
      GLdouble projectionMatrix[16];       

      glGetIntegerv(GL_VIEWPORT, viewport);
      glGetDoublev(GL_MODELVIEW_MATRIX, modelMatrix);
      glGetDoublev(GL_PROJECTION_MATRIX, projectionMatrix);  

      double winY = double(viewport[3] - mouseY);  

      double x, y, z;
      gluUnProject((double)mouseX, winY, (double)mouseZ,
           modelMatrix, projectionMatrix, viewport,
           &x, &y, &z);  

      return Vector3d(x, y, z);
 }

The last thing for implementation is where we put all things together. We can either select the objects on click or on hover. I have implemented on click selection but if you want the other type just remove the ‘if()’ statement.

 Ray mouseRay;
 void HandleMouse()
 {
      if(userMouse.IsLeftButtonDown())
      {
           int cursorX = int(userMouse.GetCurrentPosition().GetX());
           int cursorY = int(userMouse.GetCurrentPosition().GetY());  

           Vector3d nearPoint = userCamera.GetCurrentPosition();
           Vector3d farPoint = MouseClass::ConvertMouseToOGLCoordinate(cursorX, cursorY, 1.0f);  

           Vector3d direction = farPoint - nearPoint;
           direction.Normalize();  

           for(int i = 0; i < 3; i++)
           {
                Vector3d origin = nearPoint - sphere[i].GetPosition();  

                mouseRay = Ray(origin, direction);
                bool isCollided = sphere[i].CheckRayCollision(mouseRay);
                if(isCollided)
                {
                     sphere[i].SetColor(0.0f, 1.0f, 0.0f);
                }
                else
                {
                     sphere[i].SetColor(1.0f, 0.0f, 0.0f);
                }
           }  

           userMouse.ReleaseLeftButton();
      }
 }

Little explanation on this. Firstly, the near point represents our camera position and the far point represents the far plane. Then we compute the ray’s direction which is the difference between farPoint and nearPoint, which shows that the direction points away from us(towards the screen). Normalizing the direction is essential. Secondly, we loop through our spheres. We compute the ray’s origin and construct the mouse ray with the obtained variables. We check for collision and if there is such, we change the sphere’s color to green. Else, we make it red. Then, we release the mouse button in order to make the user click it again if he wants to select something else.

Download link: http://www.mediafire.com/?2yv86y4s57vw8y2

I hope you enjoyed this! Happy New Year 2012!