Category Archives: Development

Talking to node.js socket.io from Monotouch and WP8

I am writing a game and the server side for my game is written in node.js. I am also using socket.io websockets.

Writing a simple node.js server that uses socket.io is a piece of cake. Using it from Monotouch or WP8 howewer is not. There is a .NET library that works just fine on other platforms but unfortunately it uses dynamic features (dynamic keyword and so on) in .NET which causes problems when you try to use it from Monotouch – apparently Apple imposed some limitations on JIT compilers and as a result Monotouch does not have support for dynamic features.

Fixing it in Monotouch turned out to be relatively easy. I replaced all occurrences of dynamic with object – I am not really sure why dynamic was used in the first place as there doesn’t seem to be a reason for having it in there. I also needed to replace Json.NET with a version that can be used with Monotouch (this is available from Xamarin Components) and make some changes to other libraries that socketio4net uses (websocket4net and supersocket.clientengine).

Making this very same code work on WP8 was far trickier, I needed to implement a number of collections that are used by socketio4net and are not available in WP8 flavor of .NET. I was in luck as copying source files from Mono did the trick for most of them.

All this is on Github, see https://github.com/ayls/socketio4net. Now you can create Monotouch and WP8 apps that can talk to socket.io :)

Simulating Fixed and Line Joints in Farseer Physics Engine 3.5

Recently there was a new release of the excellent Farseer Physics Engine. Since my game is still in very early stage and I am still mucking around with samples and tweaking the settings I decided to upgrade since performance improvements is one of the things changed. Not that the old version was slow, but since I am inexperienced in game programming and quite likely doing some things in a non optimal way I though I could use those extra CPU cycles.

However version 3.5 is not backwards compatible and among other things it no longer includes fixed joints like FixedRevoluteJoint etc. and I have been using those in my proof of concept. As it turns out it is quite easy to achieve the things I used to use fixed joints for.

Firstly, credit where credit is due – a lot of my code is based on Farseer Samples and this post by Roy Triesscheijn.

Anyway I was testing various paddles as explained in the code that can be downloaded from the blog post mentioned above.

Here is how everything looks in action:

In Farseer 3.3, the code for the motorised paddle would look like this:

Body motorPaddle = CreateMotorPaddle();

var j = JointFactory.CreateFixedRevoluteJoint
        (
                World,
                motorPaddle,
                new Vector2(0.0f, 0.0f),
                new Vector2(-14.0f, 10.0f)
                );

// set motor speed
j.MotorSpeed = MathHelper.Pi;

// set torque and enable motor
j.MotorTorque = 100; 
j.MotorEnabled = true;
j.MaxMotorTorque = 100;

In version 3.5 you can achieve the same thing by the code below. Note the use of another static body to act as an axle:

Body motorPaddle = CreateMotorPaddle();
Body motorPaddleAxle = BodyFactory.CreateCircle(World, 0.1f, 1f);

var j = JointFactory.CreateRevoluteJoint
    (
        World,
        motorPaddle,
        motorPaddleAxle,
        new Vector2(0.0f, 0.0f),
        new Vector2(-14.0f, 10.0f)
        );

// set speed and torque
j.MotorSpeed = MathHelper.Pi;
j.MotorImpulse = 100; 
j.MotorEnabled = true;
j.MaxMotorTorque = 100;

The code for free swinging paddle is more or less the same, except that the motor is not enabled and would look like the code below:

Body simplePaddle = CreateSimplePaddle();
Body simplePaddleAxle = BodyFactory.CreateCircle(World, 0.1f, 1f);

JointFactory.CreateRevoluteJoint
    (
        World,
        simplePaddle,
        simplePaddleAxle,
        new Vector2(0.0f, -1.4f),
        new Vector2(25.0f, 10.0f)
        );

The trampoline was implemented using LineJoint in Farseer 3.3. That code looked like this:

Body trampolineAnchor1 = CreateTrampolineAnchor1();
Body trampolineAnchor2 = CreateTrampolineAnchor2();
Body trampolinePaddle = CreateTrampolinePaddle();

var spring1 = JointFactory.CreateLineJoint
        (
                trampolineAnchor1,
                trampolinePaddle,
                new Vector2(12.0f, 11.0f),
                Vector2.UnitY
                );

spring1.CollideConnected = true;
spring1.Frequency = 3.0f;
spring1.DampingRatio = 0.05f;

World.AddJoint(spring1);

var spring2 = JointFactory.CreateLineJoint
        (
                trampolineAnchor2,
                trampolinePaddle,
                new Vector2(16.0f, 11.0f),
                Vector2.UnitY
                );

spring2.CollideConnected = true;
spring2.Frequency = 3.0f;
spring2.DampingRatio = 0.05f;

World.AddJoint(spring2);

LineJoint is gone in Farseer 3.5, but there we can use WheelJoint instead, like in the code below. A wheel join allows rotation and suspension like movement along a specified axis.

Body trampolineAnchor1 = CreateTrampolineAnchor1();
Body trampolineAnchor2 = CreateTrampolineAnchor2();
Body trampolinePaddle = CreateTrampolinePaddle();

var spring1 = JointFactory.CreateWheelJoint
    (
        World,
        trampolinePaddle,
        trampolineAnchor1,
        Vector2.UnitY
        );

spring1.CollideConnected = false;
spring1.Frequency = 3.0f;
spring1.DampingRatio = 0.05f;

World.AddJoint(spring1);

var spring2 = JointFactory.CreateWheelJoint
    (
        World,
        trampolinePaddle,
        trampolineAnchor2,
        Vector2.UnitY
        );

spring2.CollideConnected = false;
spring2.Frequency = 3.0f;
spring2.DampingRatio = 0.05f;

World.AddJoint(spring2);

That is it!

Farseer Physics Engine

Recently, I have started to get ready to create a retro inspired 2D platformer game and as part of this I was looking for a physics engine suitable for use with MonoGame.

It seems that Farseer is the most popular library for these kind of things out there and there are samples included in MonoGame Samples project on GitHub. Those samples are targetting OS X, but adapting them for iOS is not difficult:

  • I had to re-generate some of content files to get them to load (it seems that spritefonts are a bit quirky on iOS) which is easy to do with MonoGame Content Project. But you better do so on a Windows 7 machine as it requires some parts of XNA Game Studio that require a bit of hacking to get them to work on a Windows 8 machine. I prefer to leave my Windows Phone development environment as it is so I used a Windows 7 virtual machine.
  • And you have to touch enable everything which was a breeze as the samples are beautifully written and easy to read.
    • The end result is this:

      Very nice! and all the collision detections and bouncing of the car and so forth is managed by Farseer! All you have to do is define a World, define its gravity, add some bodies to the world and specify their weight, define any relationships between objects such as how the tyres of the car are related to car chassis and so on. Very neatly done!

BlurryNews

I just released a simple WP8 client app for NewsBlur.com. For those who do not know, NewsBlur is a service that is competing with Google Reader. Or should I say was competing since Google is shutting Reader down.

Like many others, the news of Reader being shut down got me in search of replacement and in NewsBlur I have found a very good service that satisfies what I need from it.

Back to my app! The version that just got published in WP marketplace is very simple and gives you only the ability to browse and read stories within your feeds. I plan to add new functionality within the next few weeks. I have just submitted v1.1 for certification. This version brings the ability to signup for NewsBlur service, add new feeds, some performance improvements and other code changes to improve stability.

feeds

Using UriMapper

I bumped into an interesting issue with UriMapper on Windows Phone 8.

I followed the instructions here to redirect user to AccountPage.xaml page when they haven’t entered their credentials yet. After the user has logged in I tried to navigate back to MainPage.xaml, but I couldn’t and the app wasn’t throwing any exceptions.

Eventually I figured out that NavigationService.CurrentSource was saying the app was on MainPage.xaml even though I was on Account.xaml.

Turns out that when mapping with UriMapper that does not affect NavigationService.CurrentSource property, the property remains set to the value of original Uri. And at app startup that was the Uri as configured in WMAppManifest.xml:

    
      
    

My UriMapper implementation was like this:

    public class PageUriMapper : UriMapperBase
    {
        private readonly MainViewModel _viewModel;

        public PageUriMapper(MainViewModel viewModel)
        {
            _viewModel = viewModel;
        }

        public override Uri MapUri(Uri uri)
        {
            if (!_viewModel.Settings.IsValidUsername)
            {
                return new Uri("/AccountPage.xaml", UriKind.Relative);
            }
 
            return uri;
        }
    }

So I decided to set the startup page in WMAppManifest.xml to a page that does not exist in my project:

    
      
    

I modified my UriMapper to be like:

    public class PageUriMapper : UriMapperBase
    {
        private readonly MainViewModel _viewModel;

        public PageUriMapper(MainViewModel viewModel)
        {
            _viewModel = viewModel;
        }

        public override Uri MapUri(Uri uri)
        {
            if (uri.ToString().Contains("StartPage"))
            {
                if (!_viewModel.Settings.IsValidUsername)
                {
                    return new Uri("/AccountPage.xaml", UriKind.Relative);
                }
                else
                {
                    return new Uri("/MainPage.xaml", UriKind.Relative);         
                }
            }
 
            return uri;
        }
    }

And voila! My navigation began to work since “StartPage.xaml” != “MainPage.xaml” :)

WP8 Emulator Weirdness

I bumped into an issue that IMHO shouldn’t be an issue today. Not quite sure if it is related to portable HttpClient library that I am using, but I am going to put it out there is someone else bumps into the same issue.

I am writing a simple NewsBlur client for Windows Phone 8 and my app works well on my device now so I wanted to see how it looks in other resolutions supported by WP8. And to my surprise every request I made through HttpClient library returned status 404. Huh?

Turns out that IE on the emulator isn’t configured when you run the emulator. So when I tapped on IE I was presented with this:

wp8-ie-settings

Once I had that out of my way and I tried to run my app again it worked. Huzzah!

UPDATE:

The above no longer works. I seem to have bigger issues with the emulator. Sigh… I’ll try¬†re-installing.

The Actor Framework for Windows Azure

I listened to Erik Meijer’s keynote at a developer conference I attended a while ago and on his way to convince us that SQL is bad he mentioned ActorFX framework.

I find the concept of an actor in the cloud to which you can push function delegates on the fly really interesting. The framework is still in early alpha stages and that is to a certain extent true for documentation too :) The code snippets are a bit inconsistent, but the accompanying text explains the concept very clearly.

So what are these actors in the cloud? Here is how I understand the thing:

  • The actor can keep anything as its state and that includes function delegates or actor methods from uploaded assemblies. As far as an actor is concerned function delegates are part of its state, behaviour is state.
  • Actors can run in a cluster, with state being replicated amongst them
  • Clients can change actor state or add new things to state (which includes assemblies with actor methods)
  • There is no need to recycle actor when uploading new versions of actor methods, the behaviour of the actor changes immediately
  • Clients can subscribe to updates made by other clients
  • Actors support transactions and idempotence¬†

The example Erik showed during his keynote was an observable list that lived in the cloud, but given how flexible actors are you could implement actors that are able to do many different things.

More details about ActorFX can be found here.

Using gestures in MonoGame (and XNA)

I was trying to use this bit of code yesterday, but it didn’t work:

        protected override void Update(GameTime gameTime)
        {
            while (TouchPanel.IsGestureAvailable)
            {
                var gesture = TouchPanel.ReadGesture();
                if (gesture.GestureType == GestureType.FreeDrag)
                {
                    _cue.Rotate(gesture.Delta, GraphicsDevice.Viewport.Bounds);
                }
            }

            base.Update(gameTime);
        }

Why? Because I forgot to enable gestures! This line was all that was missing:

            TouchPanel.EnabledGestures = GestureType.FreeDrag;

EnabledGestures is a flag property so you can enable multiple types of gestures by using bitwise or, like, for example:

 TouchPanel.EnabledGestures = GestureType.FreeDrag | GestureType.Tap;

In my rotate method I simply translate the delta into something more useful, which in my cases are degrees:

        public void Rotate(Vector2 delta, Rectangle viewPortBounds)
        {
            var degreesAroundYAxis = (delta.X / viewPortBounds.Width) * 360;
            var degreesAroundXAxis = (delta.Y / viewPortBounds.Height) * 90;
            Rotation += new Vector3(MathHelper.ToRadians(degreesAroundXAxis), MathHelper.ToRadians(degreesAroundYAxis), 0.0f);

            if (MathHelper.ToDegrees(Rotation.X) < 5.0f)
            {
                Rotation = new Vector3(MathHelper.ToRadians(5.0f), Rotation.Y, Rotation.Z);
            }
        }

Starting with MonoGame

I love coding little apps for my phone and (hopefully soon) tablet. The project I am working on now is porting a simple Snooker game I wrote using DirectX and C++ nearly a decade ago over to Windows 8 and Windows Phone devices.

My initial plan was to just copy my C++ code to a Direct3D project, tweak a few things and see it run. An overly optimistic goal, given my rusty C++ skills and the fact that DirectX API has evolved a lot since DirectX 8. So I started looking for alternatives that would get me to my goal quicker (I like to keep my hobby project short). If XNA had support on Windows 8 and Windows Phone 8 devices I would go with that one, but since they are not I started looking at MonoGame which is an open source implementation of XNA API. And it is awesome.

To get started you need to get MonoGame source code from GitHub by cloning the repository. The source contains VS2012 templates, copy these over to your templates folder and you are ready to start coding with MonoGame. For more details on how to do this follow instructions at bob’s blog. But you will need to (or can) do certain things differently!

First, MonoGame project has evolved a bit since and now you will have three VS2012 templates in there:

  • Game is the one you want to use if you are writing a game using MonoGame only,
  • XamlGame is a combination of MonoGame and XAML and
  • WindowsPhone is obvious

Secondly, before you can load your mesh models into your game you need to convert them into XNB file format, but at the moment there are no Content Importers in XNA. So you will need to use project templates that come with XNA Game Studio in order to convert the models to XNB format. There were some issues with installing XNA on Windows 8 in the past (see Aaron Stebner’s WebLog) but if you install Windows Phone 8 SDK it installs without a problem and you can use XNA Content project from VS2012. Then create a “Content” folder within your MonoGame project and copy XNB files in there (mark them as Content in properties and make sure they are always copied to output directory). I believe you could tweak the location by changing the line below in your Game class:

Content.RootDirectory = "Content";

This should have you ready and going. As for myself, I have this after one day:

Snook

Dynamic WCF Proxy

I find it hugely annoying to refresh Service References after every change to service contract. Having said that, if your services are public and you have external consumers for your services you don’t really want to make big breaking changes to your service contract anyway.

But when services are limited to your project or organisation/client you are more likely to change things and maintenance of service references can become a bit tedious then, especially when you have dozens of service references.

But there is an easier way! You can programatically create your service proxies, which, of course, is not without drawbacks as creating a WCF proxy on the fly is quite an expensive operation. The drawbacks can be countered by trying to cache and reuse proxies whenever possible.

And this is what I have done in DynamicWCFProxy library. You can download it from GitHub.

Using it is as easy as this:

            using (var client = new ProxyBase<IMyService>())
            {
                Console.WriteLine(client.ExecuteProxyFunction(() => client.Proxy.GetData("Dude", 34)));
            }

Where IMyService is your WCF service contract and GetData is one of it’s methods. As you can see ProxyBase is the magical thing that manages the lifecycle of the proxy. Proxies are pooled (the maximum number of proxies in pool being limited by the configured number of connections per endpoint) and as soon as we are out of the using block the proxy will be returned to the pool, ready to be used by some other thread. Every proxy has a connection life cycle strategy, which defaults to keep the connection open for a while to avoid reopening it if we do multiple requests to the same service in a sequence.

Now the life cycle strategy might work or not work in your scenario. With WCF you always want to do some performance testing around your app. And it could be that the default life cycle strategy is not your cup of tea, but you can always create your own and then write your code like this instead:

            using (var client = new ProxyBase<IMyService>(new MyConnectionLifeCycleStrategy<IMyService>()))
            {
                Console.WriteLine(client.ExecuteProxyFunction(() => client.Proxy.GetData("Dude", 34)));
            }

MyConnectionLifeCycleStrategy must inherit from ConnectionLifeCycleStrategyBase and the rest is up to you. Let’s have a look at default implementation in the library:

    public class DefaultConnectionLifeCycleStrategy<T> : ConnectionLifeCycleStrategyBase<T>
        where T : class 
    {
        private readonly object _connectionLock = new object();
        private DateTime _lastUsed;
        private Timer _timer;
        private int? _maxConnectionIdleTime;
        private int MaxConnectionIdleTime
        {
            get
            {
                if (_maxConnectionIdleTime == null)
                    // take send timeout (operation timeout) and add 5 seconds on top of it to get the idle time after which connection should be closed
                    // this is to avoid closing the connection before it timeouts which could lead to confusing error messages
                    _maxConnectionIdleTime = Convert.ToInt32(EndpointContext.ServiceFactory.Endpoint.Binding.SendTimeout.TotalMilliseconds) + 5000;

                return _maxConnectionIdleTime.Value;
            }
        }

        public override T Open()
        {
            lock (_connectionLock)
            {
                var proxyOut = base.Open();

                _lastUsed = DateTime.Now;
                StartConnectionCheck();

                return proxyOut;
            }
        }

        public override void Close()
        {
            lock (_connectionLock)
            {
                base.Close();
                StopConnectionCheck();
            }
        }

        private void StartConnectionCheck()
        {
            if (_timer == null)
                _timer = new Timer(ConnectionCheck, null, MaxConnectionIdleTime, MaxConnectionIdleTime);
            else
                _timer.Change(MaxConnectionIdleTime, MaxConnectionIdleTime);
        }

        private void ConnectionCheck(object state)
        {
            lock (_connectionLock)
            {
                DateTime checkAt = DateTime.Now;
                if ((checkAt - _lastUsed).TotalMilliseconds >= MaxConnectionIdleTime)
                {
                    base.Close();
                    StopConnectionCheck();
                }
            }
        }

        private void StopConnectionCheck()
        {
            _timer.Change(Timeout.Infinite, Timeout.Infinite);
        }
    }

As mentioned, the default strategy is to keep the connection open for as long as possible to avoid having to reopen the connection. This is why in the constructor we read endpoint idle timeout configuration and calculate the max open time based on this. Note that if we have an operation running which is going to timeout we still want to see a timeout exception, hence why max connection open time is 5 seconds longer than configured endpoint idle timeout. Next notice that this strategy keeps track of when the connection was last used which means the connection will remain open for MaxConnectionIdleTime after last call was made, and if a new call is made that gets extended again. A background timer will close the connection if we reach MaxConnectionIdleTime timeout.

Well this is it. I hope you find this useful!