PlayCanvas WebGL game engine is open sourced

4. June 2014

 

Today it was announced that PlayCanvas Game Engine has been open sourced.  PlayCanvas is a WebGL HTML5 game engine that runs across supported browsers, or on mobile devices using a solution such as CocoonJS.  Given yesterdays announcement that Safari for Mac and iOS 8 are both going to support WebGL, it is becoming much more viable.

 

Playcanvas logo

In their words, PlayCanvas engine is:

 

 

In case you haven’t come across the PlayCanvas Engine before, it’s a JavaScript library engineered specifically for building video games. It implements all of the major components that you need to write high quality games:

  • Graphics: model loading, per-pixel lighting, shadow mapping, post effects
  • Physics: rigid body simulation, ray casting, joints, trigger volumes, vehicles
  • Animation: keyframing, skeletal blending, skinning
  • Audio engine: 2D and 3D audio sources
  • Input devices: mouse, keyboard, touch and gamepad support
  • Entity-component system: high level game object management

 

It sounds very similar in scope to the Turbulenz engine I looked at last year.  One major difference is PlayCanvas includes a complete visual editor that runs in the browser:

 

Playcanvas

 

The code is now available on GitHub.

You can read the documentation here as well as the API reference here.

 

Keep in mind though, even though PlayCanvas is now open source, it is not completely free ( although a free tier exists ).  You can check out the pricing tiers here.




Game development tutorial: Swift and SpriteKit - Part 1 A Simple iOS/Mac OS App

3. June 2014

 

With Apple’s recent release of the Swift programming language I have decided I have to check it out.  One of the biggest reasons I’ve stayed away from Apple’s various SDKs is my dislike of Objective-C.  Swift on the other hand is quite a nice little language at least from my experiences so far.

 

Keep in mind a couple thing while reading this.  I am new to Swift ( everyone is, it’s a day old! ) and am new to Apple’s various SDKs and Frameworks.  Therefore I give no promises that anything in this tutorial series is actually the proper way of doing things.  Frankly it works on my computer and that’s about the extent of a warranty I can give! :)  I have heard great things about SpriteKit, the 2D game library Apple released with iOS 7, so I am working with it.

 

Let’s jump right in with some code.  The following is a Mac OS app, but should work equally well on iOS devices.  Keep in mind, to run Swift code you need to have Xcode 6, which is currently in beta.  Obviously you need to have a Mac to follow around.  There are “cloud based” virtual Mac services you can use as well, but my experiences weren’t great.

 

To get started I used one of the provided templates then replaced most of the code.  There used to be a SpriteKit template, but now it has been rolled into “Game”.

In Xcode select File -> New -> Project

Then select OS X -> Application and choose Game, then click Next:

Game

 

In the next dialog, name your application, be sure to select Swift as the programming language and SpriteKit as the Game Technology, click Next.

 

Game2

 

In the next dialog you select where you want to create the project and whether or not you want to create a git archive.  In this case I am not, but if you are working with a team or want version controlling, allow it to create a git repository.

 

When done, click Create and your project will be created.  When I run the generated project, I actually get:

 

Game3

 

Well, that’s not good!  Truth is though, I want to start simpler than the included project, so we are going to replace all the code anyways.  The starter template seems a bit odd to me, extending behaviour that should have probably been built in in the first place.  Let’s get rid of the complexity and strip it down to basics.

 

When you look at the project hierarchy Xcode has created, you will see a number of generated files.  Swift code files end with the extension .swift ( well, that makes sense… ).  It’s these that we are going to replace.  The generated project should look something like:

 

Game4

 

For each file listed below, edit your source to match:

 

AppDelegate.swift

 

import Cocoa

import SpriteKit

 

class AppDelegate: NSObject, NSApplicationDelegate {

    

    @IBOutlet var window: NSWindow

    @IBOutlet var skView: SKView

    

    func applicationDidFinishLaunching(aNotification: NSNotification?) {

            let scene = GameScene(size:self.skView.bounds.size)

            scene.scaleMode = .AspectFill

            

            self.skView!.presentScene(scene)

        }

    func applicationShouldTerminateAfterLastWindowClosed(sender: NSApplication) -> Bool {

        return true;

    }

}

 

GameScene.swift


 

import SpriteKit

 

class GameScene: SKScene {

    override func didMoveToView(view: SKView) {

        /* Setup your scene here */

        

        let sprite = SKSpriteNode(imageNamed: "beach.png")

        sprite.position = CGPoint(x:0,y:0)

        sprite.anchorPoint = CGPoint(x:0.0,y:0.0)

        sprite.size = view.bounds.size

        self.addChild(sprite)

    }

}

 

 

You can completely delete the file GameScene.sks.

 

Additionally, I dragged an Image file “beach.png” into my project file from Finder.  You can use any image you want, just be sure to update the filename in GameScene.swift accordingly.  When dropping the image file, make sure you select Copy if needed, and that the image is being put in the proper target, like so:

 

Game5


 

 

Now when you run the program ( Play icon in top left of your Xcode window ), you should see:

Game6

 

Of course, in your case it should display whatever image you selected.  Let’s take a quick look at what we’ve done here.

 

In our AppDelegate, we handle the applicationDidFinishLaunching event.  Once our app is launched, we create an instance of our GameScene class, set the fill mode to AspectFill and make our newly created scene active for our SKView.  This small function implementation demonstrates a few Swift concepts, i’ll start from the beginning.

Notice the line:

let scene = GameScene(size:self.skView.bounds.size)

 

How we pass in the name of the variable parameter (size), as well as a value (self.skView.bounds.size).  When declaring a function in Swift you have to option of making the user name the parameters or not when they call the function.  That is, when you are declaring a function, you can specify an internal and external parameter name and if you provide an external parameter name, the user must provide the name when calling the function.  Consider the function:

    func printSomething(item:String){

        println(item)

    }

For that function, you can simply call it like:

    printSomething("Hey")

 

However, if you declared the function using an external parameter name, like so:

    func printSomething(thingToPrint item:String){

        println(item)

    }

 

You then need to call the function like so:

    printSomething(thingToPrint:"Hey")

 

If you are familiar with Flash, TypeScript or Haxe, the syntax for functions in Swift should look pretty familiar.  It’s basically

func functionName ( externalVarName localVarName:DataType ) -> ReturnType { FunctionBody }

 

The next line containing new Swift syntax is:

scene.scaleMode = .AspectFill

 

Scale mode is simply an enum defined like so ( in SKScene )


enum SKSceneScaleMode : Int { case Fill case AspectFill case AspectFit case ResizeFill }

 

That line is functionally the same as:

scene.scaleMode = SKSceneScaleMode.AspectFill

 

 

The final line here that might be a bit confusing is 

self.skView!.presentScene(scene)


Specifically the exclamation mark after skView.  This has the somewhat scary name of “implicitly unwrapped optionals”.  See, all types in Swift must have a value, either at declaration or construction.  The exception to this rule is Optional Types.  If you’ve worked in C# this concept ( and syntax ) should look familiar to you, although in C# they are called nullable types.  An optional type declaration looks like this:

var myVariable:String?


 

This is declaring a type that can either have a value, or the special value “nil”.  For an optional type you can “implicitly unwrap” it, using the ! postfix operator, like so:

println(myVariable!)

 

When you do this, you are promising that myVariable currently has a value.  If it doesn’t, you will get a runtime error.

 

The GameScene class is much more straight forward and uses very few new Swift features.  We are loading a SKSpriteNode from file, once again you see an example of an external parameter name here, “imageNamed”.  We then set the image pivot point to the bottom left corner, just because I like the image pivot point being the bottom left corner!  SetPivot works in texture coordinated, so 0,0 is bottom left, while 1,1 is top right.  We size our image to be the same as the view, then finally add the sprite to the SKScene using addChild().  

 

And that is our very first simple application created in Swift displays a sprite on screen using SpriteKit.

 




Apple announce iOS 8 SDK. Includes Metal, an OpenGL replacement and the Swift programming language

2. June 2014

EDIT:  For a better understand of Apple’s Metal API and what it means for OpenGL, click here. 

So finally we are getting some developer related announcements out of the Apple Developer Conference.  For game developers, todays announcement is a dozy.  iOS 8 SDK includes 4,000 new API calls but most importantly includes Metal, a new lower level graphics API similar to AMD’s Mantle.  The idea is to get closer to the metal ( thus the name ) and remove the overhead of OpenGL:

 

Gaming on iOS takes a huge leap forward in iOS 8 with Metal, a new graphics technology that maximizes performance on the A7 chip. With its dramatic 10 times improvement in draw call speed, Metal enables leading game providers for the first time to bring console-class 3D games to mobile devices. For casual games, iOS 8 now features SceneKit, making it easy to create fun 3D games, along with major enhancements to SpriteKit, including field forces, per-pixel physics and inverse kinematics.

 

10 times performance improvement over OpenGL?  That sounds like marketing BS to me or describes an edge case.  If OpenGL was that bloated it would have died off year ago.  The important take away is it’s A7 only, so newest iPad and iPhones are the only ones that support it.  Unity, Crytek and Unreal are all expected to support it so it should be pretty transparent to most developers.

 

The other major announcement was Swift:

 

Swift is a powerful new programming language for iOS and OS X® that makes it easier than ever for developers to create incredible apps. Designed for Cocoa® and Cocoa Touch®, Swift combines the performance and efficiency of compiled languages with the simplicity and interactivity of popular scripting languages. By design, Swift helps developers write safer and more reliable code by eliminating entire categories of common programming errors, and coexists with Objective-C® code, so developers can easily integrate Swift into their existing apps. Xcode® Playgrounds make writing Swift code incredibly interactive by instantly displaying the output of Swift code.

 

The iOS beta software is available now for registered Apple developers.  XCode 6 is required to support the Swift programming language.  You can learn more about Swift here.  I LOVE new programming languages, so I will certainly be taking a closer look.  Some Apple toted features of swift are:

 

Swift has many other features to make your code more expressive:

  • Closures unified with function pointers
  • Tuples and multiple return values
  • Generics
  • Fast and concise iteration over a range or collection
  • Structs that support methods, extensions, protocols.

 

… interesting.  I hate ObjC, so an alternative is certainly appreciated. 

, ,




TypeScript in WebStorm

2. June 2014

 

So far in working with TypeScript I’ve exclusively used Visual Studio and that hasn’t been entirely trouble free.  There are many people out there that wont have access to Visual Studio ( working on Mac or Linux perhaps? ) or simply wont want to.  Thankfully there is a great alternative, WebStorm.  Granted WebStorm isn’t free, although there is a 30 day trial.  It is however a very well spent $50 if you are working in JavaScript ( or TypeScript ).  This post looks at working in TypeScript with Webstorm.

 

First step of course it download and install WebStorm.  The trial is fully functioning by the way.

During the install, if you havent already, you will be prompted to install Java 6.  Don’t worry, WebStorm takes care of the process for you.

Next you need to install Node.  Node.js is a JavaScript environment that works outside of the browser.  I’ve worked with Node a number of times on this site.  Install Node using the default settings.

Now open up a terminal/command prompt and type npm install –g typescript

The results should look like:

image

 

This installed the TypeScript language.  We are now ready to go.

 

When you open a project with a typescript file a file watcher should kick in automatically.  If not, its easy enough to define one.

Select File->Settings.  ( This menu has a different location on MacOS I believe )

On the left hand side, locate File Watchers:

image

 

On the right hand side, if none exist for TypeScript, click plus.  If one exists, make sure its checked.

image

Then select TypeScript from the list:

image

 

Default values should be correct:

image

 

If you have any problems at this point, make sure that Node was installed correctly and that you installed TypeScript, these are the most common problems.

 

Now with a File Watcher created, whenever you save a change to a TS file, it while automoatically compile the JS file.  Like so:

image

 

From this point on you will be able to see full syntax highlighting as well as code completion:

image

 

 

Additionally, you can set a breakpoint in WebStorm:

image

 

And assuming you’ve enabled the WebStorm plugin, you can debug in Chrome:

image

 

Which then allows you to perform the standard debugging tasks in WebStorm:

image

 

If you are coming from Visual Studio, there is one major difference to be aware of.  In Visual Studio, adding a file to your project makes it available for code completion.  In WebStorm this isn’t the case.  If you include a library, such as Phaser, you need to add a reference identifier at the top of your ts file, like so:

 

/// <reference path="phaser.d.ts"/>

 

Then code completion will work properly.

Programming ,




Adventures in Phaser with TypeScript– Where did my game loop go?

29. May 2014

 

 

One thing every single game has in common is a game loop.  That said, it’s not always under your control!  Today we are going to look at how the game loop is implemented in the Phaser HTML5 game engine.

 

Pretty much every single video game ever created follows the same basic program flow:

 

Program Starts

Check Input

Update World

Draw scene

Program Exits

 

Of course this is a massive simplification ignoring things like updating physics simulations, multiple threads, streaming of assets, etc… but the basic flow is there in every game.  The three indented process, Input, Update and Draw are performed over and over in a loop, thus “game loop”.  In Phaser there is no exception, but the way it’s handled is a bit different.

 

If you’ve done any JavaScript game development before you’ve no doubt encountered requestAnimationFrame or if using an older browser setTimeout JavaScript functions.  Both perform basically the same task, they call a function once an interval, such as every 30th of a second if your game is set to run at 30fps.  This is the very heart of most JavaScript games and Phaser is no exception.  You the end developer don’t have to care about such low level aspacts though as this functionality is taken care of in the class Phaser.RequestAnimationFrame and is automatically created by Phaser.Game.  If you want to see the actual game loop driving your game though, I suppose this code snippet from RequestAnimationFrame.js is it:

 

    updateRAF: function () {

        this.game.update(Date.now());

        this._timeOutID = window.requestAnimationFrame(this._onLoop);

    }

 

As you can see, its basically just calling Game’s update() over and over.  Now if we take a look at the source code for update in Game it all becomes clear:

 

update: function (time) {

    this.time.update(time);

    if (!this._paused && !this.pendingStep) {
        if (this.stepping) {
            this.pendingStep = true;
        }

        this.debug.preUpdate();
        this.physics.preUpdate();
        this.state.preUpdate();
        this.plugins.preUpdate();
        this.stage.preUpdate();

        this.state.update();
        this.stage.update();
        this.tweens.update();
        this.sound.update();
        this.input.update();
        this.physics.update();
        this.particles.update();
        this.plugins.update();

        this.stage.postUpdate();
        this.plugins.postUpdate();
    }
    else {
        this.state.pauseUpdate();
        // this.input.update();
        this.debug.preUpdate();
    }

    if (this.renderType != Phaser.HEADLESS) {
        this.renderer.render(this.stage);
        this.plugins.render();
        this.state.render();
        this.plugins.postRender();
    }

}

 

So there is your traditional game loop, just nicely tucked away.  So then, where then does your code fit in all of this?  Remember back in the Hello World post when we created a Game instance we past in a “State” object implementing create and passed in the function this.create to be called, like so:

this.game = new Phaser.Game(800, 600, Phaser.AUTO, 'content', { create: this.create });

 

Well, that’s how we do it.  A State object has a number of functions that will be called, in this case we provide an implementation for create, now lets look at a slightly more complicated example:

 

class SimpleGame {

    constructor() {
        this.game = new Phaser.Game(800, 600, Phaser.CANVAS, 'content', {
            create: this.create, update: this.update,
        render: this.render});
    }

    game: Phaser.Game;
    textValue: Phaser.Text;
    updateCount: number;

    create() {
        var style = { font: "65px Arial", fill: "#ff0000", align: "center" };
        this.textValue = this.game.add.text(0, 0, "0", style);
        this.updateCount = 0;
    }

    update() {
        this.textValue.text = (this.updateCount++).toString();
    }

    render() {
        this.game.debug.text("This is drawn in render()", 0, 80);
    }
}

window.onload = () => {
    var game = new SimpleGame();
};

 

Here is the code running:

 

 

In this example the State object we are passing in to the Phaser.Game constructor implements create, update and render.  Create will be called once, predictably enough on creation.  Here we create a red text object like we did in the Hello World example.  This time however we keep a reference to it.  We also add a counter variable updateCount.  Each frame update() will be called, we simply increment the counter value and assign this to out text object.  Finally in render we draw our text using game.debug.text().  Phaser provides a number of convenient debug methods for dumping information on screen, either as text or graphically.  These functions however are *NOT* optimized and should not be used in production!

 

So as you can see, update works pretty much like you would expect, but instead of your game controlling the loop you implement methods in a State object that will be called by the Phaser engine.

 

Let’s look at a slightly more complex example that will probably make State objects make a bit more sense.  This is a two screen game, first there is a title sreen shown that when clicked then moves to the game state, which is the same as the above demo.  Let’s jump in with code:

 

module GameFromScratch {
    export class TitleScreenState extends Phaser.State {
        game: Phaser.Game;
        constructor() {
            super();
        }
        titleScreenImage: Phaser.Sprite;

        preload() {
            this.load.image("title", "TitleScreen.png");
        }
        create() {
            this.titleScreenImage = this.add.sprite(0, 0, "title");
            this.input.onTap.addOnce(this.titleClicked,this); // <-- that um, this is extremely important
        }
        titleClicked (){
            this.game.state.start("GameRunningState");
        }
    }

    export class GameRunningState extends Phaser.State {
        constructor() {
            super();
        }
        textValue: Phaser.Text;
        updateCount: number;

        create() {
            var style = { font: "65px Arial", fill: "#ff0000", align: "center" };
            this.textValue = this.game.add.text(0, 0, "0", style);
            this.updateCount = 0;
        }

        update() {
            this.textValue.text = (this.updateCount++).toString();
        }

        render() {
            this.game.debug.text("This is drawn in render()", 0, 80);
        }
    }

    export class SimpleGame {
        game: Phaser.Game;

        constructor() {
            this.game = new Phaser.Game(800, 600, Phaser.WEBGL, 'content');

            this.game.state.add("GameRunningState", GameRunningState, false);
            this.game.state.add("TitleScreenState", TitleScreenState, false);
            this.game.state.start("TitleScreenState", true, true);
        }

    }
}

window.onload = () => {
    var game = new GameFromScratch.SimpleGame();
};

 

And when you run it you see ( click to proceed ):

 

One thing to be aware of right away is this example should probably be split across 3 files not in a single one.  I kept them together to make following along easier.

 

Here, instead of creating a state object inline we declare two of them.  Here we are using the TypeScript ability extend to create Phaser.State derived objects as inheritance really isn’t part of JavaScript. Let’s take a quick look at what this code does, starting with SimpleGame.

 

Here instead of providing a State object to the Phaser.Game constructor inline ( in { } form ) we register 2 different states using game.state.add().  The first value is the string value we will access this state using, the second is the state itself while the final value is if you want to start the state while adding it.  Finally after adding each state we start one calling game.stat.start and pass in the key value of the state.  Yes, we could have simply added true when we added the TitleScreenState, but I think doing it long form is clearer.

 

Once our TitleScreenState starts, in preload it loads an image, then in create it adds the image as a sprite.  Finally it adds a tap handler that will be called when the screen is tapped.  Image loading, sprites and input will all be covered later.  One very important thing to understand here though is the this parameter passed in to onTap.addOnce.  The second value is the context that titleClicked will be called in.  In other words, the value of “this” within titleClicked is determined by the value you pass here.  This is one of the warts of JavaScript IMHO and I wished TypeScript fixed it, although it appears it hasn’t.  The importance here is, if you don’t pass the context into the Signal (onTap) then the called function (titleClicked) wont have access to itself!  You will then get an error that this.game is undefined.  Finally when titleClicked is called we launch the GameRunningState like we did earlier.  GameRunningState is basically just the functionality from our earlier example split out into Phaser.State form.

 

As you can see, Phaser.State objects allow you to logically split up your game functionality.  Of course you could just implement a single inline state like we did earlier and ignore them from this point on.

 

Programming , , , , ,