Tuesday, 21 January 2014

12 javascript optimizations tips


Urban Galaxy Online's client is written in pure javascript utilising modern API's such as WebGL, websockets, HTML audio and CSS3.

The client is written on thousand lines of javascript, most of them executing on each frame to update the game's logic and handle the continuous communication with the server. Every single line of code may have implications on the browser performance, affecting the game's framerate and the user experience.

The initial implementation of the client was... slow, especially on javascript engines other than Google's V8. The performance on Google Chrome was adequate at the time the client was built, but.. it suffered alot on Firefox and Safari. This changed when Firefox 22 was released, which featured a HUGE speed boost making the performance to be on par or even better compared to Google Chrome.

By applying a couple of optimization tips we managed to double or triple the performance of the javascript execution engine making the game play smooth on the most popular WebGL-enabled browsers.

This blog post is about revealing a couple of hints applied to the javascript code to improve framerate.

1. For loop optimizations

Replace the classic for loops with while loops.


for (var i = 0; i < list.length; ++i) {


var i = list.length;
while(i--) {

2. Loop unrolling

There are special cases where loops can be unrolled to reduce for-loop overhead when the list length is fixed and known.


for (var i = 0; i < 3; ++i) {



3. Caching properties or arrays

Objects can contain objects which might contains objects and so on. It is very important to cache a property when it is accessed multiple times within a loop. Same goes with multidimensional arrays as illustrated in the example below.


var grid = [][];
for (var x = grid.length - 1; x >= 0; --x) {
  for (var y = grid[x].length - 1; y >= 0; --y) {


var grid = [][];
var x = grid.length;
while(x--) {
  var column = grid[x];
  var y = column.length;
  while(y--) {

4. Cache globals

When a variable is declared outside the scope of a function then, when it is accessed, it is looked up until the root window object, in order to be found. You'd better cache it locally.


var global = 5;
function foo() {
  var i = 100;
  while(i) global += 10;


var global = 5;
function foo() {
  var i = 100, local = global;
  while(i) local += 10;
  global = local;

5. Use prototypes

Use prototypes for frequently allocated objects.


function myObject(data) {
  this.foo = data.foo;
  this.bar = data.bar;
  this.doSomething = function() {


function myObject(data) {
myObject.prototype.init = function(data) {
  this.foo = data.foo;
  this.bar = data.bar;
myObject.prototype.doSomething = function() {

6. Optimize Math

Sometimes you may get a performance boost by replacing the Math.* functions with inline operations, such as:

Math.round(X)  ->  ~~(0.5 + X)
Math.floor(X)  ->  X|0

Also you may cache some numbers such as:

Math.PI * 2    -> var UG_PI = Math.PI * 2
Math.PI * 0.5  -> var UG_PI_HALF = Math.PI * 0.5

or some math functions

var UG_PI_DIV_180 = Math.PI / 180.0;

var UG_180_DIV_PI = 180.0 / Math.PI;

function deg2rad(degrees) {
  return degrees * UG_PI_DIV_180;


function rad2deg(radians) {

  return radians * UG_180_DIV_PI;

7. Reuse objects

Garbage collection may have a critical hit on your application's performance. Cache frequently used objects as proxies that can be reused. For example:


function swap(vector1, vector2) {
  var temp = new Vector3();


var proxy = new Vector3();
function swap(vector1, vector2) {
  //avoid memory allocation and garbage collection
  var temp = proxy;

8. Inline function calls

Instead of calling a function inside big loops, try to inline the function within the loop. This way, you have a performance gain by avoiding the overhead of the function call.


function copyVector(source, target) {
  target.x = source.x;
  target.y = source.y;
  target.z = source.z;
var i = ships.length;
while(i--) {
  var ship = ships[i];
  copy(ship.previous, ship.next);


var i = ships.length;
while(i--) {
  var previous = ship[i].previous;
  var next = ship[i].next;
  next.x = previous.x;
  next.y = previous.y;
  next.z = previous.z;

9. Minimize closures

Closures are one the most powerful and awesome features of the javascript language but making overuse of it can decrease performance, messing alot with your garbage collector.


setTimeout(function() {
}, 1000); 


function timoutCallback() {
setTimeout(timeoutCallback, 1000);

10. Touch the DOM as less as possible

One of the most important performance hogs is altering the DOM, either by changing the DOM structure or by modifying the CSS. For in-game HUDs that need to change frequently, try to cache their status in javascript variables and then change it.  On the example below, each ship (or character) has an HTML element attached to display its name on top of the ship object in 2D space. When the ship is outside the camera viewport we need to hide it and display it each time it gets inside.


if ( ship.isInside(viewport) ) {
else {


if ( ship.isInside(viewport) ) {
  if (!ship.visible) {
    ship.visible = true;
else if (ship.visible) {
  ship.visible = false;

11. Set CSS style directly

Continuing the previous example, lets say that need to set the position of the ship's name element on each frame. jQuery is neat for changing the CSS of HTML elements, but when we need to touch the DOM many times per frame, the jQuery overhead may be important. So... for frequent changes, use raw javascript.


var i = ships.length;
while(i--) {
  var el = ships[i].el_name;
    top: Y + 'px',
    left: X + 'px


var i = ships.length;
while(i--) {
  var style = ships[i].el_name.style;
  style.top = Y + 'px';
  style.left = X + 'px';

12. Do not blindly use external libraries

Urban Galaxy is making use of some really neat frameworks, such as underscore.js. Underscore provides the _.each function to iterate through objects and lists. Although convenient, it introduces a perfomance hit due to the function callback. Use a while loop instead.  


_.each(list, function(item) {
}, this);


var i = list.length;
while(i--) {

Wednesday, 26 June 2013

Designing a game UI with HTML and CSS, Urban Galaxy story

Recently we have made an enormous update on our game by releasing the new html5 client.

By saying html5 client one would mostly think about the 3D engine that replaced the previous one but the truth is that the whole underlying structure and code that supports the new client tries to get the most out of all the involved technologies.

In this post we will talk only about a really small part of the new client that is the actual user interface implemented for the in-game menus and interactions.

Story so far

In order to have a complete documentation of how the UI progressed - along with the game - in this section we will present all the steps that led us to where we are right now, so feel free to skip this.

The development started a long time ago and the client was in JMonkey until very recently. In the beginning of the project the scope was to give it a retro look closer to Fifth Element which was a great inspiration in all aspects of the game.

The initial design of the UI was mostly orange, with blue buttons....It was not beautiful, actually ugly, but it was very functional! The initial UI more or less set the various UI elements positioning. Designing the UI for the first time we had to solve one basic balance problem: the game was running in 800x550 dimensions only so we had to make the UI non intrusive to the gameplay and keep the player's view as clear as possible AND display all the useful info in the UI. What we finally came up is shown below

The design is not that great but again all the elements are there! Keep in mind that the look and feel we initially wanted was more retro than futuristic.
The different elements that we came up with were static with fixed sizes and positions (such as the player status element, the shortcuts area and the map) and with varied size and positions (inventory, ship ghost, quest window etc.).
We went on with this UI for a long time and gathered useful feedback to use in our next UI shown below.

In this version there are many changes and optimisations. The thought is always the user available space and functionality. What we have done in this version is group all the player related data in the lower bar along with the shortcuts, adding more info about the current user XP (little bar below shortcut #4). That alone released a lot of space in the upper left corner! Moreover we squished a bit more the selection window (upper left) and all the popup windows. And hey!! we decided to go with the blue as a more futuristic color. Also, we replaced rounded corners with lines to give a more crisp look.
This was the final version of the UI that you probably have played in the java client.

Initial thoughts and ideas

Having already experience from the previous UI we tried to improve and think all of the flaws and problematic areas in hand. Since we are talking about html5 client, all the UI is 100% pure html (not that pure actually since some elements are using raphael.js and most of the layout is handled through backbone with underscore templates!!).

Taking into account the above let's say "directions" we came up with the specifications:

  • Utilize responsiveness of the css/html elements to create more room for the user to see the action, we had to make all menus and ui-elements responsive so that they would adjust to the available space.
  • Make some of the ui-elements interactive in their functionality, so that the user can contract/expand them
  • Implement the whole interface so that it can be easily enhanced, altered and re-organized in the future.
During the whole process we thought of our game as a stand alone game and never thought of it as a browser game so as to avoid design and idea compromisations such as "it's just a website with a game skin", "that <div> can't do that stuff" and more like this that would result is something less fancy.

We wanted the design of the UI to reflect something futuristic with simple lines. We also wanted to included only what the player could really use and avoid any noise in the interface. Playing with the elements size and color also helped in grouping and making something more important.

Ideas on customisation

Since we will be working with HTML and CSS we have thought the idea of customised UI. Both HTML and CSS are well known technologies, so it would be a waste to not adopt this to our design. The idea is that the whole UI - eventually - be fully customisable in terms of elements/windows positions and sizes as well as colouring and fonts.
That in the end will allow each player to customise the UI to his liking and make it familiar to his own play flow.


After setting up the specifications and the rules we started prototyping the UI. In the game UI there are two main different areas of interaction, the actual interface that includes all the panels and the windows that the player uses and the hidden interface used to interact with the scene of the game that includes the  floating names that follow each ship and the interaction elements with all the active elements in the scene (enter a shop, enter a portal, hover a ship and select it etc).
So the initial layout of the UI and interactions is as follows:

  1. Canvas element that hosts the visual aspect of the game, is set in the bottom layer
  2. In-game hud interface that is interacting with the canvas elements and sits on top of the canvas
  3. Game UI with all the windows and panels sitting on the top layer
The whole player interaction involve layers 2 and 3.

Since we wanted to properly support customisation we had to include this capability from the beginning of the development. So in the backend we split the styling of the UI in CSS that can be customised and other that are not customisable and contain more generic rules that need to be applied in any case or as a fallback. Getting valuable info from css frameworks such as bootstrap we break the css rules and files in two groups:
  1. A group responsible for general positioning and ordering rules that are to be applied in any case
  2. A group responsible for the actual styling and actual positioning  of the elements
So in group 1 a css rule is looking like that:

#qlist-preview {position:absolute;display:block;overflow:hidden;}

While in group 2 the css rule for the same elements looks like that:

#qlist-preview {margin-top:255px;font-family:AldoSemiBold;font-size:1em;text-shadow: 0 0 1px rgba(0, 0, 0, 1);width:15em;margin-right:0.5em;}

In that way we try to separate the functional positioning and elements ordering from the styling of those elements. So the first group mainly contains all the basic styling that must be equal in all cases and the second one is a certain styling of the UI (customisation). Those CSS groups are applied to both UI layers.

Layer 2: In-game hud interface

The UI layer 2, in-game hud interface, should extend to the entire game area so it is of width/height 100% with a z-index greater than that of the canvas layer, to sit on top of it.

The hud interface contains elements that are absolute positioned and controlled by javascript to animate or fix their position and display.

Layer 3: Game UI core

The UI layer 3, actual game UI, is also absolute positioned and with width/height 100% and z-index greater that that of layer 2. This layer contains the core of the game interactions. Since we wanted customisation from the start we created some elements for better organisation of this aspect. Below is a graphic image showcasing the basic break down of the game UI layer.

So in the above image you see that we have defined 5 areas for UI elements placement:
  • Full area is placed on top of all other elements and has width/height 100%, used for all the popup windows and in general elements that are not shown by default in the UI like messages and info text on XP acquired etc. All UI elements placed in here are absolute positioned.
  • bottom,left, right and top areas are used as placeholders for docked elements of the UI. In general we try to keep any elements shown in these areas not overlapping with each other. In here we implemented additional positioning classes to align docked UI elements to the sides and the middle of the area. The idea here is to allow the player/user to customise the elements by dragging them along each area and snapping them.

Overview of a window container

So far we have defined the basic placement of the whole UI and the positioning of the UI windows. Here we will talk about the HTML and CSS of an actual window. In order to allow windows reposition we had to make a common base that all UI can share. In that way we could easily move a docked window to a floating position and readjust only the CSS of that window. The common base is as follows:

  1. A <div> as the window container, since most of the UI windows are unique an id is added on this level to distinguish each unique window (#playerbar, #chat, #map, #shop etc.). This element also defines the width and height of the window. The size is defined by the position of the element on an area (docked, left or right, top or bottom).
  2. HTML elements for styling using 4 <divs>, one for each corner of a rectangle (.top.left, .top.right, .bottom.left, .bottom.right). Using the position of the UI window we change the styling and size of those divs. Those elements don't cover all the possible needs of a window style but we heavily utilized the :before and :after pseudo rules to expand our toolbox. We had to add these styling elements because we couldn't handle a specific case where we have corner borders and transparency applied in almost every window.
  3. A <div> element absolute positioned with width and height of 100% where we put all the content of the window.
In some windows some extra HTML elements are used to display a title, a close option etc.
We will surely need some expansion of the basic window structure when we actually try to implement a different styling to the UI, but so far we didn't need to change the window container.

Minor "issues"

Since the UI of a game is quite dynamic in order to fulfill various needs are covered by inserting new elements in the UI. So more elements means expanding the DOM of the page. In a normal web application where the new DOM elements contribute to the UI and the application itself there is no problem....but....since we are talking about a webgl game where the page already contains a ton of 3D assets and information in a whole different level one should try and minimize the DOM as much as needed. A.k.a. better put that extra squeeze of browser/memory power on the canvas than on DOM elements manipulation and ordering and staff...
In that direction we use whenever possible the pseudo elements :before and :after and also avoid extra elements addition to the DOM when it can be avoided, as in the Shop were you can have a never-ending list of items. In the specific example each element contributes only one li element to the DOM and the slots are a repeated background on the ul element of width/height 100%.

Another issue we needed to address was the anchors. We thought that an anchor with an empty href will still interrupt the user experience with the link helper showing on the bottom of the browser (hover here for an example). So instead we used a span with an anchor styling to simulate pointer functionality.

Future work

More or less this is the current status on the UI. We can't say that we have something final, but we surely can say we have something functional. The transition from Java to html was worked quite successful and we think that we used some of the benefits that html brings on the table.
For sure this version of the UI is not final, like we said, and we already have some improvements and extensions in mind for the future. We would really like to create our own font-face to replace the static images that we currently use, making the interface more flexible and adjustable. Another idea we need to work on is the actual implementation of the customizable UI; meaning we have to create a proper framework and supporting css rules/files to help you customize the UI to your needs and preferences. Expand the responsiveness of the UI to accomodate even smaller screen sizes (the current cap is 800x550 actual game size).

As a conclusion, working with HTML and CSS to implement a game user interface was a great experience! The instant feedback you get from your design is liberating. One can freely test whatever his own skills allow him and sky is the limit! The restrictions that CSS and HTML bring to the table are easily surpassable and - top of it all - really really well documented and troubleshoot!! HTML and CSS are quite living languages that are actively evolving day by day, if you combine that with all the great capabilities and robustness of the modern browsers we see no reason to not walk this path.

Rock on!!

Thursday, 6 June 2013

Urban Galaxy 3D assets - part2:Smaller fillers

In the first part we talked about the main set of assets that define the level. We described the process that led as to the final form of the buildings used in the levels and how we finally came up with what we have now, that is building sets with the ability to fit perfectly with each other.

In the second part we will talk about the extras, smaller assets that add more variety and character to the levels. This is actually the spice, that extra 20% that makes the difference (http://en.wikipedia.org/wiki/Pareto_principle).

GIG company garage
A beauty shot of a garage filler placed on top of a building

Starting thoughts

Having ready the main buildings layout in the level it was time to start developing additional fillers, that was a no-brainer. At the beginning fillers started as small 3D assets that one could find in a city, some street lights, traffic lights, flora elements, some shops. The whole idea behind was to think of fillers that would add some motion to the unmoving scene, bringing more life to the city.
The principle behind developing those fillers was yet again reusability. This time the specs were forced due to the presence of buildings that most of the fillers are attached to as well as from the hard specifications of those buildings (since the actual building had 500-700 polys and a 512x512 map, no filler would get larger specs that those).
Again the fillers were produced in sets and been grouped that way in texture, so instead of having 5 or 6 smaller textures for a set of traffic fillers you had only one shared with various other city assets in a larger texture. That was a good decision as more assets good derive by reusing the same texture on a different mesh - actually we still are adding more assets even to the first filler texture we created -.

Hands on

Ok, so what exactly is a filler set right now and how it is broken? A filler set is defined by a basic texture of 512x512 dimensions and a set of 3D meshes that are mapped on this texture. The basic thought here is reusability and small size. Each mesh tri-count varies between 130 and 450 tris. We try to be proportionate tri-count to asset size (more tris->bigger asset). Each filler set has approximately 10 different meshes of various sizes but as we move on more assets are added to the filler set.
What's implied above is that the base of a filler set is its texture. If that is carefully designed it can accomodate a long list of different assets on it. Currently on Urban Galaxy the filler sets are organised thematic.

Some assets from city fillers set

Lets take for example the basic city fillers set containing lights, power stations, antennas, signs, traffic lights. When we started the game development this set contained only some city lights and signs with most of its texture space unused. As we moved on we started adding similar assets to the filler set and currently the texture is fully used.

The city filler set texture right now.
There are 12-14 different assets on the set and more can easily be added as we come up with more ideas. 
When you design a texture that is to be used by various 3D meshes as filler assets you must keep the texture as generic as possible to avoid repeatability on distinctive elements in a level. As you can see in the above texture the repeatable elements are the sign letters "CITY ALTITUDE LIMITS" and the model name on the vertical train.

Update/Upgrade  iteration

Playing around with all those fillers in level design we created a set of levels. The levels were great but...they were still not that different. Navigating those levels and watching the various neighbourhoods from a far distance revealed the problem. Reusability of buildings and fillers turned against us as repeatability. Having only big assets, buildings, and small assets, smaller fillers, left a gap in the middle asssets area. In order to address this problem we took two steps, actually building bigger assets using filler textures and introducing building add-on fillers using the actual building textures.

Current state

Urban Galaxy, animated vertical train with some traffic in the background

Having a rich set of asset variations to create fancy and distinctive levels we started building up the levels of the game. The evolution of the assets as well as the underline engine can go nowhere but up. This means that we always keep an eye for new ideas and things that will make Urban Galaxy levels more rich and alive. Currently where we stand we have animated fillers, introduced particles on fillers (aka smoke), created filler ships to simulate traffic inside the level. Some future thoughts include a working horizontal train that goes around the level, some more fancy ads, under-construction area assets....and more to come!

We would love to hear more thoughts and suggestions on assets directly from you or even get more technical on some matters.

Thursday, 30 May 2013

Urban Galaxy 3D assets - part1:Buildings

Creating 3D assets to populate levels in Urban Galaxy included some really big challenges. In this post we will try to display the whole think and development process that led us to the current assets used in-game.
The 3D assets are comprised of two different parts that we will talk here, those are the actual 3D mesh and the textures applied on that mesh. Those two parts communicate with each other through the UV mapping of the mesh surfaces on the texture. Sorry for the obvious disclaimer but it had to be written!

First come the hard requirements!

Here we are talking about file requirements as well as size and "beauty" requirements. The fact that the game is a browser game implies that we want it to load fast. That translates to:
  • as few polygons in the mesh *
  • as smaller file size for the texture(s) *
(* as possible!)

Apart from the platform specs we wanted the assets to look really beautiful and match at the scale of the game - each level is a city block of approximately 1,2Km by 1.2Km. So here comes an implied requirement, the buildings need to look large and really really tall!! (not to mention great looking from far and closeup).

Then come the soft requirements

Taking the above a step further, since we wanted the whole level to load fast we had to think of a way to reuse as much of the assets as possible, but always in a way that the repeat would not be that obvious.
Since the majority of the assets are mostly fillers, the whole styling of the assets should be unobstructive to the gameplay if the asset does not affect the gameplay, in other words DO NOT F** WITH THE PLAYER'S VISIBILITY OF MOBS, OTHER PLAYERS AND OTHER ACTIVE ELEMENTS!!(mind the caps). In the same category of requirements but reversing the effect, the active assets must popup for the player but not spoil visually the whole setting.

Getting hands dirty

Having setup the requirements we started creating assets, setting off with a simple square building. The challenges of creating the first building ever were:
  • Texture should repeat in order to cover as much mesh space as possible
  • In order to keep the mesh in normal polycounts certain parts of the mesh should have different scaled texture than others
  • A special texture space should be used to add details to the model in player's zone (the zone in which the player can fly in game)
After alot of trial and error we decided that the final texture size for the buildings would be 512x512. The texture space on that was split more or less:
  • 70% texture space for high detailed large chunks (walls with windows)
  • 15% texture space for low detailed large chunks (walls standing at heights and lows outside the player zone)
  • 15% various smaller details used to add closeup details and variation on the final asset.
Breakdown of the first-ever building texture, closeup details got more detailed in the latest building sets
The whole idea was to utilize the final texture to apply it on various building meshes with different shapes.....and that was good!! So far what we have accomplished was to define a set of buildings that share the same texture.
On the front of mesh polycounts we found the balance of simple mesh and complex result standing at 500-700 tris per building. That was due to the fact that we had to add some kind of details in the player zone and also the outline of each building should be as unique as possible.
Finishing our first buildings set and starting to rough out a first level another problem was visible: having only single block buildings was restricting the variations of level layout - plus it was reeeally ugly! -.
So we had to think of a way to add more variety to the level. What we finally came up with is a way to "build" building blocks more or less like Lego, where each building perfectly aligns to the one next to it.
A chunk with the seam shown in red, all building chunks share the exact same seam shape so they perfectly fit with each other.
Going one step further with that idea we adopted a standard for building chunks seams that allows various buildings from various sets to be perfectly aligned and create a large building block. To give more flexibility to the larger blocks we implemented 3 basic building types/variations: a straight building, a corner building and an inverse corner building. Using these we can create a large variety of shapes for building blocks.

Here ends the first post covering the 3D assets, in the second part we will talk about lesser 3D assets aka fillers.

Friday, 24 May 2013

On homegrown tools

The level editor

In order to build Urban Galaxy Online we had to create a set of tools to make our life easier as developers, so we decided to invest alot of our time to create a simple level editor so that our level designer could put the pieces together as fast as possible.

We decided to build our tools on Java and we chose jMonkey Engine as our foundation library. After a couple of months we ended up on our level editor looking like this:

Urban Galaxy Editor

We chose the grid based approach to create game districts as easy as possible using building fragments connected together like lego parts.

Within the editor you can set some generic properties such as the level size, name, pvp flags etc. Then, using brushes you can actually "paint" the level using building blocks.

Apart from the level itself, you are able to position mobs and NPCs inside the level and adjust their positioning and patrol path.

The admin pages

The level editor is actually part of a bigger set of tools called "admin pages", a web based portal to edit everything that has to do with the game, in a distributed manner that works on top of a cloud. The admin pages were built using Codeigniter PHP framework and the Bootstrap library for the interface.

From the admin pages, you can edit all aspects of the game, including items, weapons, mobs, quests, events etc. While developing the game several "needs" emerged for helping tools. Those tools will be added into the admin pages. Currently we have developed such a tool to help us visualize the quests per class. We also plan to develop such tools to help in balancing the in-game economy.

Each graph represent the quest sequence of a career, since this is a first version of the tool there are overlapping errors

Behind the scenes

The level editor is running within the admin pages as well using the Java applet technology of  jMonkey Engine and LWJGL.

We built the user interface of the editor from scratch using the following components of the JMonkey Engine 2.0:

  • BitmapText
  • Textured Quads
  • Orthographic viewports
  • Key and mouse event listeners
All the 3D primitives are loaded using JMonkey's OBJ loader and then saved to a custom XML file format describing the structure of the level.

Monday, 13 May 2013


A few years ago...

our indie team, passionate about computer games, gathered in a quest for "Let's make our own game". Ideas came and go, all of them around a set of goals:

  • Find a niche market
  • Do not make another copy of what is out there
  • Make it playable through the web
  • No installations, instant play
  • Find a financial model that would make the game sustainable
... and let there be Urban Galaxy Online.... a browser based MMORPG set in a unique world.

So, an MMORPG with flying cars in a cityscape? Hmmm, looked like we were the first to do something like that, so it sounded like a good idea, getting inspired by sci-fi movies such as Blade Runner or the 5th Element.

Next step, lets find a cool universe around it, that will set the base for cool/expandable stories on top of it... and let there be Anassin, the capital city of Dual Solar Empire, the place where the game takes place.

After setting the gameplay goals and the basic background story, it was time to start coding our tools... (to be continued)