Last month (September 2011) I received very great news: the Windows PHone SDK 7.1 had just been released. I opened the "What's New" session and it was
full of nice new features. I was particularly interested in the new Windows
Phone Emulator, which now has the ability to emulate device sensors, such as the Windows Phone Accelerometer.

This article is intended to show how to play with this new accelerometer emulation, accompanied by a simple application that use it.

Windows Phone SDK 7.1The Windows Phone Software Development Kit (SDK) 7.1 provides you with all of the tools that you need to develop applications and games for both Windows Phone 7.0 and Windows Phone 7.5 devices.

The new Windows Phone SDK 7.1 and the new documentation are now packed up with lots of new features:

Multi-targeting and App Compatibility

Multitasking

The Execution Model and Fast Application Switching

Alarms and Reminders

Background Agents

Background File Transfers

Background Audio

Media

Silverlight 4

Sensors

Sockets Support

Network Information

Push Notifications

Live Tiles

Silverlight and XNA Integration

Application Performance Analysis

Visual Basic Support

Advertising

WebBrowser Control

Device Status

Local Database

Isolated Storage Explorer

Launchers and Choosers

Contacts and Calendar

Encrypted Credential Store

User Experience Design Guidelines

Certification Requirements

Marketplace Test Kit

Camera

Pictures Extensibility

Search Extensibility

Application Bar

On-Screen Keyboard

System Tray and Progress Indicator

OData Client

Globalization and Localization

Creating Trial Applications

From all these features, the one we will be dealing with in this article is Sensors. But not all kinds of sensors (since "sensors" include accelerometer,
gyroscope sensors, combined motion and rotation rate). For now, we will play only with the accelerometer. Hopefully, in a near future we can focus on other features of WP7.

To access the new accelerometer emulator is quite easy. First, launch Windows Phone emulator. Then move the mouse over the emulator window. At this point, the same vertical icon bar
you found in the previous version of the emulator will be shown. The difference is the ">>" icon that you can spot at the bottom of the icon bar. Click it and a new "Additional Tools"
window will be opened:

Only that first tab, "Accelerometer", matters to us. It has the 3D rendering of the device (notice that this rendering doesn't show the same screen of the emulator). It's a fake
screen with static tiles. But hey, Microsoft, it would be very cool to have here the actual device screen, don't you think?

The second thing to notice in the accelerometer emulator is the Orientation dropdown list. We need first to pick the correct orientation (portrait or landscape and standing or flat)
to correctly perform the emulation. Our application will only work correctly if the device is in the horizontal position, so you must choose either Portrait Flat or Landscape Flat orientation.

The second thing to notice in the accelerometer emulator is the little red circle at the center of the window. Drag it and move it around the screen in order to emulate the accelerometer.

As you move the accelerometer control point around, the X, Y and Z coordinates change and are displayed on the screen. Also, this data is also passed to the Windows Phone Emulator
in real time, so any changes you make can be read by the application.

In code, the accelerometer functions are part the <class>Microsoft.Devices.Sensors namespace:

using Microsoft.Devices.Sensors;

As soon as the application begins, we start the accelerometer, which fires the update event every 20 millisecond:

When the accelerometer sensor value is changed, we simply change the <class>gravity parameter of the <class>World object. The World object
is used to manage all other objects in Farseer:

void accelerometer_CurrentValueChanged(object sender, SensorReadingEventArgs<AccelerometerReading> e)
{
// Note that this event handler is called from a background thread// and therefore does not have access to the UI thread. To update// the UI from this handler, use Dispatcher.BeginInvoke() as shown.if (World != null)
{
World.Gravity = new Vector2(e.SensorReading.Acceleration.Y * -ACC_GRAVITY_COEF, e.SensorReading.Acceleration.X * -ACC_GRAVITY_COEF);
}
}

Farseer is a wonderful open source physics engine, based on the original Box 2D open source project
(as an aside, the Angry Birds game uses Box2D). The difference is that Box2D is written in C++ (and has been ported to many languages), while Farseer is made with C#
aiming Silverlight and XNA. Also, the Farseer website claims this framework has many other features other than the ones provided by the original Box2D release.

By default, Farseer renders a circle object as an ellipse with a certain border and texture. Our ball is nothing more than a Farseer circle rendered with a static texture
of a steel ball. We first load the ball texture and define the initial position of the ball:

Now we create our labyrinth by joining a series of rectangles, right? Wrong! Unlike the ball,
the labyrinth is created from the texture image of the labyrinth. This is a very nice feature of Farseer engine that
makes our life much easier! The farseer built-in functions create a solid object from our labyrinth plain image, provided
that we leave the empty spaces with the transparent color, like this:

Now imagine how easy it is to create new levels... amazing, isn't it? The Farseer functions will do the hard job for us, and
from the code below, the part that is more worth mentioning is the BayazitDecomposer.ConvexPartition method, which creates
smaller convex polygons out of a single big concave polygon:

publicoverridevoid LoadContent()
{
.
.
.
//Create an array to hold the data from the texture
uint[] data = new uint[labyrinthTexture.Width * labyrinthTexture.Height];
//Transfer the texture data to the array
labyrinthTexture.GetData(data);
//Find the vertices that makes up the outline of the shape in the texture
Vertices textureVertices = PolygonTools.CreatePolygon(data, labyrinthTexture.Width, false);
//The tool return vertices as they were found in the texture.//We need to find the real center (centroid) of the vertices for 2 reasons://1. To translate the vertices so the polygon is centered around the centroid.
Vector2 centroid = -textureVertices.GetCentroid();
textureVertices.Translate(ref centroid);
//2. To draw the texture the correct place.
labyrinthOrigin = -centroid;
//We simplify the vertices found in the texture.
textureVertices = SimplifyTools.ReduceByDistance(textureVertices, 4f);
//Since it is a concave polygon, we need to partition it into several smaller convex polygons
List<Vertices> list = BayazitDecomposer.ConvexPartition(textureVertices);
//Adjust the scale of the object for WP7's lower resolution
scale = 2f;
//scale the vertices from graphics space to sim space
Vector2 vertScale = new Vector2(ConvertUnits.ToSimUnits(1)) * scale;
foreach (Vertices vertices in list)
{
vertices.Scale(ref vertScale);
}
//Create a single body with multiple fixtures
labyrinth = BodyFactory.CreateCompoundPolygon(World, list, 1f, BodyType.Dynamic);
labyrinth.BodyType = BodyType.Dynamic;
labyrinth.IsStatic = true;
StartAccelerometer();
}

"Haptics Technology", or "Haptics" is the tactile feedback provided by devices to the their users in response to some
event occurring in games or simulations in some kind of virtual reality.

Although this project may not be called "virtual reality", indeed it tries to imitate those old glass-covered wooden labyrinth boxes with little balls inside. The addition of the
tactile feedback certainly improves the user experience and that's why we are using it. But how to implement it in Windows Phone?

One of the nice aspects of programming for smartphones is that this little toys have many features/devices/sensors that desktop computers don't. So, while in desktop programming
you target the keyboard/mouse/screen/speakers/disk, in smartphones you now have access to built-in accelerometer/vibration/gyroscope/multitouch and so on.

First, we must handle the collisions between ball and the labyrinth. Then, we should measure the impact of the collision and finally tell the phone to vibrate according to the impact.
The harder the impact, the longer the vibration will be maintained.

As for the implementation, we first use the reference to the Microsoft.Devices namespace:

using Microsoft.Devices;

Then we declare two constants, one for the maximum interval (in milliseconds) of the vibration and the other for the minimum velocity needed to start the vibration.

Notice that not all collisions cause vibrations. The ball impact velocity must match a predefined minimum value, as well as the vibration must not
be kept for too long. We have applied these constraints because otherwise the feedback wouldn't be as real as we expected. For example, little impacts
would make the phone vibrate all the time, while big impacts would produce a long vibration. This would be annoying for the user. The best way as I
found it, was to keep the vibrations under these two constraints.

If you tried to develop games before the Windows Phone Mango update, you may have become disappointed by the fact that XNA only managed to to run at
30 frames per second (no matter how powerful your hardware was). This might have been a nice spec 3 years back, but for the current smartphone platforms 30 fps
is terrible for action games.

Fortunately, Mango update lifted this barrier by letting us to enable the highest frame rate possible for our hardware, which is currently 60 fps. But in
order to benefit from this feature, you must first configure yor application to run at 60 fps.

First, implement the PreparingDeviceSettings event of the GraphicsDeviceManager in your Game class:

The XNA Framework on Windows Phone OS 7.0 targeted a refresh rate of 30 Hz, regardless of which PresentationInterval you set.

The XNA Framework on Windows Phone OS 7.1 supports the native device refresh rate, up to 60 Hz. If you set the
PresentationParameters.PresentationInterval property to PresentInterval.One, then the PresentInterval.One value is used, targeting the native device refresh rate.

And that's it. Maybe in future updates this will be the defaul setting, but for now remember to enable it in your applications.

Yes, at this point, this is not yet a "labyrinth game", this is just "labyrinth". My intention here is not to create a complete game, just to point
to the direction to it. Now you could create a decent score control, "holes" in the floor, traps, fans, coils, elevators, all sorts of obstacles, and
so on. There is a lot of potential for this to become a very nice game, I think.

We are glad that the Windows Phone SDK 7.1 that followed the "Mango" update has brought lots of new tools for us developers. I'm sure this will help improving both the quantity
and quality of the applications at the Windows Phone Marketplace.

If you're interested in developing new, exciting apps for the Marketplace, I strongly recommend stay in touch with the newest tools and technologies. First, read
the "What's New in the Windows Phone SDK 7.1" paper. Also, download the samples in that page and take a
time to understand how it works.

Share

About the Author

Marcelo Ricardo de Oliveira is a senior freelance software developer who lives with his lovely wife Luciana and his little buddy and stepson Kauê in Guarulhos, Brazil, is co-founder of the Brazilian TV Guide TV Map and currently works for ILang Educação.

I do have one thing that I do not like with this article. When you download the articles code, it is not really clear which bits you wrote and which bits are core Farseer classes, that came from Farseer sample code.

I would prefer to see you reference a Dll that has all the stuff you did not write in it, for example when I download this, I find things like

Samples/Prefabs
Agent
Border
Pyramid
Ragdoll
Spider
Spiderweb

Which also happens to have your LabirynthDemo.cs code in it.

I have downloaded the Simple Silverlight samples, which has similar stuff in it, which is part of Farseer 3.3.1, but these classes are not the same as ones your demo uses, so where did yours come from?

The download makes it extremely hard to see wood from the trees.

In short I think you have made it very hard for anyone wishing to figure out what they need to do, to get up and running from scratch quite hard, due to the way you have scructured your projects/solution code that goes with this article.

I for one, do not see what I need to look at, or not, how much of it is standard Farseer code, which I can just use directly by using Farseer Dll?

Also after looking even further, there are a lot of extra classes in the SceenSytem folder, which seem to do an aweful lot, which are not mentioned at all in this article.

What do they all do. I don't know. You must, but will reader know, from reading this article. I doubt it

Do you see what I mean.

I would love to see you restructure the attached code to make it easier for people to pick it up.

You're right Sacha, I'm going to revise the code later on, and explain it better, in order to clearly separate the Farseer original code from mine (I'm thinking of different project/namespaces). At first I tried to upload the full Farseer projects along with mine, but I ran in trouble because of the size of the zipped file.