Saturday, May 30, 2009

WPF Black Holes


My journey into WPF is still in its infancy, but I want to document some of the ups and downs I've discovered working with the framework, ending in a big UP!

I've been googling like mad and absorbing knowledge as I ramp up the WPF learning curve. Some of my early research left me feeling pessimistic about the prospects of writing a game using WPF. First, there was the message group post (I cannot locate the link anymore, but I promise this was for real) where the poor programmer was experiencing poor render performance drawing lines in WPF (more on that later!) The suggestion he finally adopted was to run a WinForms Picture control hosted in his WPF application! Astonishingly, the GDI+ based WinForms outperformed WPF in the line drawing heavy application!

Second was the promosing blog entitled "WPF for Games". The author was literally gushing about WPF in his early blog entries. By the end of the blog, this grim topic appeared - "Throwing in the Towel", where the author is fed up fighting against the WPF framework and decides to write his game in XNA.

I love a good challenge, and this just makes me want to try harder to get a decent game out of WPF ;)

My first concrete project in WPF is a port of my TurboSprite sprite engine. I have debated internally about whether to port TurboSprite to WPF, or to try and use WPF's framework as the basis for my sprite animation. I concluded that porting TurboSprite would save me alot of headaches in the long run. My feeling is that my lightweight sprite engine will allow me to realize the graphics performance I want without pushing this burden onto the WPF framework. My sprites descend from Object - and there's nothing more lightweight than that! I will use the WPF framework to try and make a cool user interface surrounding the main SpriteSurface that contains the game's action.

But how to translate TurboSprite to WPF? The main component of TurboSprite is the SpriteSurface, and for this I derive from FrameworkElement, and drawing in an overridden OnRender method, using the supplied DrawingContext. In my next blog post I plan to go into some of the early technical details of my implementation, but for now I can describe some of the early results.

I've found that rendering images in the DrawingContext using DrawImage is blazingly fast, and perforing rotations using Transforms seems to not impact rendering performance. I was able to create many very large ImageSprites and add them to the SpriteSurface without and degredation in FPS. This is good news for Scenarios that like to use many large background graphics!

Next I tried to tackle porting beat2k's SpiralSprite, which is the basis for black holes in the SV graphics. The code ported easily enough, but when I created a SpiralSprite in my new WPF TurboSprite, the animation rate went down the toilet! Adding 2 or 3 SpiralSprites caused a complete bottleneck and the FPS was down in the single digit range.

But I was determined to find a better solution than hosting a WinForms control for my SpriteSurface!

After some research I discovered that creating a Geometry was the way to go. Apparently, the Geometry can be rendered with graphics acceleration all in one shot, while rendering the individual lines was very time consuming. The problem with this approach is that it sacrificed the ability to color each segment of the spiral, an effect that beat2k implemented in his code. I solved the problem by rendering the SpiralSprite using a RadialGradientBrush, with the end color set to Transparent.

The end result is a new SpiralSprite class that still has the customizability, the rotation (now leveraging the existing Sprite Spin and SpinSpeed properties), and that can be rendered extremely quickly on the SpriteSurface.

The code for the modified SpiralSprite


//SpiralSprite class by Jason Milliser

using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Media;

namespace SCG.TurboSprite
{
public class SpiralSprite : Sprite
{
//constructor
public SpiralSprite(int arms, float radiusmin, int radiusmax, int armslope, int slopelength, bool isSpinningClockwise, Color CenterColor)
{
//arm slope is the number of lines drawn to the center of the spiral. Also controls the tightness of teh spiral.
//slopelength is the length of each line segment of each spiral. longer lines can tighten spiral, but quality will go down.
slength = slopelength;
_centerColor = CenterColor;
_direction = isSpinningClockwise;
_radiusMax = radiusmax;
_radiusMin = radiusmin;
_armSlope = armslope;
_arms = arms;
Shape = new Rect(0-_radiusMax, 0-_radiusMax, _radiusMax * 2, _radiusMax * 2);
}

//calculate points of spiral
protected internal override void Process()
{
//we now need to create points only once, rotation performed by transformed
if (_points != null)
return;

int theta = 0;
float sinvalue = 0;
float cosvalue = 0;
double altitude = 0;
float faltitude = 0;
double radiusscale = 0;
double dradiusmin = 0;
int rdegrees = 0;

//preliminary math calculations
theta = 360 / _arms;

if (_points == null)
_points = new Point[_arms * _armSlope + 1];

for (int arm = 0; arm < _arms; arm++)
{
for (int seg = 0; seg < _armSlope; seg++)
{
if (_direction == true)
rdegrees = (seg * slength) + (arm * theta);
else
rdegrees = -(seg * slength) - (arm * theta);
while (rdegrees < 0) rdegrees = rdegrees + 360;
while (rdegrees >= 360) rdegrees = rdegrees - 360;

radiusscale = _radiusMax - _radiusMin;
dradiusmin = _armSlope;
altitude = (seg + 1) / dradiusmin;
altitude = radiusscale * altitude;
dradiusmin = _radiusMin;
altitude = dradiusmin + altitude;
faltitude = Convert.ToSingle(altitude);

sinvalue = LookupTables.Sin(rdegrees) * faltitude;
cosvalue = LookupTables.Cos(rdegrees) * faltitude;

_points[(arm * _armSlope) + seg].X = sinvalue;
_points[(arm * _armSlope) + seg].Y = cosvalue;
}
}
}

//Render the sprite
protected internal override void Render(DrawingContext dc)
{
if (_points != null)
{
//Create the Geometry if it doesn't yet exist
//this needs to be done on the same thread, so it's done here and not in Process
if (_geom == null)
{
_geom = new StreamGeometry();
StreamGeometryContext sgc = _geom.Open();
sgc.BeginFigure(_points[0], false, false);
List points = new List();
for (int i = 1; i < _points.Length; i++)
points.Add(_points[i]);
sgc.PolyLineTo(points, true, true);
sgc.Close();
}

//Transform the location to match the sprite's position
Transform t = new TranslateTransform(X - Surface.OffsetX, Y - Surface.OffsetY);
dc.PushTransform(t);

//Rotate sprite
Transform rotate = new RotateTransform(FacingAngle);
dc.PushTransform(rotate);

//Create gradient brush so spiral fades out
RadialGradientBrush rgb = new RadialGradientBrush(_centerColor, Colors.Transparent);

//Draw the spiral geometry
dc.DrawGeometry(null, new Pen(rgb, 2), _geom);

//Draw the central back hole
dc.DrawEllipse(Brushes.Black, null, new Point(0, 0), 7, 7);
dc.Pop();
dc.Pop();
}
}

//private members
private Point[] _points;
private int _arms;
private float _radiusMax;
private float _radiusMin;
private int _armSlope;
private Color _centerColor;
private bool _direction;
private int slength;
private StreamGeometry _geom = null;
private Pen _pen = new Pen(Brushes.Yellow, 1);
}
}

Friday, May 29, 2009

Better Days ahead for WPF

I see after reading this article that the deficiencies in the WPF development experience that I mentioned in the previous blog post are being addressed in Visual Studio 2010. For example, the Property window has an Events button that lets you see the events of a class and set event handlers. It was frustrating to see that missing in the VS 2008 WPF Designer. I know, you can get a list of events by typing a space in the XAML and using Intellisense, but this is a very poor substitute for having the events nicely laid out in the Property window. Also, there are RAD tools that help creating bindings and apply styles to controls. I also noted that VS 2010 will also include a Designer for Silverlight applications. Maybe 2010 will be the year for SV 2010 - WPF and Silverlight editions.

Wednesday, May 27, 2009

Feet wet with WPF

I usually make a major shift in programming technologies when there's a very compelling reason. I remember when I decided to switch from Visual Basic to Delphi because Delphi offered a perfect object oriented framework and component model. Years later, when Delphi began to decline, I made a shift to the .NET Framework and C#. Mainly, I follwed Anders Hejlsberg from Borland to Microsoft - he was the primary architect of Delphi until Microsoft lured him away and he became the primary driver of C#.

With .NET came a layer of abstraction away from Windows, meaning less fine-grained control and power, but a modern development environment with a clear future.

Since the release of the .NET Framework 3.0 in late 2006, the WPF (Windows Presentation Foundation) framework was the cool new API in the Windows world. Windows Forms became old fashioned and quaint.

I'm about 3 years late to the party, but I have finally begun to update myself in WPF. The compelling reason this time is fear that Windows Forms is becoming a dinosaur framework, and I need to keep current. I have mixed feelings about this move, unlike for example the shift from VB to Delphi which I felt had no negative aspects.

First of all, my feeling is that WPF is currently half baked, without a full RAD development experience in Visual Studio. The idea of using two tools (Visual Studio and Expression Blend) to work on an application is not appealing to me. The direction of promoting XAML as a form markup language that a developer needs to code in leaves a very bad taste in my mouth. In my mind, the form markup language should remain in the background without having to be seen, much less edited. Also, much of the WPF API seems to have the flavor of the old Win32 APIs, with function calls with loads of obscure parameters in favor of a cleaner and more well thought out framework.

On the positive side, preliminary conversion of TurboSprite to pure WPF is showing promising results, with an animation frame rate of 3000+ FPS in my basic testing with no sprites added yet to an animated surface. All of my research indicates that GDI+ suffered badly in terms of performance when rendering images. WPF makes better use of graphics accelerators, so in general rendering should be much faster, as my early tests support.

Hopefully this will translate to an eventual SV6 and future games where graphics updates are no longer an issue! This transition also opens the door to create a companion SV6 client in Silverlight that will run in the web browser (in Windows or Macs) and allow multiplayer play through PrismServer. You may not remember, but once upon a time there was a Java applet version of SV that ran in the browser. Having a browser based, full fledged SV client is another compelling reason in favor of shifting development to WPF.