Monday, September 20, 2010

Windows Phone Memory Constraints

The final Windows Phone Developer Tools have been released and the launch date is not far away. It's time to finalize the apps.
Windows Phone has some tough hardware requirements, but it's still a mobile platform with limited resources. In this blog post I'll describe how to determine the current memory usage, what the allowed maximum is to get your app approved for the Marketplace and other constraints a developer should be aware of.


Maximum memory usage
The Windows Phone hardware specifications requires that a device has 256 MB RAM or more. The allowed maximum memory an app can use is defined in the Windows Phone 7 Application Certification Requirements at point 5.2.5
The application must not exceed 90 MB of RAM usage. However, on devices that have more than 256 MB of memory, an application can exceed 90 MB of RAM usage.
One might now ask how to get this information at runtime. Fortunately there's the DeviceExtendedProperties class to obtain some device information at runtime. This class defines the GetValue and TryGetValue methods which expect a string key as parameter. The list of available property keys is defined here. Among other interesting properties like the DeviceUniqueId, it's possible to retrieve the DeviceTotalMemory, the ApplicationCurrentMemoryUsage and the ApplicationPeakMemoryUsage. The property keys are interpreted case-sensitive.
The application needs to define the device identity capability in the WMAppManifest.xml file in order to retrieve the DeviceUniqueId property, but it's not needed for the other keys like the ApplicationPeakMemoryUsage.

Here's the code to get the peak memory usage and the available total memory at runtime:

var timer = new DispatcherTimer {Interval = TimeSpan.FromSeconds(2)};
timer.Tick += (s, e) =>
{
   var memuse = (long)DeviceExtendedProperties.GetValue("ApplicationPeakMemoryUsage");
   var maxmem = (long)DeviceExtendedProperties.GetValue("DeviceTotalMemory");
   memuse /= 1024 * 1024;
   maxmem /= 1024 * 1024;
   MyTextBlock.Text = String.Format("Mem usage: {0} / {1} MB", memuse, maxmem);
};
timer.Start();

The timer checks the properties every two seconds and converts the bytes to MB. The values are then shown in a TextBlock. The peak memory is the most interesting since this value must not exceed 90 MB on a device with 256 MB. Also note that an empty application with two grids and a TextBlock already has a peak of 5 - 7 MB in the emulator or on a device.


PhoneApplicationPage.State limitation
The PhoneApplicationPage.State property is typically used to save transient state for tombstoning. The size of the State data is limited to 2 MB for a Page and 4 MB for the whole application. Be warned, if this limit is reached a not very descriptive exception is thrown. The message text is "The client who called IAccessControl::IsAccessPermitted was the trustee provided tot he method".
If more than 2 / 4 MB is needed to save transient data, the IsolatedStorage can be used. The applications IsolatedStorage is only limited by the device's flash storage size. The minimum requirement for Windows Phone is 8 GB. The available free isolated storage in bytes can be retrieved with the AvailableFreeSpace property of the IsolatedStorageFile class.

Tuesday, August 31, 2010

Rect and Point Extension Methods

I'm currently working on multiple Windows Phone projects and don't have much time for longer blog posts, but I just wanted to get this out.
For one of the projects I need to calculate some simple vector arithmetics like the Euclidean distance. I also need other properties of the Point and Rect structs that aren't built-in the Silverlight framework. As you might know I'm a huge fan of extension methods for extending built-in functionality (1, 2). That's why I wrote a few extension methods for the Point and Rect structs that might come handy.

Rect
public static class RectExtensions
{   
   // Calculates the center point of this rectangle.
   public static Point Center(this Rect rect)
   {
      return new Point(rect.X + rect.Width * 0.5, rect.Y + rect.Height * 0.5);
   }

   // Tests if this rectangle intersects with the other.
   public static bool IntersectsWith(this Rect rect, Rect other)
   {
      // Test for separating axis
      if (other.Bottom < rect.Top || other.Right < rect.Left 
       || other.Top > rect.Bottom || other.Left > rect.Right)
      {
         return false;
      }
      return true;
   }
}

The usage should be pretty obvious.
Rect r = new Rect(0, 0, 200, 300);
Point center = r.Center();

bool isIntersecting = r.IntersectsWith(new Rect(500, 600, 100, 50));


Point
public static class PointExtensions
{
   // Calculates the distance vector of the points.
   public static Point Distance(this Point p1, Point p2)
   {
      return new Point(p1.X - p2.X, p1.Y - p2.Y);
   }

   // Calculates the length of the vector.
   public static double Length(this Point p)
   {
      return Math.Sqrt(p.X * p.X + p.Y * p.Y);
   }

   // Calculates the square length of the vector.
   public static double LengthSquare(this Point p)
   {
      return p.X * p.X + p.Y * p.Y;
   }
}

The squared length saves some cycles if this information is only needed for comparison.
Point p1 = new Point(200, 300);
Point p2 = new Point(400, 500);
Point distance = p1.Distance(p2);

double length = distance.Length();
double lengthSq = distance.LengthSquare();
length = Math.Sqrt(lengthSq);

Source Code
You can download the two C# files from here.

Tuesday, August 10, 2010

Coding4Fun - Part 1 of the Windows Phone Picture Effects App and Roadmap

My new Windows Phone 7 article for Microsoft's Coding4Fun site is live. It's the first part of a short series about the development of a Windows Phone 7 picture effects application called "PicFx". The first article will show how to create the base Windows Phone application and how to implement some basic effects. The source code is licensed under the Ms-PL and can be downloaded from the CodePlex site.
I'm already working on the second part of the series, which will explain how to implement advanced effects (the cool stuff) and other features. After this article I'll add more features and important effects, enhance the existing effects and release it as "Pictures Lab" on the Marketplace.

Video
The video below demonstrates the Coding4Fun PicFx application features and also shows how it can be used. It was recorded with the application running in the emulator.

Monday, August 2, 2010

Book Review - 3D Game Development with Microsoft Silverlight 3: Beginner's Guide

A couple of weeks ago I got a review copy of the book 3D Game Development with Microsoft Silverlight 3: Beginner's Guide. The book has 452 pages, is written by Gastón C. Hillar and shows how to write games with Silverlight.
Although the title includes "Silverlight 3", the concepts are also valid for newer versions of Silverlight, like the current version 4.
This blog post is a short review of the book. I also have one physical copy of the book to give away. Yeah, a free book, like free beer.






The Content
The book 3D Game Development with Microsoft Silverlight 3: Beginner's Guide starts by explaining what tools are needed for Silverlight game development. Then the first simple Silverlight application is developed.
The second chapter explains what Sprites are, how they can be used for 2D games and frame based animations. Silverlight 2.5D hardware accelerations is also covered and how basic vector transformations work.
The next chapter introduces a Sprite wrapper class and how to simplify the game loop with it. Basic 2D collision detection with an axis-aligned bounding box is covered too. The author also shows in this chapter how to use keyboard input for the game control.
Chapter 4 finally brings 3D game development. It starts with a WPF XAML Browser Application (XBAP) application that draws a 3D model, which was generated with the 3D modelling tool Blender and then exported to a XAML file. After this, the 3D engine Balder is introduced and a simple application is created. To be honest, Balder has come a long way since the book was written and a lot of new features were introduced. Nevertheless, many concepts and the basics are still valid.
The next chapter explains some 3D concepts like Cameras and shows how to use them with Balder and XBAP. The 6th chapter is about input controlling and demonstrates how to use DirectInput with the XBAP application. Chapter 7 explains textures, lights and the usage of these in a game. The next chapter is all about animation.
The 9th chapter introduces the Silverlight physics engine Farseer and chapter 10 shows how to detect collisions and apply basic artificial intelligence. The next chapter adds an asteroid belt to the space game, which is used as an example throughout the book.
In Chapter 12, the author shows how to measure the game progress and how to use Expression Blend to create screens for highscore and other statistics. The next chapter continues with this and also explains the usage of pixel shaders from the WPF Pixel Shader Effects Library. Persisting settings to the IsolatedStorage is covered too. The last chapter demonstrates how to play and control audio and video with the Silverlight MediaElement.

Summary
If you want to get into game development with Silverlight, this is the right book for you. It starts with the basic tools, then shows how to write a simple 2D game, finally how to write a 3D Silverlight game with Balder and how to add a physics system. Another nice thing of this book is that the tools and techniques to create / convert content are also shown step-by-step.
3D Game Development with Microsoft Silverlight 3: Beginner's Guide lives up to its title: "Beginner's Guide". If you are a beginner in the field of Silverlight game development and don't know where to start, buy this book here.

Free Book!
I actually got two physical copies of the book and I like to give one away. If you want the book, just write a comment why you should get this gift. Make sure to include some form of contact information.

Monday, July 19, 2010

Photos, Photos, Photos - How To Save, Load And Iterate Pictures With Windows Phone 7

The Windows Phone developer tools beta version was recently released and brought some important changes and also new features. For example the emulator is a lot better now and tombstoning was introduced. Tombstoning is an important concept to know when a Launcher or Chooser is being used in an app.
But this blog post is not about tombstoning, this post will show how to load an image from the picture library with the PhotoChooserTask. And most important how to save a picture to the library, which is not as obvious as the usage of the Task API. The last part will show how to get all images from the picture library without using the PhotoChooserTask.

Sample
I've built a Windows Phone 7 app that uses the WriteableBitmapEx library and lets the user draw on the WriteableBitmap surface. The app supports multi touch for drawing and the radius of the pen can be changed with the Slider control. An image from the phone's picture library can be chosen with the folder icon button and the floppy disk button saves the current image to the picture library. When the third button (download icon) is clicked, all pictures from the phone's library are loaded without further user interaction. The trash button clears the draw surface.
The video below demonstrates the features and shows how to use the app.
It would be great if anyone could try this sample app on a real device and give me some feedback. I'm especially interested how the multi touch drawing works.


Background music is Soft Shapes by Planet Boelex.

How it works
The raw touch points are handled through the Touch.FrameReported event. For each multi touch point a circle is being drawn with the WriteableBitmapEx' FillEllipseCentered method and a color map array that provides alternating colors:
private void Draw(IList<TouchPoint> points)
{
   // Check
   if (!isManipulating)
   {
      return;
   }

   // Init some vars
   var bmp = Bitmap;
   var w = bmp.PixelWidth;
   var h = bmp.PixelHeight;
   var r = Radius;

   // Draw
   for (int i = 0; i < points.Count; i++)
   {
      var p = points[i].Position;
      if (p.X < w && p.Y < h)
      {
         bmp.FillEllipseCentered((int)p.X, (int)p.Y, r, r, 
                                 ColorMap[(i + colorBase) % ColorMap.Length]);
      }
   }

   // Show
   Present();
}


Choose a photo
The PhotoChooserTask allows the user to select an image. The code for this task is pretty straight forward with the beta of the developer tools.
A member variable of the PhotoChooserTask is instantiated in the constructor and an event handler for the Completed event is attached.
public MainPage()
{
   // ...

   // Init chooser
   photoChooserTask = new PhotoChooserTask();
   photoChooserTask.Completed += PhotoChooserTaskCompleted;
   
   // ...
}
private void PhotoChooserTaskCompleted(object sender, PhotoResult e)
{
   if (e.TaskResult == TaskResult.OK)
   {
      // Load original image and invalidate bitmap so it gets newly rendered
      var bitmapImage = new BitmapImage();
      bitmapImage.SetSource(e.ChosenPhoto);
      Viewport.Source = bitmapImage;
      bitmap = null;
   }
}

The PhotoChooserTask.Show method is called when the corresponding Application Bar button was clicked:
private void ApplicationBarIconOpenButton_Click(object sender, EventArgs e)
{
   photoChooserTask.Show();
}

The Show method launches the Windows Phone photo app. The current version of the Windows Phone operating system only allows one application to run at the same time and therefore our app gets terminated when the Chooser is started. Here's where the concept of tombstoning comes into play.
After the user selected an image or pressed the back button, the Chooser's Completed event is raised. You might have noticed the black screen in the video that appears after the choose operation. As a result of the app termination, the Visual Studio debugging session is stopped. The Windows Phone 7 emulator detected that the app was started in a debug context and the emulator now waits at the black screen for re-attaching. So just go back to Visual Studio and hit F5 (Start Debugging), then the debugger is being re-attached and the app continues. Of course it's also possible to Start Without Debugging in Visual Studio.
The Chooser's Completed event provides a PhotoResult that contains the TaskResult, the OriginalFileName and the ChosenPhoto as a Stream. If the user hasn't cancelled the operation, the stream is used as the source of a BitmapImage which is then assigned to the WriteableBitmap draw surface (Viewport). The user can now make some nice drawings on the photo.


Save a picture
After the user created his masterpiece he probably wants to save it back to the picture library / photo album. But how could this be done? There's no PhotoSaveTask available in the Silverlight SDK. Fortunately the Windows Phone's XNA MediaLibrary comes to the rescue. Only a reference to the Microsoft.Xna.Framework assembly is needed to use it in our Windows Phone Silverlight application. To make this task a bit easier I wrote some reusable extension methods for the WriteableBitmap. These are located in the file WriteableBitmapMediaLibraryExtensions.cs from the source code download. The signatures look like this:
// Saves the WriteableBitmap encoded as JPEG to the Media library.
// The quality for JPEG encoding has to be in the range 0-100, 
// where 100 is the best quality with the largest size.
void SaveToMediaLibrary(this WriteableBitmap bitmap, string name, int quality);

// Saves the WriteableBitmap encoded as JPEG to the Media library 
// using the best quality of 100.
void SaveToMediaLibrary(this WriteableBitmap bitmap, string name);

The methods use the MediaLibrary's SavePicture method internally. The SavePicture method expects a stream or a byte array as parameter that contains an image encoded in the JPEG format. For the earlier CTP versions I wrote a custom JEPG encoding functionality that used some parts of my Silverlight JPEG encoding blog post and an adapted FJCore version. Fortunately things got a bit easier with the Windows Phone Tools beta release. The Microsoft.Phone assembly now comes with two WriteableBitmap extension methods called LoadJpeg and most important SaveJpeg. The SaveJpeg method expects the targetStream, the width and height of the target, the orientation which is not used at the moment and the quality in a range from 0 to 100. The width and height parameters are useful when a scaled version of the WriteableBitmap should be saved as JPEG.

The current bitmap surface is saved as JPEG when the disk floppy button was clicked:
private void ApplicationBarIconSaveButton_Click(object sender, EventArgs e)
{
   var name = String.Format("MediaLibSample_{0:yyyy-MM-dd_hh-mm-ss-tt}.jpg",
                            DateTime.Now);
   Bitmap.SaveToMediaLibrary(name);
}


Load all pictures
The last thing I'd like to cover in this post is the Pictures property of the MediaLibrary class. This property returns a collection of Picture instances. This class provides all the necessary meta information about the picture and streams of the image and thumbnail data.
I use this in the sample code to create a mosaic of all Windows Phone media library pictures:
private void ApplicationBarIconOpenAllButton_Click(object sender, EventArgs e)
{
   using(var mediaLib = new MediaLibrary())
   {
      // Pictures also includes saved pics, 
      // mediaLib.SavedPictures returns the same collection items
      var allPics = mediaLib.Pictures;

      // Combine the pics to a single WriteableBitmap mosaic
      var bmp = Bitmap;
      bmp.Clear();
      int x = 0;
      int y = 0;
      foreach (var picture in allPics)
      {
         // Load thumbnail stream to WriteableBitmap
         var wb = new WriteableBitmap(0, 0);
         wb.SetSource(picture.GetThumbnail());

         // Blit thumbnail to background bitmap
         var w = wb.PixelWidth;
         var h = wb.PixelHeight;
         bitmap.Blit(new Rect(x, y, w, h), wb, new Rect(0, 0, w, h));
         x += w;

         // Check bounds and move to next row
         if (x >= bitmap.PixelWidth)
         {
            x = 0;
            y += h;
         }
         // Bitmap filled
         if (y >= bitmap.PixelHeight)
         {
            break;
         }
      }
   }

   Present();
}

The GetThumbnail method returns the stream of an image thumbnail sized 99 x 99 pixels. This bitmap is then combined with the surface bitmap by using the WriteableBitmapEx' Blit method.
Beside the Pictures property the MediaLibrary also has the SavedPictures property, but I encountered that the SavedPictures collection returns all pictures in the emulator and not only saved pictures like the name and documentation implies. But as a little bird told me, the SavedPictures property works as expected on a real device.
The MediaLibrary has some more members that might become interesting in the future, esp. when combined with the MediaPlayer class.


Conclusion
This blog post covered the complete workflow of loading, manipulating and saving a picture to the Windows Phone's picture library / photo album. I also showed how to load all images from the library and mentioned some gotchas.

Source code
Download the complete Visual Studio 2010 Windows Phone solution from here.