Fiddling with the HTML5 Canvas

I’ve been doing some experimenting with HTML5’s Canvas element. After some brushing up on Javascript, I started working on a couple of proof-of-concept scripts to see how well the platform can be used.

I have not been disappointed. Javascript, as a language, has evolved quite a bit since the old days of document.write(), with DOM editing as the one true way to manage dynamic content. Having said that, I find that Javascript is still quirky and flawed.

Here’s a short script I wrote (fewer than 160 lines) that animates a girl wearing the traditional Oktoberfest outfit. She walks back and forth within a given 500×500 area. This is not a video, your browser is doing the math to update her animations and move her around in realtime!

You should be able to see the demo just above this message, if you have a fairly recent browser that supports the HTML5 Canvas element. I was actually surprised about how mainstream Canvas support is: Chrome ≥ 22, Firefox ≥ 15, IE ≥ 9; Opera ≥ 12.1; Safari ≥ 5.1, Android ≥ 2.1 and Safari Mobile ≥ 3.2, all support this new element.

The animation atlas was taken from this cool website with resources free to use. The script “slices” the image, taking the appropriate frames to draw depending on the time simulation and the direction the character is walking towards (left or right).

Sprite animation atlas.

Sprite animation atlas.

Despite Javascript’s gotchas, with the addition of the HTML5 Canvas element, it’s become a nice tool that allows hacking together some easy 2D (or even 3D!) graphics and display them in a browser.

See you next time!

Function Objects using Variadic Templates in C++11

One of the biggest features introduced in C++11 are lambda expressions. Lamba expressions (or “lambdas”) are a powerful mechanism that allows defining functions “on-the-fly”. These can be stored in function objects and then be used by an object that doesn’t want to reveal its internal implementation, as well as to perform tasks on a parallel thread.

I was wondering how function objects could be implemented using other constructs of the language, mostly to see how much the language had to be changed in order to accomodate them. In this post I will show how to implement function objects using nothing but C++11’s variadic templates.

Variadic templates were introduced in our previous post in this C++11 series. This post will help pave the way for us to move into the more advanced topic of lambda expressions and std::function objects.

Function Pointers in C

As far as I can tell, C has always had functions as first-class citizens. Although their syntax is vastly different from the way one declares variables of other types, you could always define a variable that can be assigned a pointer to a function.

#include <stdio.h>
void print_number(int number)
{
    printf("Argument is: %d\n", number);
}

int main(int argc, char* argv[])
{
    void (*f)(int);  // f is a variable that can 
                     // store a pointer to a 
                     // function that receives 
                     // an int an returns nothing.
    f = print_number // legal.

    f(1024);         // calls print_number.  

    return 0;
}

Because C is a statically-typed language, we must be very careful with the types we declare f with, otherwise the assignment may be deemed invalid by the compiler.

Another problem is that the syntax can be cumbersome to remember and handle. Notice how the name of the variable is declared within the associated types.

Function Objects in C++

Unless you were using boost, C++ never had its own version of function objects until C++11. Programmers had to rely on the traditional C construct or write functors, classes that implement operator() and allow mimicking a function’s behavior.

Unlike C function pointers, functors are more readable, but we need to declare a class and implement operator() inside it. It’s much more verbose.

C++11 introduced the standard std::function type, which allows encapsulating a function declared by lamba expressions (or by other means). In production code, you will most certainly want to use std::functions. In this post, however, because of academic interest only, we’re going to exercise C++11’s variadic templates by implementing a generic function wrapper object called alg::function.

alg::function

Using variadic templates, it’s very easy to implement a simple function wrapper capable of handling any function type. I’m going to implement my solution using C function pointers. Remember: in C++11 production code, you will never do this.

namespace alg
{
    template <typename R, typename... T>
    class function
    {
        public:
            function(R (*f)(T...)) { _f = f; }
            R operator()(T... args) {return _f(args...);}
		
        private:
            R (*_f)(T...);

    };
}

And that’s all there is to it, really. Let’s go over the code.

I declare the class alg::function as a template that is to be instanciated by two parameters: a return type dubbed “R” and a list of types which I will refer to as “T”. The list of types can be empty, the return type is mandatory.

alg::function objects will have a single private member that is declared to be a pointer to a C function that returns a value of type R and receives the list of argument types T.

The only two additional methods that we need are: a public constructor that receives the function to wrap, storing it, and operator(), which will let us call the function. Notice how easily we can unpack the arguments when we call _f.

Instancing Examples

Let’s see it in action!

These samples illustrate the basic idea without complex data structures. It is certainly possible to pass alg::function objects around as the first-class citizens that they are, as well as passing-in and returning arbitrary C++ objects and structs from these wrappers.

The only limitation is the fact that we don’t support const parameters. Adding support for them would require tweaking the alg::function class a bit more. We leave this as an exercise to the reader.

A single function that receives an int and prints it:

void fun(int arg)
{
    std::cout << "hello from fun! (arg=" 
              << arg 
              << ")"
              << std::endl;
}

int main(int argc, char* argv[])
{
    alg::function<void, int> f(fun);

    f(0); // prints "hello from fun! (arg=0)"
}

A function that receives no parameters:

void fun2()
{
    std::cout << "hello from fun 2!" << std::endl;
}

int main(int argc, char* argv[])
{
    alg::function<void> f2(fun2);

    f2();  // prints "hello from fun 2!"
}

A function that receives two std::string instances and prints them together:

void fun4(std::string msg1, std::string msg2)
{
    std::cout << "hello from fun 4! (concat=" 
              << msg1 << msg2 
              << ")" 
              << std::endl;
}

int main(int argc, char* argv[])
{
    alg::function<void, std::string, std::string> f4(fun4);

    f4("hello, ", "world!"); // prints "hello from fun 4! (concat=hello, world!)"
}

Conclusion

Variadic templates offer a lot in terms of flexibility and allow us to extend the language even further than it was possible before. Remember, these examples are just food for thought. In C++11 production code, you will most certainly want to use std::function objects and lambda expressions.

See you next time!

Other articles in this C++11 series

Posted in C++