Programming

Last updates on Skald Engine:

Color utility functions

PixiJS handle colors by its int value (e.g., 0xFFFFFF), so I created a bunch of function to convert or manipulate colors in this format. Right now you can:

  • Convert color from/to RGB format (array, [255, 255, 255]).
  • Convert color from/to HEX format (string, ‘#FFFFFF’).
  • Convert color from/to HSL format (array, [255, 1, 1]).
  • Get the individual color channels (red, blue, green, hue, saturation, lightness).
  • Saturate a color by a given amount.
  • Desaturate a color by a given amount.
  • Covert the color to greyscale.
  • Lighten a color by a given amount.
  • Darken a color by a given amount.
  • Spin the color by the hue space by a given angle.
  • Blend two colors.
  • Tint (blending a color to white).
  • Shade (blending a color to black).

 

Utility for random generators

I also added a bunch of function to generate random numbers and other  stuff related:

  • `random.choose()` to choose a value from an array.
  • `random.inclusiveRandom()` which is similar to Math.random(), but it can include the 1 (i.e., it generates a number in interval [0, 1]).
  • `int()` to generate a random integer.
  • `polar()` to generate a number between -x and x.

Easing function and modifiers

I add more easing functions, a general bell curve and a gaussian shaped (using the normal distribution formula without the normalization term). So they can be used to generate interesting effects.

I also added two function that modifies the easing functions, one for mirroring the result of the easing (it repeat the ease function 2 times, but it invert the result of the second half), and one for repeating (pretty straightforward). I am still testing this format, so I don’t know if I’m gonna keep it.

Particle systems!

Added an initial implementation of particle system. there are some improvements to be made, but it is working pretty good.

Game config changes

I decided to remove the manifest as parameter of the game and added it as an item of the configuration. This should keep consistence among the API.

Additionally, I added a startScene and a preloadScene option, so the game can initialize and run a preload scene during the manifest loading, and start automatically the main scene when the game starts.

To help you in this initialization process, I also added a `start` event, triggered after the preload (if there is any item on the manifest), and added a default preload scene.

Scene stacking

I thought I could live without it, but I was wrong, so we have scene stacking now. Now you can add or remove scenes over the base scene (the one called with `play` method). The scenes are attached to the base scene, so if you remove the base, all scenes in the stack will die too.

 

Next steps

For the next alpha release, I want to add an event pool for event recycling (so we don’t have to create a new event instance everytime an event is triggered), and simplify the scene API. Right now the scene API is very limited and unintuitive.

Read more

About two year ago I started a game engine called Creatine, which was built upon CreateJS. I used this engine for quite some time, creating 4 jam games with it. However, I reached a point where I couldn’t improve Creatine anymore due to the limitations of CreateJS, in particular because CreateJS cannot use WebGL.

After some time without seeing anything about game development (I started in a new job, and hence my absence from this blog), I decided to start a new engine in order to enter make games for game jams again. This time, I decided to go with PixiJS, which is the status quo of 2D WebGL rendering in the JavaScript world.

But why I don’t simply use Phaser? Well, Phaser is undoubtedly a great project, with a mature code base and huge community, but I personally don’t like it. Its internal structure is confuse and I can’t understand properly (without spending a lot of time) how it works. Notice that, this is my opinion. I don’t like Phaser, but I am not saying you shouldn’t use it.

So I started Skald, my new engine, with some important pillars in mind:

  • The engine must allow me to create fast prototypes for my jam games, however, it must have a good architecture so I can create larger games with it if I want to.
  • Kind of consequence of the point above, the engine must allow me to reuse individual components, something similar to how Construct 2 works.
  • The engine architecture must be simple and intuitive, so anyone could understand what is happening under the hood.

Additionally, I would like that the engine be flexible enough so people can use it ignoring any part of it (e.g., you may rewrite how scenes and ECS works with relatively simplicity).

Right now Skald is on Alpha 2 – which means that I don’t recommend anyone to use it yet! – and the core features at this point are:

  • Game class with managers to control audio, inputs, scenes, devices, etc.
  • An extensible asset loader.
  • ECS objects. Not perfect or very strictly classic implementation, but it is working well.
  • Multiple and extensible audio systems. Right now with support to webaudio and html5 audio.
  • Support to 3rd-party plugins.
  • Scene transitions (similar to creatine).
  • Tweens, color and easing functions, and other utility functions and structures.
  • Most of the features of PIXI.

The final version of Skald won’t be released any time soon, but for the next alpha release I would like to add the following features:

  • Particles! Super important to have a particle system.
  • Scene stacking, so we can add, for example, a pause screen over the game without removing the game scene off the screen.
  • A better initialization procedure with a default loading scene (if there is anything to load).
  • Anonymous scenes and entities.

The project is hosted on github:

 

Read more

This was a long week. We had E3 conferences starting Sunday night (for Brazil) and ending on Tuesday, with a lot of awesome – official – announcements: Fallout 4 (my next love), Dishonored 2, Doom 4 and new IPs such as Horizon (which looks very promising), unravel and others. During the week I’ve been playing Fallout shelter also announced on E3, which is a good-looking and funny mobile game, but has the same problems of other farming games: there is no end and it gets bored fast.

In the weekend, I start-and-finished The Last of Us. Man! What a game! I love post-apocalyptic games with adult narrative. My only regret is that I didn’t gave more time to it – I had to play on easy in order to finish in this weekend because I won’t be able to play it for the next week, and if I have more than 1 week gap between my gaming sections, I just can’t continue from where I stopped.

C++

Even with all stuff that happened this week, I almost finished the Accelerated C++ book. Here are some highlights:

Maps

You can create ordered maps defined in <map> and unordered maps defined in <unordered_map>. Their usage is similar, but map is slower to add new items due to the ordering function. Usage:

map<string, int> dict;
dict['key'] = 132;

If you try to access a nonexistent key in the map, this key will be created automatically.

Maps return pair objects as iterators. A pair type is defined as pair<const K, V> and has the following attributes (to key and value, respectively):

auto pair = dict.begin(); // first key in dict
pair->first // key
pair->second // value

About double angle brackets

In cases like map<string, vector<int>>, the compiler may have problem to parse the statement (due to the >> symbol), so it is recommended to use map<string, vector<int> > (with the space). This seems to be a an old practice, I doubt that compilers nowadays still have such problems.

Default arguments

You can use default arguments on function parameters, like Python:

void my_function(int non_default, int default=123) { ... }

Notice that, the parameters with default arguments must be the last items on the list.

Constant methods

C++ has a mechanism to protect object from write access, for example when you define a function like:

void my_function(map<K, V>& writable, const map<K, V>& non_writable) { ... }

where non_writable is constant. When a parameter is defined as constant, C++ only allows to read public attributes and call const methods, such as:

void my_function() const { ... }

Brackets on const maps

Due to the constant restriction described above, constant maps don’t have the operator [ ], because this operator changes the map when the key doesn’t exist.

Generics/Templates

Generics are called templates in C++ and is used as:

template <class T>
T my_function(vector<T> V) { ... }

With stand-alone functions you don’t have to specify the template explicitly, e.g.:

int a = my_function(my_int_vector);

The typename keyword

C++ has so many features on it that sometimes the compiler simply doesn’t know what to do. For instance, when you try to define a variable within a subtype defined inside a template, like this:

template <class T>
Class MyClass {
  T::SubType * ptr;
  ...
};

In this case, the compiler interprets SubType as a static member of T, thus, it tries to multiply SubType with ptr, causing an runtime error. Because of this, you always must use the typename keyword, avoiding compiler mis-interpretation:

template <class T>
Class MyClass {
  typename T::SubType * ptr;
  ...
};

Reference: http://stackoverflow.com/questions/1600936/officially-what-is-typename-for

Iterator categories

There are 5 types of iterators. They are divided by what they can do (thus, which operators are allowed) with the object they reference. The categories are:

  • Input
  • Output
  • Forward
  • Bidirectional
  • Random access

Consult http://www.cplusplus.com/reference/iterator/ to see the table of all operations these iterators handle

Stream iterators

istream and ostream can be used as iterators:

std::copy(v.begin(), v.end(), ostream_iterator<int>(std::cout));

This piece of code sends all elements of a vector v to the console output.

Default constructor

To avoid double initialization when you create an object, you must use the constructor initializers:

MyClass::MyClass():
  attribute1(0), attribute2(0) {
    ...
}

Without this, C++ initializes the object attributes before the constructor body, and in constructor you probably will initialize the attributes again.

Pointers

Just a reminder:

  • &x returns the address of the object x
  • *x returns the object in the address x

Pointers to functions

You can create pointers to functions as:

int (*fp) (int) = my_function

This creates a pointer fp of a function that receives and return int values. Notice that you don’t have to use &my_function, because C++ convert functions automatically. The same can be applied to the usage (you don’t have to call (*fp)(2), only fp(3)).

You can also return a pointer to function from another function, this is a bit tricky because you have to use typedef to declare the pointer before:

typedef int (*fp) (int);
fp my_function() { ... }

To return a pointer to a function that uses template is trickier, you will have to define a struct with the pointer and return the struct.

Arrays

C++ arrays are pointers to values and, thus, they can be used as iterators:

int array[] = {2, 3, 4, 5, 6};
int sum = std::accumulate(array, array+5, 0);

Notice that, the variable array stores only the first pointer, thus *a == 2.

The index usage array[3] is equivalent to say *(array+3).

Because array is only a bunch of pointers, you don’t have the type_size directly, but you can use size_t from <cstddef>.

File streams

Using input or output files is pretty easy:

ifstream infile("input.txt");
ofstream outfile("output.txt");

The usage is the same as cin and cout.

Specific streams

Instead of cout, you can use cerr for error output (it is preemptive, so it prints the string when it is called), and clog for logging (non-preemptive).

New and delete

To allocate and deallocate objects manually, use new and delete:

int *p = new int(42);
delete p

int *p = new int[3];
delete[] p

If you allocate an object manually, it will only be deallocate manually too. You must be very careful to avoid memory problems!

Explicit constructors

C++ allow explicit and implicit object initialization:

int p(4); // explicit
int p = 4; // implicit

The explicit keyword prevents the compiler to use the wrong constructor due to wrong type conversions:

class MyClass {
public:
    MyClass(int) {}
    explicit MyClass(double) {}
}

This

Another reminder: this is a pointer to the object.

Copy constructor

Passing an object by value to a function, returning an object by value from a function, or simply assigning one object to another variable, implicitly copies the object. The constructor used in the case is called copy constructor:

T::T(const T&)

Rule of the three

To control all creation and deletion process of a class, you must implement at least the following methods:

T::T() // and other constructors

T::~T() // destructor
T::T(const T&) // copy constructor
T::operator=(const T&) // assignment operator

Citing the book:

Because copy constructor, destructor, and assignment operator are so tightly coupled, the relationship among them has become known as the rule of three: If your class needs a destructor, it probably needs a copy constructor and an assignment operator too.

Read more

I started this blog intended to post my developments and things that I’ve been learning during my path towards game industry. But, in general, I’ve only been writing tutorials and releases notes. Tutorials are pretty hard to do, because I like to create examples, format, make images, revise, and give details about what I’m writing about, and releases notes are only published when I have a release to announce. Both demand time, which I don’t have much lately. In consequence, my posts now have about 1-month gaps among them, and this isn’t good.

Thus, in order to keep my initial plan and write more frequently, I’m creating a weekly log, starting with this one, so I can register and tell what I’m studying or developing.

C++

In this post I will only talk about C++, which I’ve been studying almost exclusively.

First thing to say is, I’m following the book Accelerated C++ by Andrew Koenig and Barbara Moo. The book is pretty good, but I wouldn’t recommend for a total beginner. In my opinion you should learn the basic on other languages before getting this book – and language.

I am learning C++ in depth because I want to have some experience on the AAA industry, so this is pretty much obligatory. I understand that C++ is a pretty powerful language, but damn, this language is complex as hell. Notice that I’m not talking about syntax or readability, I’m talking about the concepts behind every feature of C++. There is a lot of redundancy (you can solve problems in a dozen of different ways) which seems to be caused by the performance concern (generally there is a super – but complex – parsimonious solution).

During the course of this book (and the followings) I will share more my thought about the language. For now, I’m going to give some highlights of interesting stuff on the book:

Abstraction

The author’s give a pretty good definition of abstraction right on preface:

We define abstraction as selective ignorance – concentrating on the ideas that are relevant to the task at hand, and ignoring everything else

Containers and size_type

Most STL containers provide a size_type type, which defines the appropriate type to hold the number of elements of a given container. For example, to move through a string, you should use:

std::string text;
std::string::size_type i;
for (i=0; i<text.size(); i++) {
  // stuff here
}

instead of:

std::string text;
int i;
for (i=0; i<text.size(); i++) {
  // stuff here
}

The reasons of that is because the number of elements in the container may be bigger than what int (or unsigned int, etc..) can handle.

The & operator

The & denotes a reference to some variable.

MyType a;
MyType b = a; // copies a
MyType& b = c; // a is a reference to a

As a good practice, you should use const to tell programmer when your function does not have intention to change the parameter value. E.g.:

void my_function(type& i_want_to_change, const type& i_dont_want_to_change)

The istream objects

istreams have a failure state that is kept until cleared, thus, if you put a string on to this:

int a;
std::cin >> a;

you won’t be able to read anything until you clear the stream:

std::cin.clear();

lvalue

Non-const arguments can only receive lvalues  (can’t be anonymous):

void my_function(Type& param) { ... }
my_function(4) // error!
Type a;
my_function(a) // ok!

The same is valid for return values.

Header files

You must avoid the use of using inside the header files, because your never know how the source file will use the variables. Avoiding using you avoid unnecessary conflicts.

Also, you must always use the preprocessor directives:

#ifndef UNIQUE_IDENTIFIER
#define UNIQUE_IDENTIFIER
// code here
#endif

because compiler insert the header code into the source files that import the header. Without it, the definitions would repeat several times causing errors.

Inline functions

Inlines functions are cool, they only exists before compiling. The compiler copy the body of the inline function where it is called. Use this to avoid the overhead by function calls.

Built-in exceptions

Import <stdexcept> to use the default error classes:

  • logic_error
  • domain_error
  • invalid_argument
  • length_error
  • out_of_range
  • runtime_error
  • range_error
  • overflow_error
  • underflow_error

using:

try {
  throw logic_error("Message")
} catch (logic_error e) {
  e.what(); // returns the message
}

Vector limitations

Vectors are optimized for random access and pushing/removing items from the beginning or end. Other operations are slow. The reasons for that is that vector move all elements back or forward when you change items at middle of the container.

Note: for fast insertions or removing, use list. However, list items can only be accessed sequentially.

Iterators

Iterators are cool, and in general are implemented as pointers (but not true all the time). You can use the following iterators:

container::const_iterator
container::iterator
container::reverse_iterator
container::const_reverse_iterator

each one for a specific situation: const to handle const values, reverse to reversed loops, iterator for common loops. For instance, to move through a string you can do:

for (auto it = my_string.begin(); it != my_string.end(); it++) {
  std::cout << *it; // print each string char
}

Overloaded function as arguments

You must avoid using overloaded function as arguments to functions, because the compiler can have problems to decide which function to use. Instead you should use an auxiliary function.

Static variables

You can use static storage class specifier on local variables inside functions. A static variable is created the first time the function is called and reused in subsequent calls.

Using functions as arguments

To create functions that receive other functions as parameters:

void my_function(type other_function(type2 param)) { ... }

A final note: the STL has A LOT of interesting things, for instance, check the algorithm package.

Read more

Last Ludum Dare I implemented a circular world for my game. I wanted to do that for some time, but before this LD I had no idea how to implement such a thing. Now I see that is pretty easy to do so. In this post I will explain how to create a circular world like the one I used in Democracy.

The beauty of a circular world is that we can work only with the radius of the planet, ignoring its position at the screen. So, first thing to do is defining our planet to a radius “r” (lets say 150px) and to screen position (0, 0). To center the planet in the window, you move the camera to (-w/2, -h/2) where w is the window width and h is the window height. You should see something like this:

step1

Now that we have an empty world, lets add some objects on it. All objects must have a position in this world, but this position isn’t the same of in screen, it is simpler. Suppose that at the point (0, r), what could be the north of our planet, is the angle 0°, then the east (r, 0) is 90° and so on, until the north point again. See the image below for reference:

step1-2

Now our object can be at positions like 47° or 270°, but we still must draw it into the screen. That’s pretty simple. Let’s say we have a sprite with (s_w, s_h), width and height, respectively. Then we set its screen position to (0, 0) and its anchor to (0, r+s_h). With this we have an sprite at the north point 0°, to relocate it to 306° we simply set its rotation as “sprite.rotation = 306” and done!

step2

White box is at north (0°) and the red box is at 306°.

Additionally you can also set the height of the object in that world (the distance of that object to the ground). To put a cloud at 30px high, you simply add the height to the sprites anchor, such that anchor is (0, r + s_w + height):

step3

Sometimes you may find useful to convert the world position, now (position, height), to the screen position. For example, to add some particles. So, to find the screen coordinates (x, y) of an object at (position, height) you do:

angle = radians(position);
x = sin(angle) * r + height;
y = -cos(angle) * r + height;

Contrarily, when you want to convert the screen position to world coordinates, for example to find where the mouse is pointing. You can do:

position = degrees(atan2(mouse.y - camera.y, mouse.x - camera.x));
height = euclidDistance(mouse.x, mouse.y, camera.x, camera.y) - r;

Simple right?

Let me know if you found this article useful, or if you have an alternative way to do that, or yet, if you created some circular world based on this. Cheers!

Read more