Sunday, April 29, 2012

Programming language inventors on twitter


If I've missed any others, please let me know via the comments at the bottom of this page, and I'll update the list.

I've added a twitter list with all of the above included here - twitter.com/dodgy_coder/prog-lang-inventors.


Programming Languages A-Z


Here's a list of programming languages in alphabetical order. Once again, if I've missed any significant ones, please let me know via the comments at the bottom and I'll update it.



Monday, April 9, 2012

Scalability lessons from Google, YouTube, Twitter, Amazon, eBay, Facebook and Instagram


I've gathered together in one place a few lessons in scalability from seven of the most highly trafficked websites around. I've grabbed this primarily from various articles on the excellent High Scalability Blog and have summarized the main points from each company below.

Here are some common ideas I've noticed across all seven companies ...

  1. Keep it simple - complexity will come naturally over time.
  2. Automate everything, including failure recovery.
  3. Iterate your solutions - be prepared to throw away a working component when you want to scale it up to the next level.
  4. Use the right tool for the job, but don't be afraid to roll your own solution.
  5. Use caching, where appropriate.
  6. Know when to favor data consistency over data availability, and vice versa.


Google

Reliable storage
Reliable scalable storage is a core need of any application. The Google File System (GFS) is Google's core storage platform - its a large distributed log structured file system into which they throw a lot of data. Why did they build it instead of using something off the shelf? Because they control everything about it, and it's the platform that distinguishes them from everyone else. From GFS, they gain: high reliability across data centers, scalability to thousands of network nodes, huge read/write bandwidth, support for large blocks of data which are gigabytes in size and an efficient distribution of operations across nodes to reduce bottlenecks.

Infrastructure as a competitive advantage
Google can roll out new internet services faster, cheaper, and at scale at few others can compete with. Many companies take a completely different approach by treating infrastructure as an expense. Each group will use completely different technologies and there will be little planning and commonality of how to build systems.

Build applications on top of a platform
An under appreciated advantage of a platform approach is that junior developers can quickly and confidently create robust applications. If every project needs to create the same distributed infrastructure you'll quickly run into difficulty because the people who know how to do this are relatively rare. Synergy isn't always crap. By making all parts of a system work together an improvement in one helps them all. Improve the file system and everyone benefits immediately and transparently. If every project uses a different file system then there's no continual incremental improvement across the entire stack.

Automation and recovery
Build self-managing systems that work without having to take the system down. This allows you to more easily rebalance resources across servers, add more capacity dynamically, bring machines off line, and gracefully handle upgrades.

Create a Darwinian infrastructure
Perform a time consuming (CPU bound) operation in parallel and take the winner. This is especially useful when you have spare CPU capacity but limited IO.

Don't ignore the Academy
Academia has a lot of good ideas that don't get translated into production environments. Most of what Google has done has prior art, just not prior large scale deployment.

Consider data compression
Compression is a good option when you have a lot of CPU to throw around and limited IO.


YouTube

Keep it simple
Look for the simplest thing that will address the problem space. There are lots of complex problems, but the first solution doesn’t need to be complicated. The complexity will come naturally over time. Choose the simplest solution possible with the loosest guarantees that are practical. The reason you want all these things is you need flexibility to solve problems. The minute you over specify something you paint yourself into a corner. You aren’t going to make those guarantees. Your problem becomes automatically more complex when you try and make guarantees - you leave yourself no way out.

Cheat: know how to fake data
The fastest function call is the one that doesn’t happen. When you have a consistently increasing counter, like a view count, you would need to do a database call every update. Or you could do a call every once in awhile, and update by a random amount in between - people will believe it’s real. Know how to fake data.

Jitter: add entropy back into your system
If your system doesn’t jitter then you get thundering herds of people all requesting the same resource at the same time. For a popular video, they cache things as best they can. The most popular video they might cache for 24 hours. If everything expires at the same time, then every machine will calculate the expiration at the same time. This creates a thundering herd. By jittering you are saying randomly expire between 18-30 hours. That prevents things from happening at the same time and spreads requests out over a long period of time.

Approximate correctness
The state of the system is that which the user sees. If a user can’t tell a part of the system is skewing and inconsistent, then it’s not. If you write a comment and someone loads the page at the same time, they might not get it for half a second, the user who is just reading the page won’t care. The writer of the comment will care though, so you make sure the user who wrote the comment will see it immediately. This allows you to cheat a little bit. When it comes to comments, your system doesn’t have to have globally consistent transactions. That would be super expensive and overkill. Comments are not financial transaction - know when you can cheat.


Twitter

Implement an API
Twitter's API Traffic is ten times that of Twitter’s Website alone. The API is the most important thing Twitter did to grow their user base. Keeping the service simple allowed developers to build on top of their infrastructure and come up with app ideas that are way better than Twitter could come up with. You can never do all the work your user's can do and you probably won't be as creative. So open up your application and make it as easy as possible for others to integrate your application with theirs.

Use what you know
Twitter uses messaging a lot. Producers produce messages, which are queued, and then are distributed to consumers. Twitter's main functionality is to act as a messaging bridge between different formats (SMS, web, IM, etc). Send a message to invalidate a friend's cache in the background instead of doing it all individually, synchronously. Twitter developers were most familiar with Ruby, so they moved from DRb to Starling, a distributed queue written in Ruby. Distributed queues were made to survive system crashes by writing them to disk. In Twitter's experience, most performance improvements come not from the choice of language, but from an application's design.

Know when and what to cache
For example, getting your friends status is complicated. There are security and other issues. So rather than doing a database query, a friend's status is updated in cache instead. It never touches the database. 90% of requests are API requests. So they don't do any page caching for the front-end. Twitter pages are so time sensitive it doesn't do any good. Twitter only caches API requests.

Defend yourself against abuse
Understand how people will try to bust your system. Put in reasonable limits and detection mechanisms to protect your system from being killed by bots. Build tools to detect abuse so you can pinpoint when and where they are happening. Be ruthless. Delete them as users.


Amazon

Use SOA
Amazon's architecture is loosely coupled and built around services. A service-oriented architecture (SOA) gave them the isolation that would allow building many software components rapidly and independently of each other, allowing fast time to market. The application that renders the Amazon.com Web pages is one such application server. So are the applications that serve the Web-services interface, the customer service application, and the seller interface.

Open up your system with APIs and you'll create an ecosystem around your application. Organizing around services gives you agility - you can now do things in parallel is because the output of everything is a service. Prohibit direct database access by clients. This means you can make you service scale and be more reliable without involving your clients. This is much like Google's ability to independently distribute improvements in their stack to the benefit of all applications.

Know when to favour consistency over availability and vice versa
To scale you have to partition, so you are left with choosing either high consistency or high availability for a particular system. You must find the right overlap of availability and consistency. Choose a specific approach based on the needs of the service. For the checkout process you always want to honor requests to add items to a shopping cart because it's revenue producing. In this case you choose high availability. Errors are hidden from the customer and sorted out later. When a customer submits an order you favor consistency because several services (credit card processing, shipping and handling, reporting) are simultaneously accessing the data and each rely on their data to be consistent.

Embrace failure
Take it for granted stuff fails, that's reality, embrace it. For example, go more with a fast reboot and fast recover approach. With a decent spread of data and services you might get close to 100%. Create a self-healing, self-organizing, lights-out type operation.

Only use what you need
Keep things simple by making sure there are no hidden requirements and hidden dependencies in the design. Cut technology to the minimum you need to solve the problem you have. It doesn't help the company to create artificial and unneeded layers of complexity. Not stuck with one particular approach or technology stack. Some places they use jboss/java, but they use only servlets, not the rest of the J2EE stack. C++ is uses to process requests. Perl/Mason is used to build content.

Base decisions on customer feedback
Use measurement and objective debate to separate the good from the bad. Expose real customers to a choice and see which one works best and to make decisions based on those tests. This is done with techniques like A/B testing and Web Analytics. If you have a question about what you should do - code it up, let people use it, and see which alternative gives you the results you want.

Scalability as a competitive advantage
Infrastructure for Amazon, like for Google, is a huge competitive advantage. They can build very complex applications out of primitive services that are by themselves relatively simple. They can scale their operation independently, maintain unparalleled system availability, and introduce new services quickly without the need for massive reconfiguration.


eBay

Partition everything
If you can't split it, you can't scale it. Split everything into manageable chunks by function and data.

Asynchrony everywhere
Connect independent components through event-driven queues and pipelines.

Embrace failure
Monitor everything, provide service even when parts start failing. Minimize and control dependencies, use abstract interfaces and virtualization, components have an SLA, consumers responsible for recovering from SLA violations. Automate everything. Components should automatically adjust and the system should learn and improve itself.

Embrace inconsistency
Pick for each feature where you need to be on the CAP continuum, no distributed transactions, inconsistency can be minimized by careful operation ordering, become eventually consistent through async recovery and reconciliation.

Save all your data
Data drives finding optimization opportunities, predictions, recommendations, so save it all. Know which data is authoritative, which data isn't, and treat it accordingly.

Infrastructure: use the right tool for the right job
Need to maximize utilization of every resource: data (memory), processing (CPU), clock time (latency), power. One size rarely fits all, particularly at scale. Compose from orthogonal, commodity components.


Facebook

Scaling takes multiple iterations
Solutions often work in the beginning, but you'll have to modify them as you go on - what works in year one may not work later. A good example is photos. Facebook currently serves 1.2 million photos a second. The first generation was built the easy way - don't worry about scaling that much - focus on getting the functionality right. The uploader stored the file in NFS and the meta-data was stored in MySQL. It only worked for the first 3 months but this didn't matter because time to market was the biggest competitive advantage they had. Having the feature was more important than making sure it was a fully thought out, scalable solution. The second generation was optimized - different access patterns were optimized for. Smaller images were accessed more frequently so those became cached. They also started using a CDN (Content Delivery Network). The third generation is an overlay system that creates a file that is a blob stored in the file system. Images are stored in a binary blob and you know the byte offset of the photo in the blob - so there's only one disk IO per photo.

Don't over design a solution - keep it simple
Just use what you need to use as you scale your system out. Figure out where you need to iterate on a solution, optimize something, or completely build a part of the stack yourself. Facebook spent a lot of time trying to optimize PHP, and ended up writing HipHop, a tool to convert PHP into C++. This generated a massive amount of memory and CPU savings. You don't have to do this on day one, but you may have to. Focus on the product first before you write an entire new language.

Choose the right tool for the job, but accept that your choice comes with overhead
If you really need to use Python then go ahead and do so, but realize with that choice there is overhead, usually across deployment, monitoring and operations. If you choose to use a service oriented architecture (SOA) you'll have to build most of the backend yourself and that often takes quite a bit of time. With the LAMP stack you get a lot for free. Once you move away for the LAMP stack, how you do things like service configuration and monitoring is up to you. As you go deeper into the services approach you have to reinvent the wheel.

Get the culture right
Build an environment internally which promotes building the right thing first and then fixing as needed, not worrying about innovating, not worrying about breaking things, thinking big, thinking what is the next thing you need to build after the building the first thing. You can get the code right, you can get the products right, but you need to get the culture right first. If you don't get the culture right then your company won't scale.


Instagram

Make use of existing cloud infrastructure

Don't reinvent the wheel when you can use solid and proven technology. Instagram runs 100+ instances of Ubuntu 11.04 on Amazon's EC2 cloud computing infrastructure. They also use Amazon's ELB (Elastic Load Balancer), which comprises three NGINX instances, with automatic failure recovery. The photos themselves go straight to Amazon S3 storage and they use Amazon CloudFront as their CDN (Content Delivery Network), which helps with image load times from users around the world (like in Japan, their second most-popular country).

Asynchronous task queuing
When a user decides to share out an Instagram photo to Twitter or Facebook, or when they need to notify a Real-time subscriber of a new photo posted, they push the task into the open source Gearman task management framework. Doing it asynchronously through a task queue means that media uploads can finish quickly, while the ‘heavy lifting’ can run in the background. There's about 200 workers, written in Python, consuming the task queue at any given time, split between the services they share to.

Push notifications
They use an open source Apple Push Notification Service (APNS) provider called pyapns, which is based on Twisted. It has handled over a billion push notifications for Instagram, and they report that its been rock-solid.

Real-time system-wide monitoring
With 100+ EC2 instances, it’s important to keep on top of what’s going on across the board. They use Munin to graph metrics system-wide, which sends an alert if anything is outside of its normal operating range. They write custom Munin plugins, building on top of Python-Munin, to graph metrics that aren’t system-level (for example, signups per minute, photos posted per second, etc). They use Pingdom for external monitoring of the service, and PagerDuty for handling notifications and incidents. For Python error reporting, they use Sentry, an open-source Django app. At any given time, they can sign-on and see what errors are happening across their system, in real time.

Selective use of NoSQL technology (like Redis)
Redis powers the main feed, the activity feed, the sessions system (here’s their Django session backend), and other related systems. All of Redis’ data needs to fit in memory, so they run several Quadruple Extra-Large Memory instances on EC2 for Redis, and occasionally shard across a few Redis instances for any given subsystem.


Sidenote on CAP
Eric Brewer's CAP Theorem or "the three properties of systems"
  • There are three properties of a system: consistency, availability and tolerance to network partitions (partitionability).  
  • You can have at most two of these three properties for any shared-data system. 
    • Consistency: write a value and then when you read the value you get the same value back. In a partitioned system there are time windows where that's not true. 
    • Availability: you may not always be able to write or read. The system may prevent you from writing because it wants to keep the system consistent.
    • Partitionability: divide nodes into small groups that can see other groups, but they can't see everyone.


Follow @dodgy_coder

Subscribe to posts via RSS

Saturday, March 3, 2012

Every software project I’ve worked on has used the "Spanish Theory" of project management, and its likely yours have too

The "Spanish Theory" says that management's job is to extract the maximum resources (= developer effort)  from the smallest amount of money (= developer salary). In practice what this often means for the developer is unpaid overtime (also known as "crunch time"), something very familiar to game developers, and also common in traditional software development, as the project nears its deadline. But those unpaid hours are actually costing you, the developer, because you can't get them back. You've sacrificed time in your personal life with your family and instead have chosen to work on the company's project - something of large value has been sacrificed for something of lesser value. If this imbalance continues past a reasonable level and unpaid overtime becomes the norm, then many developers will become dissatisfied and leave the company, increasing the company's staff turnover (churn) rate.

The book describing these harmful effects in the software industry was first published back in 1987. So why are many software development managers and PMs still practicing this method, some 25 years later? The reason I believe is a lack of foresight, an unquestioning acceptance of previous methods, a short term project oriented view, a limited understanding of the harm that comes to a company from a high churn rate, and finally, developers that are willing to accept these conditions. In moderation, some unpaid overtime is probably ok, but when it becomes the norm, from week to week and is just expected of all developers, then maybe that's a sign something is wrong, and could even be considered a job smell.

The attitude of government and corporations around the world towards unpaid overtime is changing, as can be seen by some recent initiatives out of Britain (Work your proper hours day). Similarly in Australia, there's now a National go home on time day held every November. The US-based International Game Developers Association (IGDA) is also active in promoting quality of life in the workplace through various publications and events.


Below I've quoted the extracts from chapter 3 of the book which gave me the idea for this brief blog post - I highly recommend you have a read of this book, or if not, then at least read through this small extract here which I thought was outstanding ...


Peopleware: Productive Projects and Teams (Second Edition)
Amazon Link: here
Authors: Tom Demarco and Timothy Lister
"Historians long ago formed an abstraction about different theories of value: The Spanish Theory, for one, held that only a fixed amount of value existed on earth, and therefore the path to the accumulation of wealth was to learn to extract it more efficiently from the soil or from people's backs.  
Then there was the English Theory that held that value could be created through ingenuity and technology. So the English had an Industrial Revolution, while the Spanish spun their wheels trying to exploit the land and the Indians in the New World. They moved huge quantities of gold across the ocean, and all they got for their effort was enormous inflation (too much gold money chasing too few usable goods). 
The Spanish Theory of Value is alive and well among managers everywhere. You see that whenever they talk about productivity. Productivity ought to mean achieving more in an hour of work, but all too often it has come to mean extracting more for an hour of pay. There is a large difference. The Spanish Theory managers  dream of attaining new productivity levels through the simple mechanism of unpaid overtime. They divide whatever work is done in a week by forty hours, not by the eighty or ninety hours that the worker actually put in. 
That's not exactly productivity — it's more like fraud — but it's the state of the art for many American managers. They bully and cajole their people into long hours. They impress upon them how important the delivery date is (even though it may be totally arbitrary; the world isn't going to stop  just because a project completes a month late). They trick them into accepting hopelessly tight schedules, shame them into sacrificing any and all to meet the deadline, and do anything to get them to work longer and harder. 
Overtime for salaried workers is a figment of the naive manager's imagination. Oh, there might be some benefit in a few extra hours worked on Saturday to meet a Monday deadline, but that's almost always followed by an equal  period of compensatory "undertime" while the workers catch up with their lives. Throughout the effort there will be more or less an hour of undertime for every hour of overtime. The trade-off might work to your advantage for the short term, but for the long term it will cancel out. 
Just as the unpaid overtime was largely invisible to the Spanish Theory manager  (who always counts the week as  forty  hours regardless of how much time the people put in), so too is the undertime invisible. You never see it on anybody's time sheet.  It's time spent on the phone or in bull sessions or just resting.  Nobody can really work much more than forty hours, at least not continually and with the level of  intensity required for creative work. Overtime is  like sprinting: It makes some  sense for the last hundred yards of the marathon for  those with any energy left, but if you start sprinting in the first mile, you're just wasting time. Trying to get people to sprint too much can only result in loss of respect for the manager. The best workers have been through it all before; they know enough to keep silent and roll their eyes while the manager raves on that the job has got to get done by April. Then they take their compensatory undertime when they can, and end up putting in forty hours of real work each week. The best workers react  that way; the others are workaholics. 
People under time pressure don't work better; they just work faster. 
In order to work faster, they may have to sacrifice the quality of the product and their own job satisfaction."

Follow @dodgy_coder

Subscribe to posts via RSS

Saturday, February 11, 2012

Coding tricks of game developers

If you've got any real world programming experience then no doubt at some point you've had to resort to some quick and dirty fix to get a problem solved or a feature implemented while a deadline loomed large. Game developers often experience a horrific "crunch" (also known as a "death march"), which happens in the last few months of a project leading up to the game's release date. Failing to meet the deadline can often mean the project gets cancelled or even worse, you lose your job. So what sort of tricks do they use while they're under the pump, doing 12+ hour per day for weeks on end?

Below are some classic anecdotes and tips - many thanks to Brandon Sheffield who originally put together this article on Gamasutra. I have reposted a few of his stories and also added some more from newer sources. I have also linked on each story to the author's home page or blog wherever possible.

1. The programming antihero - Noel Llopis

I was fresh out of college, still wet behind the ears, and about to enter the beta phase of my first professional game project -- a late-90s PC title. It had been an exciting rollercoaster ride, as projects often are. All the content was in and the game was looking good. There was one problem though: We were way over our memory budget.

Since most memory was taken up by models and textures, we worked with the artists to reduce the memory footprint of the game as much as possible. We scaled down images, decimated models, and compressed textures. Sometimes we did this with the support of the artists, and sometimes over their dead bodies.

We cut megabyte after megabyte, and after a few days of frantic activity, we reached a point where we felt there was nothing else we could do. Unless we cut some major content, there was no way we could free up any more memory. Exhausted, we evaluated our current memory usage. We were still 1.5 MB over the memory limit!

At this point one of the most experienced programmers in the team, one who had survived many years of development in the "good old days," decided to take matters into his own hands. He called me into his office, and we set out upon what I imagined would be another exhausting session of freeing up memory.

Instead, he brought up a source file and pointed to this line:

static char buffer[1024*1024*2];

"See this?" he said. And then deleted it with a single keystroke. Done!

He probably saw the horror in my eyes, so he explained to me that he had put aside those two megabytes of memory early in the development cycle. He knew from experience that it was always impossible to cut content down to memory budgets, and that many projects had come close to failing because of it. So now, as a regular practice, he always put aside a nice block of memory to free up when it's really needed.

He walked out of the office and announced he had reduced the memory footprint to within budget constraints -- he was toasted as the hero of the project.

As horrified as I was back then about such a "barbaric" practice, I have to admit that I'm warming up to it. I haven't gotten into the frame of mind where I can put it to use yet, but I can see how sometimes, when you're up against the wall, having a bit of memory tucked away for a rainy day can really make a difference. Funny how time and experience changes everything.

2. Cache it up - Andrew Russell

To improve performance when you are processing things in a tight loop, you want to make the data for each iteration as small as possible, and as close together as possible in memory. That means the ideal is an array or vector of objects (not pointers) that contain only the data necessary for the calculation.

This way, when the CPU fetches the data for the first iteration of your loop, the next several iterations worth of data will get loaded into the cache with it.

There's not really much you can do with using fewer and faster instructions because the CPU is as fast as its going to get, and the compiler can't be improved. Cache coherence is where it's at - this article contains a good example of getting cache coherency for an algorithm that doesn't simply run through data linearly.

3. Plan your distractions - Jay Barnson

The Internet is one of the greatest tools ever invented for both improving and destroying productivity. Twitter and forums and blogs and instructional websites can be extremely motivational and educational, but they can also be a distraction that completely destroys all hope of ever getting anything done. One thing I’ve done in the past which has proven pretty successful is to stick to a plan for when I can spend some minutes checking email and Twitter, or play a quick game or something. Either at the completion of a task, or after a period of time (say one five-minute break every hour). Otherwise, the browser’s only use is for reading reference manual pages, if necessary. That way I turn a potential distraction into a motivating tool.

4. Collateral damage - Jim Van Verth (@cthulhim)

Don't know how many remember Force 21, but it was an early 3D RTS which used a follow cam to observe your current platoon. Towards the end of the project we had a strange bug where the camera would stop following the platoon -- it would just stay where it was while your platoon moved on and nothing would budge it. The apparent cause was random because we couldn't find a decent repro case. Until, finally, one of the testers noticed that it happened more often when an air strike occurred near your vehicles. Using that info I was able to track it down.

Because the camera was using velocity and acceleration and was collidable, I derived it from our PhysicalObject class, which had those characteristics. It also had another characteristic: PhysicalObjects could take damage. The air strikes did enough damage in a large enough radius that they were quite literally "killing" the camera.

I did fix the bug by ensuring that cameras couldn't take damage, but just to be sure, I boosted their armor and hit points to ridiculous levels. I believe I can safely say we had the toughest camera in any game.

5. The blind leading the blind - Maurício Gomes

At university there was a team that made a FPS flash game. For some bizarre reason, the programmer, instead of checking if the character was colliding with the wall and stop you going there, he did the inverse, he checked if there was a wall, and only allowed you to move parallel to it!

This sparked a bizarre bug: in crossings or T junctions in the level, you could not actually cross, only turn to the passage on your left or right. The deadline was closing, and they had no idea on how to fix it.

Then the team writer fixed the issue; he told the artist to add an animation of hands touching the walls, and then he added in the background story that the main character was blind and needed to constantly touch the walls to know where he was going.

6. You wouldn't like me when I'm angry - Nick Waanders

I once worked at THQ studio Relic Entertainment on The Outfit, which some may remember as one of the earlier games for the Xbox 360. We started with a PC engine (single-threaded), and we had to convert it to a complete game on a next-gen multi-core console in about 18 months. About three months before shipping, we were still running at about 5 FPS on the 360. Obviously this game needed some severe optimization.

When I did some performance measurements, it became clear that as much as the code was slow and very "PC," there were also lots of problems on the content side as well. Some models were too detailed, some shaders were too expensive, and some missions simply had too many guys running around.

It's hard to convince a team of 100 people that the programmers can't simply "fix" the performance of the engine, and that some of the ways people had gotten used to working to needed to be changed. People needed to understand that the performance of the game was everybody's problem, and I figured the best way to do this is with a bit of humor that had a bit of hidden truth behind it.

The solution took maybe an hour. A fellow programmer took four pictures of my face -- one really happy, one normal, one a bit angry, and one where I am pulling my hair out. I put this image in the corner of the screen, and it was linked to the frame rate. If the game ran at over 30fps, I was really happy, if it ran below 20, I was angry.

After this change, the whole FPS issue transformed from, "Ah, the programmers will fix it." to, "Hmm, if I put this model in, Nick is going to be angry! I'd better optimize this a little first." People could instantly see if a change they made had an impact on the frame rate, and we ended up shipping the game at 30fps.

7. Its not a bug, its a feature! - Philip Tan

I worked on an RPG in which we were trying to get the NPCs (Non-player Characters) to spot when you were in range, walk up to you, and strike up a conversation with you by activating the dialog system.

We forgot to add code to distinguish NPCs from PCs (Player Characters), so we'd walk into town and all the NPCs would be talking with each other. Because all NPC AI code used the same dialog template, they actually got a few sentences in before the conversations became nonsensical. And because character dialog was broadcast, you could read everything they said if you were in range.

We decided to turn that bug into a major feature.

8. Dirty deeds - Tim Randall (Developer @ Encore)

The engine team at Gremlin Interactive used to keep a single glove in their office. When someone asked why it was there, they were told it was only used when someone was about to type some really dirty code. It wasn't so much a case of not wanting to leave fingerprints but rather not wanting to actually touch the dirtiest fixes!

9. Explicit conditional hinting - ZorbaTHut

A very, very low-level tip, but one that can come in handy... most compilers support some form of explicit conditional hinting. GCC has a function called __builtin_expect which lets you inform the compiler what the value of a result probably is. GCC can use that data to optimize conditionals to perform as quickly as possible in the expected case, with slightly slower execution in the unexpected case.

if(__builtin_expect(entity->extremely_unlikely_flag, 0)) {
  // code that is rarely run
}

I've seen a 10-20% speedup with proper use of this.

10. Object-ive oriented programming - Anonymous

Back at a game studio, I think it was near the end of the project, we had an object in one of the levels that needed to be hidden. We didn't want to re-export the level and we did not use checksum names. So right smack in the middle of the engine code we had something like the following:

if( level == 10 && object == 56 )
{
    HideObject();
}

The game shipped with this in.

Maybe a year later, an artist using our engine came to us very frustrated about why an object in their level was not showing up after exporting. The level they had a problem with resolved to level 10. I wonder why?

11. Stack vs Heap - Torbjörn Gyllebring

Stack allocation is much faster than heap allocation since all it really does is move the stack pointer. Using memory pools, you can get comparable performance out of heap allocation, but that comes with a slight added complexity and its own headaches.

Also, stack vs heap is not only a performance consideration; it also tells you a lot about the expected lifetime of objects. The stack is always hot, the memory you get is much more likely to be in cache than any far heap allocated memory.

Downside of the stack is that it is actually a stack. You can't free a chunk of memory used by the stack unless it is on top of it. There's no management, you push or pop things on it. On the other hand, the heap memory is managed: it asks the kernel for memory chunks, maybe splits them, merges thems, reuses them and frees them. The stack is really meant for fast and short allocations.

12. I'm a programmer, not an artist - Damian Connolly

For indie / solo developers who are working on an iPhone or Android game on their own, while you're looking for an artist etc, you should be developing your game at the same time. Use programmer art, stand-ins, free sprites anything. Most of the time, before even thinking about final assets, I just want something up and running quickly to see if it's fun. Prototype the crap out of it and find the game. Then, when the gameplay's locked down, you can start putting in the proper art. Doing it the other way around leads to lost money, and work that needs to be redone multiple times, which aside from harming your project, sucks your motivation to finish it (and if you're making a game to get a job, showing that you can finish a project is a good thing). Another tip if you're lacking upfront finance is to find a freelance game artist who will accept a revenue sharing deal, e.g. typically something like 30% of game revenue, payable once it gets published to the AppStore.

13. Remove unnecessary branches - tenpn

On some platforms and with some compilers, branches can throw away your whole pipeline, so even insignificant if() blocks can be expensive.

The PowerPC architecture (PS3/x360) offers the floating-point select instruction, fsel. This can be used in the place of a branch if the blocks are simple assignments:

float result = 0;
if (foo > bar) { result = 2.0f; }
else { result = 1.0f; }

Becomes:

float result = fsel(foo-bar, 2.0f, 1.0f);

When the first parameter is greater than or equal to 0, the second parameter is returned, else the third. The price of losing the branch is that both the if{} and the else{} block will be executed, so if one is an expensive operation or dereferences a NULL pointer this optimisation is not suitable. Sometimes your compiler has already done this work, so check your assembly first.

14. Hack the stack - Steve DeFrisco

I was one of a few interns at IMAGIC in 1982-83. We were all doing Intellivision carts. One of the programmers had to leave to go back to school, and I was chosen to fix the random crash bug in his game. It turned out to be a stack overflow in the timer interrupt handler. Since the only reason for the handler was to update the *display* of the on-screen timer, I added some code to test the depth of the stack at the beginning of the interrupt routine. If we were in danger of overflowing the stack, return without doing anything. Since the handler was called multiple times per second, the player never noticed, and the crash was fixed.

15. Meet my dog, "Patches" - Mick West

There's an old joke that goes something like this:

Patient: "Doctor, it hurts when I do this."
Doctor: "Then stop doing it."

Funny, but are these also wise words when applied to fixing bugs? Consider the load of pain I found myself in when working on the port of a 3D third person shooter from the PC to the original PlayStation.

Now, the PS1 has no support for floating point numbers, so we were doing the conversion by basically recompiling the PC code and overloading all floats with fixed point. That actually worked fairly well, but where it fell apart was during collision detection.

The level geometry that was supplied to us worked reasonably well in the PC version of the game, but when converted to fixed point, all kinds of seams, T-Junctions and other problems were nudged into existence by the microscopic differences in values between fixed and floats. This problem would manifest itself in one case with the main character touching a particular type of door in a particular level in a particular location; rather than fix the root cause of the problem, I simply made it so that if he ever touched the door, then I'd move him away, and pretend it never happened. Problem solved.

Looking back I find this code quite horrifying. It was patching bugs and not fixing them. Unfortunately the real fix would have been to go and rework the entire game's geometry and collision system specifically with the PS1 fixed point limitations in mind. The schedule was initially aggressive, and since we always seemed close to finishing, the quick patch option won over against a comprehensive (but expensive) fix.

But it did not go well. Hundreds of patches were needed, and then the patches themselves started causing problems, so more patches were added to turn off the patches in hyper-specific circumstances. The bugs kept coming, and I kept beating them back with patches. Eventually I won, but at a cost of shipping several months behind schedule, and working 14 hour days for all of those several months.

That experience soured me against "the patch." Now I always try to dig right down to the root cause of a bug, even if a simple, and seemingly safe, patch is available. I want my code to be healthy. If you go to the doctor and tell him "it hurts when I do this," then you expect him to find out why it hurts, and to fix that. Your pain and your code's bugs might be symptoms of something far more serious. The moral: Treat your code like you would want a doctor to treat you; fix the cause, not the symptoms.

16. Identity crisis - Noel Llopis

This scene is familiar to all game developers: It's the day we're sending out the gold candidate for our Xbox 1 game. The whole team is playtesting the game all day long, making sure everything looks good. It's fun, it's solid, it's definitely a go in our minds.

In the afternoon, we make the last build with the last few game-balancing tweaks, and do one last playthrough session when disaster strikes: The game crashes hard! We all run to our workstations, fire up the debugger, and try to figure out what's going on. It's not something trivial, like an assert, or even something moderately hard to track down, like a divide by zero. It looks like memory is garbage in a few places, but the memory reporting comes out clean. What's going on?

One dinner and many hours later, our dreams of getting out on time shattered, we manage to track it down to one data file being loaded in with the wrong data. The wrong data? How's that possible? Our resource system boiled down every asset to a 64-bit identifier made out of the CRC32 of the full filename and the CRC32 of all the data contents. That was also our way of collapsing identical resource files into a single one in the game. With tens of thousands of files, and two years of development, we never had a conflict. Never.

Until now, that is.

It turns out that one of the innocent tweaks the designers had checked in that afternoon made it so a text file had the exact same filename and data CRC as another resource file, even though they were completely different!

Our hearts sank to our feet when we recognized the problem. There's no way we could change the resource indexing system in such a short period of time. Even if we pulled an all-nighter, there was no way to know for sure that everything would be stable in the morning.

Then, as quickly as despair swept over us, we realized how we could fix this on time for the gold candidate release. We opened up the text file responsible for the conflict, added a space at the end, and saved it. We looked at each other with huge grins on our faces and said:

"Ship it!"

The extra space meant the CRC32 checksum of the text file was altered and therefore no longer conflicted with the other resource.

17. HexEdit to the rescue - Ken Demarest

Back on Wing Commander 1 we were getting an exception from our EMM386 memory manager when we exited the game. We'd clear the screen and a single line would print out, something like "EMM386 Memory manager error. Blah blah blah." We had to ship ASAP. So I hex edited the error in the memory manager itself to read "Thank you for playing Wing Commander."

18. 8-bit audio stomper - Toonse

For a launch product of a certain console I had a nasty bug report from QA that took 20+ hours to reproduce. Finally (with 24 hours left to go to hit console launch) tracked it down to some audio drivers in the firmware that were erroneously writing 1 random byte "somewhere" at random times where the "somewhere" was always in executable code space. I finally figured out that any given run of the game that "somewhere" was always the same place, luckily. 1st party said sorry, can't fix it in time as we don't know why it's being caused! So I shipped that game with stub code at the very start of main that immediately saved off the 1 byte from the freshly loaded executable in the place I knew it would overwrite for that particular version of the exe. There was then code that would run each frame after audio had run and restore that byte back to what it should be just in case it had been stomped that frame. Good times! We hit launch.

To this day I still feel very very dirty about this hack, but it was needed to achieve the objectives and harmed no-one :)

19. Rainy day server pool - Potatolicious

I used to work for a company that had a horrific hardware requisition policy. If your team needed a server, it had to go through a lengthy and annoying approvals process - and even then, it took months before Infrastructure would actually provide said servers.

In other words, when a project gets handed down from above to launch in, say, 3 months, there's no way in hell you can get the servers requisitioned, approved, and installed in that time. It became standard practice for each team to slightly over-request server capacity with each project and throwing the excess hosts into a rainy day pool, immediately available and repurposeable as required.

New servers will still get requested for these projects, but since they took so long to approve, odds are they'd go right into the pool whenever they actually arrived, which sometimes took up to a year.

Of course, it was horrifyingly inefficient. Just on my team alone I think we had easily 50 boxes sitting around doing nothing (and powered on to boot) waiting to pick up the slack of a horrendously broken bureaucracy.

20. Bit shifting magic - Steven Pigeon

In order to avoid stalls in the processor pipeline due to branching, one can often use a branchless equivalent, that is, code transformed to remove the if-then-elses and therefore jump prediction uncertainties. E.g. a straightforward implementation of abs( ) in C might be

inline int abs(int x)
{
    return (x<0) ? -x : x;
}

Which is simple enough but contains an inline if-then-else. As the argument, x, isn’t all that likely to follow a pattern that the branch prediction unit can detect, this simple function becomes potentially costly as the jump will be mispredicted quite often.

How can we remove the if-then-else, then? One solution is to use the right shift operator (>>) and the bitwise XOR operator (^) as following:

inline int abs_no_branch(int x)
{
  int m = (x >> (8 * sizeof(int)-1));
  return ((x ^ m) - m);
}

Where the expression (8 * sizeof(int) - 1) evaluates to 15, 31, or 63 depending on the size of integers on the target computer.

Further detailed reading about this technique here: Branchless Equivalents of Simple Functions.

Follow @dodgy_coder on Twitter

Sunday, January 15, 2012

The Promise of HTML5

Anyone wanting evidence of what HTML5 can achieve needs only to browse through the many excellent demos around the place, such as at chromeexperiments.com; these run inside WebGL enabled browsers, such as Google Chrome and Firefox. One of the driving forces of HTML5 is to make it easy to include and handle multimedia and graphical content on the web without having to resort to proprietary plugins and APIs; the new <canvas>, <svg>, <video>, <audio> tags allow for much of this. WebGL is a context of the canvas HTML element that provides a 3D computer graphics API without the use of plug-ins. WebGL is currently supported by all major desktop browsers, except for Internet Explorer where it is currently only supported via a plugin (named IEWebGL). Support on mobile devices is a bit patchy though, with it being limited to Mobile Firefox on Android along with some specific Nokia, Sony Ericsson and Blackberry models. On the iPhone, there is a workaround / hack to develop apps with WebGL, and its expected Apple will support it in a future version.

This demo by Evan Wallace shows off the power of WebGL - a pool of water rendered with reflection, refraction, caustics, and ambient occlusion. You can create ripples on the water and also move the sphere around, both in and out of the water.

A popular lightweight framework has sprung up on top of WebGL called three.js.The aim of the project is to create a lightweight 3D engine with a very low level of complexity; in other words, for developers who are not experienced with 3D graphics coding. The engine can render using <canvas>, <svg> and also WebGL.  It is one of the most comprehensive WebGL frameworks, covering matrices, scenes, meshes, materials, shadows, voxels, fog, and more. Many of the Chrome WebGL demos linked above use it and there's a list of demos on the three.js github page.  These demos are absolutely mind blowing - I ran them inside Chrome with a reasonably old graphics card (a three year old GEForce 9600 GT) and the results were incredible - all ran at around 60 frames per second.

A couple of real standouts here:
Floating soap bubbles - fresnel shader demo (rotate view with mouse)
Model of a head - normalmap demo (rotate view with mouse)
Model of Walt Disney - cube mapping and texture demo (rotate view with mouse)



Follow @dodgy_coder

Subscribe to posts via RSS

Wednesday, January 4, 2012

Modern Cross Platform Development

Why isn't there a modern technology available for using the same codebase to produce native apps on all of the currently popular platforms - I'm talking iOS (iPhone/iPad/iPod Touch), Android, Windows, Mac and Linux?

That was my original question before I started looking, and since then I've discovered there actually are plenty of new options out there for cross platform development catering for all of the above platforms.


A Brief History of Desktop UI Toolkits

In the 1980's the problem of a cross platform desktop user interface was for the most part solved by the X Window system, known as X11, (1984-) along with one of the first widget toolkits, Motif (1989-), which was built on top of X11. Back then, the dominant platforms used by business were Microsoft Windows and the various flavours of Unix, like Sun Solaris, HP-UX, IBM's AIX etc (later Linux came along and maintained full support for X11 and Motif). Developers who wanted to target multiple platforms such as these had this option of developing one codebase, usually written in C/C++, using X11 and/or Motif.  The UI code for the most part could remain the same and the application just needed to be recompiled with the provided X11 libraries.

Since then Motif has pretty much faded into the background and been replaced with newer widget toolkits, still built on top of X11, including Qt (1991-), wxWidgets (1992-) and GTK+ (1998-). These now run on many different platforms and bindings are available for many, many languages, including for their native C or C++.

These three free open source toolkits have been successful for the desktop application case but looking towards mobile and tablet platforms, these toolkits don't currently have the support there to take them into the future.

Qt
Native language: C++
Platforms: iOS (unofficial), Windows, Mac, Linux.

Probably the C++ based Qt widget toolkit is the most well established way of writing desktop cross platform applications. Smartphone support isn't really there yet, but there is an unofficial port to iOS. Linux's KDE desktop environment is written with the Qt toolkit. Many significant apps have been developed with Qt, including Autodesk Maya, VLC media player, Mathematica, Virtual Box and Skype. Qt is now owned by Nokia (although is still open source), and there was a release of a new version recently (Qt 4.8).

GTK+
Native language: C
Platforms: HTML5 (unofficial), Windows, Mac, Linux.

The C-based GTK+ widget toolkit is also a very well established way of writing cross platform desktop apps. Smartphone support isn't there, but there is an unofficial port to HTML5. GTK+ powers Chromium on Linux, the open source forerunner to Google's Chrome browser. The GNOME desktop environment is written with the GTK+ toolkit. The other notable app written with GTK+ is the one that launched the toolkit itself, GIMP, an open source bitmap image editor.

wxWidgets
Native language: C++
Platforms: iOS, Windows, Mac, Linux.

A C++ native mode toolkit that provides a thin abstraction to a platform's native widgets. It was originally developed as a desktop GUI toolkit in the same vein as GTK+ and Qt and support for iOS is still beta. There are a number of notable apps developed with wxWidgets including BitTorrent, Audacity, TortoiseCVS and RapidSVN.


Java and Silverlight

Sun's Java Swing UI Library (1997-) and Microsoft's Silverlight (2007-) were both attempts at "write once, run anywhere" (WORA) technology that provided a rich user interface library. Although technically successful, they failed in their attempt to become the ubiquitous technology that everyone uses to develop UIs. They both attempted to replace the 'native' look of apps developed on a particular platform and instead impose their own look and feel based on graphical primitives, which although being more powerful for developers, users on the whole didn't like.

As Johannes Fahrenkrug discusses here, people actually want to run Windows apps that look like Windows apps, and run MacOS apps that look like MacOS apps. To be fair, the Java Swing UI has actually undergone a lot of advances since it was first released and can now generate apps that do look perfectly native on all desktop platforms. The problem may be however that people's original experience of early Swing apps having a slow and inconsistent UI might have put them off using other Java apps and so contributed to its demise.

In the case of Microsoft's Silverlight and WPF, although not officially dead yet, they are now taking a back seat to newer technologies that were released by Microsoft at the September 2011 Build conference; Windows 8 allow developers to create new style 'Metro' applications by using either web technology (HTML5/JavaScript/CSS) or a traditional language - C#, VB.NET or C/C++ paired up with XAML for describing the UI. There's more detail about this topic on StackOverflow here for those interested.


The Rise of Web Applications and the App Store

The two big changes since the desktop UI toolkit days has been the rise of browser-based web applications and more recently the rise of downloadable apps running on smartphones and tablets such as Apple's iOS (powering the iPod touch, iPhone and iPad devices) along with Google's Android (powering a vast array of different smartphones and tablets from many hardware vendors). Google's recent Chrome OS also deserves a mention for creating an OS around the browser itself. These new class of devices offer a quick method of downloading, paying for and installing apps (often with just one click) and appear in the easy to use 'App Store' on iOS and 'Android Marketplace' on Android.

Microsoft is getting in on the App Store action a little late with its 'Windows Store' for Windows 8, which will be appearing some time in 2012. Its thought by Hal Berenson (a former Distinguished Engineer at Microsoft) that the upcoming Windows Phone 8 OS will be based on the same technology as Windows 8 and hence will unify  the development platform for Microsoft's desktop, tablet and smartphone operating systems. This will likely be announced some time in 2012, probably at the same time Microsoft launches the 'Windows Store'. This will mean Windows 8's new 'Metro' style apps on the Windows Store will run on phones, desktops and tablets - something that neither Apple nor Google can lay claim to, just yet. Add in the possibility of an XBox update which adds support for running Metro apps, and you have a huge carrot which will make the unified Windows 8 platform very attractive to both application and game developers.


Choosing Your Platform - Desktop, Web or Mobile Application?

When choosing your platform, if you need full access the underlying file system, or access to hardware devices like serial ports, microphones, webcams, etc, then you may be better off staying with a desktop application. If you need platform independence on top of this then you can go with one of the traditional widget library technologies like wxWidgets, GTK+ or Qt to provide a full cross platform UI solution.

Alternatively, if you don't need so much access to hardware and can remain restricted to the browser, then HTML5 and JavaScript may be the way to go. Browser based web applications have their own set of problems however, including the browser incompatibilities, varying support for the HTML/CSS web standards and the Document Object Model (DOM). In addition, web application development generally makes it harder to create rich UI apps than for desktop or mobile applications. HTML5 will provide massive improvements, but web apps are still running in a browser and so will always remain sandboxed and limited in what they can achieve (no access to file system, serial ports, microphone, webcam, etc.).

The main advantage of the browser app however, and its a massive one, is that its everwhere and supported by every device, so if HTML5 takes off, then it could become the defacto standard for developing apps of any kind, desktop or not. As Jeff Atwood discusses in his seminal blog post All Programming is Web Programming; "the web is the most efficient, most pervasive, most immediate distribution network for software ever created - its almost completely frictionless".  As Atwood mentions, more and more users gravitate towards preferring to run their apps inside the browser, on smartphones and on tablets where things 'just work' and there's generally nowhere near as much friction caused by the traditional desktop software setup and update process.

A third option available now is the cross platform mobile development SDK as detailed below (Mono, Appcelerator Titanium, Rhodes, PhoneGap, MoSync, Moai, Corona SDK and JUCE). Smartphone and tablet based applications are taking off, and these SDKs allow you to write once and run on any of these new class of devices, as well as in some cases also being able to run on the traditional desktop. These would seem to offer some of the 'power' of the desktop in terms of native code execution speed and access to hardware functionality, along with the enourmous 'frictionless' benefit that you get when publishing to an app store, where installing an app is literally a one click operation.

Mono
Native language: C#
Platforms: iOS, Android, Windows, Mac, Linux, Browser (e.g. via ASP.NET WebForms or MVC).
Cost: Windows, Mac & Linux: free. Android and iOS: from US$399 each. Free trial available.
License: LGPL/GPL/X11 combination. Commercial license available.
Source: Mono for Windows/Mac/Linux is open source. Mono for iOS/Android is closed source.

The C# based Mono cross platform library allows apps to be built using purely C#. However this is not strictly a cross platform UI library, since each supported platform has its own different set of Mono C# UI libaries, each with their own capabilities. The idea is that you build your software using the MVC (Model View Controller) pattern, so that the Model and Controller components (both written in C#) can be shared across all platforms without any changes. Only the View component needs to be re-written for each platform (again, in C#). Mono targets both mobile and desktop apps, however if you are just looking at developing a desktop application, then Mono probably isn't a big improvement over GTK+ or Qt, after all a well written C++ Library (with a Model and Controller component for example) will enjoy the same capability to be shared across more than one platform if you use Qt or GTK+ and then you wouldn't need a different UI library on each platform to create your view. There are several advantages that Mono has over Qt or GTK+ however - firstly in leveraging a team's existing knowledge (and codebase) of C# which is a popular language. Secondly, being able to target iOS, Android and the browser. Lastly, via Mono's .NET CLR implementation (Common Language Runtime), code is compiled into modules of bytecode, which are binary compatible across all the supported platforms.

There is also an open source library for Mono called MonoGame which lets you port with minimal effort XNA based games (which originally target the .NET platform and run only on Windows Mobile, Windows and XBox) to any of the Mono platforms such as MacOS, Linux, iOS and Android.


Appcelerator Titanium
Native language: JavaScript, Python and Ruby
Platforms: iOS, Android, Windows, Mac, Linux.
Cost: Community Edition is free. Indie Edition (extra APIs, help, support): US$499 per year.
License: Apache Public License v2
Source: Open source


An open-source solution which allows you to use web development languages (HTML, JavaScript, CSS, Python and Ruby) to build mobile and desktop apps. App data can be stored in the cloud or on the device, and apps can take full advantage of hardware, particularly camera and video camera capability. Appcelerator apps go through a complex compilation and optimization process which result in it creating apps that look, feel, and perform just like native apps, because you are using native UI components... so an iPhone app developed with Titanium will actually feel like an iPhone app. They also offer an API repository marketplace to buy and sell code to extend Titanium. One of the downloadable components allows you to develop your app using an MVC (Model View Controller) pattern. There is an active developer community Q&A site for Titanium developers which is similar in usage to StackOverflow.

Rhodes
Native language: Ruby
Platforms: iOS, Android, Windows Mobile, Blackberry.
Cost: Free
License: MIT License
Source: Open source

Rhodes is an open source, Ruby-based framework that allows the development of native apps for a wide range of smartphone devices and operating systems. The framework lets you write your code once and use it to quickly build apps for every major smartphone. Apps can take full advantage of available hardware, including GPS and camera, as well as location data. Rhodes enforces a strict MVC (Model View Controller) pattern on your apps. Views are written in HTML5 while Controllers and Models are written in Ruby.

PhoneGap
Native language: HTML5/JavaScript
Platforms: iOS, Android, Windows Mobile, Blackberry, Symbian, Palm.
Cost: Free
License: Apache License, Version 2.0
Source: Open source

PhoneGap is an open source framework that helps you develop apps for smartphones using web development languages such as JavaScript and HTML5. It also allows for access to hardware features including GPS/location data, accelerometer, camera, sound and more. PhoneGap lets you take a web app, run it in a UIWebView, and through javascript you can access iPhone features such as the camera an accelerometer. This means that it won't necessarily have the look and feel of a native app (like the other cross platform SDKs listed here). The idea is that you develop your web app like you normally do, and then use PhoneGap to 'bridge the gap' to the phone, and give you access to phone's hardware, that traditionally you couldn't access from a web-only app.

MoSync
Native language: C++
Platforms: iOS, Android, Windows Mobile, Blackberry, Symbian.
Cost: Free for Indie developers. From €199 (Euros) per year for Enterprise developers.
License: GPL v2. Commercial license available.
Source: Open source

The MoSync Mobile SDK is a cross-platform mobile application development SDK which allows the development of native apps. Free open-source, it is based on C++ but allows development also in HTML5 and JavaScript. MoSync provides access to a wide range of underlying device functionality, via a C++ SDK or optionally via JavaScript.  It requires probably a greater degree of software skill from the developer, but in principle can enable a rich variety of different kinds of application.

Moai
Native language: Lua
Platforms: iOS, Android, Chrome Web Store, Windows, Mac, Linux.
Cost: Free
License: Common Public Attribution License Version 1.0 (CPAL)
Source: Open source

Although intended to be a mobile game development SDK, I think it deserves a mention here due to its unique scripted approach to cross platform development. Games developed with Moai run on iOS and Android as well as the Chrome Web Store, Windows, Mac and Linux. Designed to be programmed with the Lua scripting language, Moai is designed for experienced game developers who wish to use Lua for mobile development. The Moai framework itself is written in C++ and is intended to be called from the Lua scripting language, but can also be called from any other language supported by the host platform. The Lua script is run as interpreted byte code, but since very few Lua instructions are processed among all the input handling, this means that rendering, animation, collision detection, and physics math runs natively. Moai's physics engine for example is the Box2D open source C++ library. Moai is free and open source, however to build apps for iOS devices you'll need the iOS SDK and the Xcode IDE (presumably running on MacOS) and be a member of the Apple iOS developer program (US$99/year). To build apps for Android you'll need the Android SDK, the Eclipse IDE and an Android device.

Corona SDK
Native language: Lua
Platforms: iOS, Android, Kindle Fire, Nook Color.
Cost: US$199/year for Android. US$199/year for iOS. $349/year for all platforms. Free trial available.
License: Commercial, price as above.
Source: Closed source

A similar toolkit to Moai in that its primarily aimed at game developers, and apps are written with the Lua scripting language. Corona SDK was developed by two former Adobe mobile engineers and has been in development since 2007. It features a proprietary OpenGL-ES rendering engine, which allows for full hardware acceleration of graphics, including sprites that animate at full GPU speed. The Corona physics engine is built around Box2D as with Moai. Its free to try Corona and run your apps in a simulator on your desktop computer, but to build an app and publish it to an App Store, you'll need to pay a yearly subscription fee (of either US$199 per year for Android or iOS or the premium subscription of US$349 for all platforms). Your apps are built "in the cloud" on Corona's server. Note that if you are developing for iOS you'll still need to pay the yearly Apple iOS developer program fee which is currently US$99. There seems to be extensive documentation available for Corona and an active developer community forum. There has been a recent push to promote Corona for use not only for developing games but also for general apps and also interactive ebooks.

JUCE
Native language: C++
Platforms: Windows, MacOS, Linux, iOS, Android (Note that Android support is a work in progress).
Cost: Free for GPL license. Commercial license from £399 (UK pounds) per product.
License: GPL. Commercial license available.
Source: Open source

JUCE is an all-encompassing C++ class library for developing cross-platform software. Its designed to contain everything you're likely to need to create most applications, and is particularly well-suited for building highly-customised GUIs, and for handling graphics and sound. JUCE is developed by Raw Material Software and consists of a small team of developers based in London, England, founded by Julian Storer in 1999, who is still the primary developer today. It would probably be best suited to experienced C++ developers. Julian Storer himself is a professional C++ coder with over 15 years of C++ experience; he takes pride in the fact the source for JUCE is literate, coherent, cross-platform and high quality. Adding JUCE to your C++ application is very simple - the easiest way involves simply including juce.h in your files and adding a single .cpp file to your project. No need to compile any libraries or worry about dependencies.

Follow @dodgy_coder

Subscribe to posts via RSS