Cogs and Levers A blog full of technical stuff

Turn off that pc speaker in Debian!

Only a short post.

The ThinkWiki has a great little write-up on disabling the pc speaker device under Debian linux. I thought I’d just shortcut the details in this post.

# Remove the pc speaker module
$ sudo modprobe -r pcspkr snd_pcsp

Remove the pc speaker permanently

# the following lines need to be added to
# the /etc/modprobe.d/blacklist.conf
# make sure you find out which device you actually have

blacklist pcspkr
blacklist snd_pcsp

Anyway, these are just the details to disable the device. The ThinkWiki article has some other ideas also on how to make the bell tone tolerable. Not for me though. I can’t stand it.

RVM & Debian

It’s always nice to have a sandboxed environment for all of your little projects. I know with how frequently I’m jumping between technologies on the same machine, I always like to use a sandbox technology of choice for the particular platform. This is a quick walk through on getting RVM up and running on a debian machine.

# First up, you need to download an install RVM:
$ curl -L get.rvm.io | bash -s stable

# Load RVM into your environment:
$ source ~/.rvm/scripts/rvm

# Check for additional requirements that rubies (you're about to install) need:
$ rvm requirements

It’s strongly advised that you follow the suggestions above for the Ruby(ies) that you want to run:

# Install the Ruby that you want to use:
$ rvm install 1.9.3

# Get Rubonic (yes, it's a word ... I ... I ... I think)
$ which ruby                      
/home/michael/.rvm/rubies/ruby-1.9.3-p327/bin/ruby

The basics of RVM

Generic value interpolation

Introduction

The core of animation in software (not necessarily graphical) is movement. That movement is between known points to achieve and overall effect. Such well-known movements might be a human moving their legs alternatively so that they can walk or a sound constantly moving from low to high to make a siren or moving your mouse cursor automatically. All of these things share the same premise. An attribute of the object needs to have its position interpolated from a starting point to an ending point over a period of time.

Some of these interpolations repeat, some do not.

Today’s post is about interpolating values between two points, but it’s about doing it with any type and with any interpolation scheme. Let’s break these parts down.

Doing it with any type

The idea here is that anything (within reason) can be interpolated. In real C/C++ terms, I mean short, int, long, float, double, char, etc. A little more interestingly when dealing with spatial objects, we could define our own Cartesian co-ordinate object - give this object X and Y attributes and then interpolate this co-ordinate between two points.

Interpolation schemes + some math

It’s the small details that matter. Linear interpolation is the simplest form of interpolation leaning on the whole “the shortest distance between two points is a straight line”. Linear interpolation will take its sequence values for progressing the object through its interpolation life using:

y = c + mx

Which looks dangerously close to the standard formula you would use to draw a straight line. In this case c would be our starting point, m would be the distance (or length) between the start and end points and x defines how far along our interpolation progression we are taking the form in range of 0.0 up to 1.0.

Another interesting scheme is trigonometric in nature. Using a soft curve to get between two points can be a softer approach. Trigonometric interpolation will take its sequence values for progressing the object through its interpolation life using:

y = c + (sin(x * (PI / 2)) * m)

Again, we have alike named variables in that c is our start point, x is our progress through the interpolated progression and m is the distance. Notice how our progress, x is multiplied by (PI / 2) only talking us 1 quarter through the progress of the curve. This is simply because we’re at 0% progress at 0 degress and 100% at 90 degrees.

Show me some code

First off, we have a base “tweener” object that will manage all of the mundane tasks that this interpolater will need to undergo in order to realize these tweened-values. You’ll notice that it is in fact a templated C++ class.

/** Provides a base interface for value interpolation */
template<class T>
class tweener {
public:
    /** Construction */
    tweener(T start, T end, const bool repeat, const Uint32 ticks);

    /** Destruction */
    virtual ~tweener(void);

    /** Resets the state of this tweener */
    void reset(void);

    /** Gets the value of this tweener */
    T value(void);

    /** Determines if the tweener has finished */
    const bool finished(void) { return _finished; }

protected:
    /** User supplied value getter */
    virtual T value_internal(const float prog) = 0;

protected:
    bool        _repeat, _finished;

    T          _start, _end;
    Uint32     _ticks, _prog_ticks;

    timer       *_timer;
};

Ignore the timer class for now. It’s there just so we can make the interpolations happen with respect to time. We move ourselves along the interpolation progression just with some simple math with regards to time. To be a little more polite about things, we detect when we’re at the start and just send the start value and detect when we’re at the end and just send the end value - rather than calculating this over and over.

/** Gets the value of this tweener */
template<class T>
T tweener<T>::value(void) {

    // make sure the timer has started
    if (!_timer->started()) {
        _timer->start();
        return _start;
    }

    // if we've already finished,
    // no more processing
    if (_finished) {
        return _end;
    }

    // accumulate split timing
    _prog_ticks += _timer->split();

    // need to handle boundaries if we're repeating
    if (_repeat) {
        // have we overflowed?
        if (_prog_ticks > _ticks) {
            _prog_ticks %= _ticks;
        }
    } else {
        // have we finished?
        if (_prog_ticks > _ticks) {
            _finished = true;
        }
    }

    // return the calculated value
    return this->value_internal((float)_prog_ticks/(float)_ticks);
}

The custom implementations for getting actual values (from types of interpolation) are as simple as this:

/** Linear interpolation calculation */
template<class T>
T ltweener<T>::value_internal(const float prog) {
    return _start + (prog * _length);
}

/** Trigonometric interpolation calculation */
template<class T>
T ttweener<T>::value_internal(const float prog) {
    return _start + (sinf(prog * M_PI_2) * _length);
}

So you can see that these custom implementations marry very closely to the formula we specified above. I think that this design documents the implementer’s intention very clearly by not having to worry about the progression code. The choice of using C++ templates also allows future implementations to target specific types. Whilst the implementations given in this article will work well for scalar values, they won’t translate very well to complex class types that don’t correctly implement operator overloading with mathematical correctness in mind. That being said, if the scope of implementation is beyond what the generic base provides, it’s only a matter of specifying the specific type when implementing your own value_internal method.

Enjoy.

A few tweeners more

Just playing around with the code set that I have here, I’ve been able to make logarithmic and parabolic tweeners relatively easy. It would be great to be able to control the co-effecients in the parabolic formula, but for the time being it’s a quadratic class:

y = x2 + c

/** Construction */
template<class T>
log_tweener<T>::log_tweener(T start, T end,
                   const bool repeat, const Uint32 ticks) :
tweener<T>(start, end, repeat, ticks) {
    // calculate the linear delta
    _length = (end - start);
}

/** User supplied value getter */
template<class T>
T log_tweener<T>::value_internal(const float prog) {
    return _start + (log10f(1.0f + (prog * 9.0f)) * _length);
}

/** Construction */
template<class T>
parab_tweener<T>::parab_tweener(T start, T end,
                   const bool repeat, const Uint32 ticks) :
tweener<T>(start, end, repeat, ticks) {
    // calculate the linear delta
    _length = (end - start);
}

/** User supplied value getter */
template<class T>
T parab_tweener<T>::value_internal(const float prog) {
    return _start + ((prog * prog) * _length);
}

Simple logging in C

Logging is probably one of the most important services you can offer your application. Your programs have information that needs to be expressed to the user, in fact in parts it’s important for your program to be almost paranoid that it hasn’t said anything.

All things should be controllable though. Putting your application into production with a paranoid level of logging doesn’t make for very happy sys-admins, so this is left as an exercise to the reader. Here, I want to present you a configurable but most importantly, a usable logging framework that you can drop into your C projects without much effort at all. Let’s go through the header!

#ifndef __libced_log_h_

#define __libced_log_h_

#include <unistd.h>
#include <time.h>
#include <stdio.h>
#include <stdarg.h>
#include <string.h>

/** Logs a line of text */
void _ced_log(FILE *file, const char *fmt, ...);

#define ced_logf(f, ...) _ced_log(f   , __VA_ARGS__)
#define ced_log(...)     _ced_log(NULL, __VA_ARGS__)

#endif /* __libced_log_h_ */

This is very simple stuff. Only one function _ced_log is defined that’s used by this header. The user is encouraged to access the logging functionality by proxy of the macros defined (ced_log and ced_logf). ced_log takes in the same parameter structure as a printf call allowing the very natural format strings to be used for your logging. ced_logf takes the structure of fprintf where you can direct your log information to a specific file handle. Again, with some small modifications you can direct all of your logs into a file by default. I just like to throw all mine out to the console. I hate surprises (in development)!! The implementation for this library piece is also very simple with only one function needing to be filled out:

#include "../include/log.h"

/** */
void _ced_log(FILE *file, const char *fmt, ...) {
  va_list ap;
  time_t t;
  char datestr[51];

  /* determine if we just go to std error */
  file = (file == NULL) ? stderr : file;

  /* datetime & pid formatting */
  t = time(NULL);
  tzset();
  strftime(datestr, sizeof(datestr) - 1, "%a %b %d %T %Z %Y", localtime(&t));
  fprintf(file, "%s [%d]: ", datestr, getpid());

  /* draw out the vararg format */
  va_start(ap, fmt);
  vfprintf(file, fmt, ap);
  va_end(ap);

  /* bump to the next line */
  fprintf(file, "\n");
}

Here is where you can really make this module your own. The default format that I have going in here has the current process ID and date/time stamp. I find these very useful during the fault-finding process once a unit of software is running. The most important thing to draw from this is you can change the default makeup of a log line by changing this code. I use this code just about everywhere. I use it so much that I have included it in my library that it available from github here.

Function Pointers, the MacGyver of C

Introduction

It’s a very well studied topic in the C field. Many people have written tutorials on how to use function pointers and what they are. The function pointer tutorial is always a good read for the uninitiated or seasoned professional who’s function pointer theory is a little rusty.

This write up isn’t going to try and fill the shoes of the basic-square-1-hello-world style tutorial. I just wanted to talk about how I’ve used them to better a piece of code and make a system a bit more extensible overall.

What are they?

Like any data pointer a function pointer is an address. It’s an address that will point to the entry-point of some code. It’s that simple. The complexity comes into the argument when you start to add C syntax. C likes to be very descriptive with the data that you’re feeding functions and function parameters are no exception.

/* a function that takes no arguments and returns no value called "func1" */
void (*func1)() = NULL;

/* a function that returns an integer and takes two integer arguments called "func2" */
int (*func2)(int, int) = NULL;

Ok, simple example time over. It’s onto what this article is really about.

Problem description

I have a game that has a few game states. They look like this:

  • Introduction credits
  • Game title
  • Menu
  • Game play
  • Game over
  • High score board

Each of these states all have functionality that they need to accomplish. The basic specification for a game state goes as follows:

  • Needs to be able to be initialized
  • Needs to be able to have its resources freed (tear down)
  • Needs to be able to update its internal logic
  • Needs to be able to render its internal state
  • Needs to be able to respond to events (keyboard, etc)

Good. We’ve established that we have a set of game states and they all attract a set of actions that we’d like them to perform.

Getting down to it

So, let’s define the actions first (as function pointers) and we can then fill in the implementation later:

/* function signature for initializing this state */    
typedef void (*init_func)();                            
                                                        
/* function signature for tearing down this state */    
typedef void (*teardown_func)();                        
                                                        
/* function signature for the render function */        
typedef void (*render_func)();                          
                                                        
/* function signature for the update function */        
typedef void (*update_func)(Uint32, Uint32);            
                                                        
/* function signature for the keyboard input event */   
typedef void (*keyboard_func)(SDL_KeyboardEvent*);      

Slightly different from above is the use of the “typedef” keyword. This allows us to define these function pointers as types so that we can treat them just as we do any other type. These types that we’ve defined are the outline to what we need. We still have the colour in, but we’ve got a framework ready to go. Lets define our function pointer variables using the types we defined above.

/* we need to define the pointers themselves so that
   the game loop can read them and the game module can
   write to them */
init_func game_init          = NULL;
teardown_func game_teardown  = NULL;
render_func game_render      = NULL;   
update_func game_update      = NULL;   
keyboard_func game_keyboard  = NULL;   

Simple enough. Now that we have these variables define (close-by to our game loop), we can write a game loop that will look a little something like this:

/* runs the game loop */
void run_game(void) {
    SDL_Event event;

    while (!game_finished) {

        /* process events here */

        /* if we've got a keyboard event process
           and we've got a valid keyboard handler */
        if (game_keyboard != NULL) {
            game_keyboard(event.key);
        }

        /* if we've got a valid update function, update
           the game logic */
        if (game_update != NULL) {
            game_update(frame, total);
        }

        /* if we've got a valid render function, render
           the game state to screen */
        if (game_render != NULL) {
            game_render();
            /* flip backbuffer to front */
        }
    }
}

This is psuedo code really. There’s a whole heap of infrastructure that you’ll need in order to make this work. You can see that only 3 of the functions we require are being are being used at the moment. We still need to get the init and teardown involved. The game module also needs a way to shift between game states. Thankfully, both of these functions come together in the one function:

/**                                                
 * Sets the handlers for the render, update and    
 * keyboard */                                     
void set_game_state(int state) {                   
                                                  
   /* if we have a valid teardown function to call,
      call it now */
   if (game_teardown != NULL)
      game_teardown();
 
   /* based on the requested state */              
   switch (state) {                                
      case GAME_STATE_INGAME:                           
                                                   
         /* assign the game handlers over */      
         game_init = init_game;
         game_teardown = teardown_game;
         game_render = render_game;               
         game_update = update_game;               
         game_keyboard = keyboard_handler_game;   
                                                   
         break;                                    
                                                   
      default:                                     
                                                   
         /* clear out any of the game state */     
         game_init = NULL;
         game_teardown = NULL;
         game_render = NULL;                      
         game_update = NULL;                      
         game_keyboard = NULL;                    
                                                   
         break;                                    
                                                   
   }                                               
      
   /* if we've got a valid initialization routine,
      call it now */
   if (game_init != NULL) {
      game_init();
   }
                                             
}                                                  

So, this function tearsdown the existing game state (if we have a state), and initializes if we initialize to a valid state. Easy!! Well, this has been just one possible use for function pointers. You can do so much, much more with them, but I thought I’d share my use of them here!