I'm very happy to announce that I'm moving this blog to http://nokola.com
Click here to visit the new blog: http://nokola.com/blog
Click here to subscribe to the new blog: http://nokola.com/blog/syndication.axd
In the last few weeks I was quetly posting in the new blog on http://nokola.com/blog in order to entice people to move there :)
What do you get in the new blog:
- New posts not posted at the old one:
The Cool Windows 7 Selection Done in WPF/Silverlight - what it reads :)
WPF/Silverlight Tutorials From My Previous Blog - these are all posts that I consider interesting from this blog, grouped by topic (e.g. Gaming, Design/Effects, Controls, Whitepapers, Beginner Samples, Web Services/Authentication and Tips)
Two Ways to Create High-Quality Glassy Controls in XAML
- more various (hopefully interesting) content now that the blog is not associated with blogs.msdn.com
- similar topics as the old blog (I haven't changed :))
If anyone other than me cares: why the blog move?
- allows for better site integration, now running my own version of http://www.dotnetblogengine.net/ - check that blog engine out, it's cool!
- I have more control over the blog (e.g. can do Silverlight integration better)
- better content, because I can now attach more pictures, etc to the blog (there was a system limitation with blogs.msdn.com)
- last but not least, I can talk about more topics that interest me since the blog is no longer directly associated with msdn.com...hopefully you'll find them useful!
Still figuring out few tweaks with themes...but everything is up and functional.
Blog Engine is great - it took < 10 minutes to set up! amazing...
Goodbye here and Hi there! :)
Edit: fixed broken links
What is the best method to create a game loop?
I created a small experiment comparing 5 different animation methods.
The results, along with code samples and test screenshots are summarized in this document:
5 Game Loops in Silverlight: Which is the best? (PDF)
5 Game Loops in Silverlight: Which is the best? (DOCX)
Sample test app (requires reading the document above to understand the setup): http://nokola.com/gamelooptest
This is part of the test app startup screen before measurements begin:
Contents of the doc:
Welcome
What Are Some Things Important For A Game?
Why Are We Discussing Game Loops?
Methods
Test Setup
Test Results
MaxFrameRate Unset (Defaults to 60):
Analysis of the 60 FPS default case:
MaxFrameRate=300:
Analysis of the 300 FPS case:
Additional Tips
Quick Comparison Chart
Summary & Conclusion
I hope this will shed some light on Silverlight game loop that several people on this blog asked so far!
Please let me know what you think!
Attachment(s): gameloop.jpg
My latest creation last night... space view of a planet on a starry background
The image is 1920x1440
Hope you like it :) Feel free to use it as your desktop background, if you like :)

Attachment(s): planet1.jpg
Check out the new starfield and compare it with the old one.
Edit: thanks to for pointing out an issue, I updated the code again - now the stars no longer form straight lines if the Silverlight control was invisible for some time. Also updated the speed algorithm, to be more close-to-nature :)
Source and demo below show the latest changes.
Some notes on how it is made below the stars :)
Source code: http://nokola.com/sources/StarField.zip
Do you like the new one or the old one better? Please comment
I made 4 improvements to the star field:
· First I fixed the star brightness to actually be from 0 to 1 (initially it was in the range 0..256).
· If you think about it, the further you look, the more stars you see. In the previous example, the further you look, the same number of stars you see. This takes a away a lot of the realism and feeling of "depth" to the field.
To fix this, I chose a 60 degrees viewing angle, then divided my "3d" space into 8 planes parallel to the screen (near to far plane).
Then, I compute the number of stars in each plane, based on the previous plane. The first plane contains 4 stars (chosen arbitrarily).
· The other fix is star speed – the further back stars are, the slower they appear to move. Fixed it – nice J
· Next one is star brightness – stars get dimmer based on the square of the distance from the viewer, not linearly
I also fixed a few bugs, and added some “magic” constants here and there. For example, the dimmest star is has alpha of 0.3…because I don’t want to waste resources on stars that are not noticeable on screen.
Edit2: After posting this, I made a significant improvement on the star field... will post it tonight. In the new version there's more sense of depth not just "dots" like the one below. The star speed and brightness now is calculated better (based on square of the distance and correct view angles). See the next update tonight...will look a lot better :)
A good space game can't go without stars :)
Source code: http://nokola.com/sources/StarFieldOld.zip (the new one is in newer post)
Check out the Silverlight star field below, its intentionally large-size so that I can finally appreciate the night sky :)
Edit: I'm stupid...Brightness should be in a range 0..1 (or 0..2 or something like that)...please add / 100.0 to the Brightness (star.Brightness = Globals.Random.Next(256) / 100.0;) when you download the source. I'll update the effect when I get back home tonight.
It looks 1000 times cooler with the correct opacity...
Notice the dimmer, slow moving stars in the background. Notice the CPU usage. It's 2-3% 1080P here , if it is higher on your side, please ping me!
Also, since I made the background, you are free to use it for your purposes (credit me or not - I don't care)!
Below the Star field read a few notes on how its built.
this is the Old version of the star field.
Stars are represented with Ellipses on a Canvas. Each star has a X, Y, and Z (distance) position.
The X and Y are just normal screen coords (e.g. 0..1024 for X), depending on the control/screen size. The Z is in the range 0...1.
1 means "farthest". Z determines how fast the star moves and the size of the Ellipse.
Each star has a Brightness as well - approx 0..2. You can probably see why I chose Z to be from 0..1 now - because Z * Brightness = Star control's Opacity. It just makes things easier...
On every frame I move the ellipses - see the code.
Here...a quick bite from the new game coming out...

Silverlight 3, full screen,
Got an idea for a name?
Attachment(s): ship1.png
Edit: this post is now replaced by the more in-depth view here: http://blogs.msdn.com/nikola/archive/2009/08/19/exposed-5-methods-to-create-game-loop-which-is-the-best.aspx
Nice!
I just ported my Shock game to Silverlight 3.
Getting the graphics to work as before (and better), took me about an hour reading through docs. But the changes took about 5 minutes.
I'll just list them here for you in case you're building one of the next generation Silvelight games:
1. In your Silverlight Control's .HTML or .aspx file set EnableGPUAcceleration="true". This allows Silverilght to use the GPU for controls that you tell it to (see below).
Also set MaxFrameRate="1000". I’ll explain why we set the frame rate to such a high value in a bit.
Here’s how Shock’s Silverlight control looks after the change:
<asp:Silverlight ID="Xaml1" runat="server" Source="~/ClientBin/Shock.xap" MinimumVersion="3.0" Width="640px" Height="480px" EnableGPUAcceleration="true" MaxFrameRate="1000"/>
2. Find elements in your application that move, scale, rotate or blend (use transparency).
For each of these elements turn on hardware acceleration from XAML by setting CacheMode="BitmapCache" like this example:
<Image x:Name="imgBolt" CacheMode="BitmapCache"
VerticalAlignment="Bottom"
HorizontalAlignment="Left"
Opacity="0"
Source="Shock/Images/Explosions/bolt.png"
Height="304"
Stretch="Uniform"
Width="590"
Margin="0,0,0,64"
IsHitTestVisible="False">
<Image.Clip>
<RectangleGeometry x:Name="boltClipRect"
Rect="0,0,590,10000"></RectangleGeometry>
</Image.Clip>
</Image>
This really helps (in my case CPU down from 10% to < 3%)! J I enabled hardware acceleration for the balls and for the lightning bolt in Shock. Now the animations and redraws look smoother.
3. If your game loop uses a timer, storyboard, or thread, change it to use CompositionTarget.Rendering instead. The reason is that Silverlight 3 can render animations more smoothly than Silverlight 2.
Also, your timer will typically be called every 15 msec now (60 FPS). In Shock, the balls move through Storyboard-s. I used to hit-test the balls with bricks, paddle, and screen 60 times per second. Now I see that sometimes animations will be drawn faster than this, and in some cases I could notice balls being drawn on top of bricks, or the paddle. With faster animations and better runtime, the effect is easier to notice.
This is the reason why I wanted to recalculate the hit testing and update animations faster. The easiest way to do this in Silverlight today is by using CompositionTarget.Rendering and setting MaxFrameRate to a high number (1000 is pretty good, although 200 generates almost the same results already). I used MaxFrameRate=”1000” in conjuction with CompositionTarget.Rendering to achieve smoother animations in Shock.
That’s for today! Hope you liked it!
I’m trying to stay away from posting yet-another-“Silverlight 3 is released”-post and listing all the benefits to get a temporary boost in reads. Instead I hope my own findings will bring you unique value and enjoyment developing Silverlight applications!
If you’re still interested in what’s new in SL 3, this is the official list
This is the second post of the "Reallistic Human Movements with Silverlight" series. I'll spend a little time talking about the .bvh file format structure. I’m still working on the code and that’s why I’ll make this post short in order to get back to the mocap code. There is a link to more relevant info at the bottom.
I updated to the motion capture source code (download attachment to this blog) that contains a major fix related to joint rotation.
The latest sample is here: http://nokola.com/mocap.html
Some people thought the sample is a saved video – it is not. The sample shows rendering of 3D motion capture data at real time on Silverlight. Try out the new “body fat” slider! If you click “Add another person” then “Show Info” you’ll see the x, y, z angles for joint rotations in realtime.
Before going on, a quick overview of one way animation studios do motion capture today:
1. A human (e.g. actor or martial artist) is placed in a special costume for motion capture
2. There are numerous cameras surrounding that person (e.g. 24 cameras) that take videos of the person
3. Software processes the videos to "understand" where the person's hands, feet, etc are and saves this information in a motion capture file
One such file format is .BVH (Biovision motion capture).
The bvh contains 2 sections:
1. Skeleton data describing the hierarchy and initial pose of the human skeleton whose motion is being captured
2. Frame data describing how the human's joints move over time
The skeleton data looks something like this:
HIERARCHY
ROOT Hips
{
OFFSET 0.00 0.00 0.00
CHANNELS 6 Xposition Yposition Zposition Zrotation Xrotation Yrotation
JOINT Chest
{
OFFSET 0.00 5.21 0.00
CHANNELS 3 Zrotation Xrotation Yrotation
JOINT Neck
{
OFFSET 0.00 18.65 0.00
CHANNELS 3 Zrotation Xrotation Yrotation
JOINT Head
{
OFFSET 0.00 5.45 0.00
CHANNELS 3 Zrotation Xrotation Yrotation
End Site
{
OFFSET 0.00 3.87 0.00
}
}
}
…
For each joint, we have its 3D offset relative to its parent joint (Hips is the parent of Chest) and its channel information.
You can read more about this here: http://www.cs.wisc.edu/graphics/Courses/cs-838-1999/Jeff/BVH.html
One thing missing from the above page is that it is very important to note the order of the channels –this is the order in which you have to rotate the joints. For example order of “Zrotation Xrotation Yrotation” means that you have to rotate by z,x,y in that order.
The bug that I fixed in my code was related to that. If you don’t follow the order in the file, you’ll end up with weirdly moving figures or jitter in the playback.
The second part of the .bvh file is the frame information – I encourage you to read about it here: http://www.cs.wisc.edu/graphics/Courses/cs-838-1999/Jeff/BVH.html
This resource explains it pretty well!
More Info
One person also asked me “how do I capture my own motion data?” Usually this is pretty costly (e.g. $10,000-$20,000), but could be made with lower cost too!
I’ll talk a little bit about this in the next post. In the meantime you can search for “motion capture single camera” or "markerless motion capture" on the internet. This seems to be the cheaper way to do it (cheaper as in $50-$500). Recent scientific developments (last few months) in markerless motion capture really open the possibility for the public to use this technology!
Attachment(s): MocapView.zip
Hoho! yes! How to make reallistic human movements in Silverlight?
Check out this stickman animation demo here: http://www.nokola.com/mocap.html
Download source code for the above sample in the attachments to this post below.
You're looking at 3D realtime animation of stick man figures using motion data found on the internet.
The motion capture viewer took me the whole day yesterday - still nothing compared to doing these animations manually frame by frame.
As a start, you need movement data (motion capture or mocap data). You can find a lot of that online. This site http://sites.google.com/a/cgspeed.com/cgspeed/motion-capture/3dsmax-friendly-release-of-cmu-motion-database contains thousands of human motions - e.g. jump, punch, kick, wash windows, mop floor, and other.
I used the .BVH files - they have a short description of the skeleton being animated (joints, head etc) as well as rotational information (e.g. "wrist should be rotated at 50 degrees at time X")
Since this is a work in progress, I'm just publishing this quick blog post - more info will come later, because I want to make the animations transition into each other.
In the future I'll talk about the motion capture file formats and some challenges I faced (and are still facing!) implementing the above sample.
Here's a quick overview of motion capture from Wikipedia:
"Motion capture, motion tracking, or mocap are terms used to describe the process of recording movement and translating that movement onto a digital model. Initially invented in Scotland, it is used in military, entertainment, sports, and medical applications. In filmmaking it refers to recording actions of human actors, and using that information to animate digital character models in 3D animation. When it includes face, fingers and captures subtle expressions, it is often referred to as performance capture."
http://en.wikipedia.org/wiki/Motion_capture
Motion capture is used in games, movie special effects, and now in demos like the one above :)
Attachment(s): MocapView.zip
I decided to give a third spin of Joe Stegman's dynamic image generation code. This time, it's many times faster (about 10x) than the original implementation and the png is generated in-place (no recoding necessary).
I used some hacky optimizations :) For example, replacing the big CRC loop with a constant (0), definitely improves speed a lot! :)
There are no more intermediate memory streams or buffers: whenever SetPixel() is called, the value is written directly into PNG. Also all the header and size information is created just once. That also helped performance quite a bit.
With the new code my raindrops sample runs 20% faster (90% of the time used in calculating the drops): www.nokola.com/raindrops
Download the source code containing the new PngEncoder class here: www.nokola.com/sources/water.zip
Here's how to use the new image generator class:
PngEncoder surface = new PngEncoder(640, 480); // image dimension
surface.SetPixelSlow(40, 30, 200, 135, 32, 255); // set pixel at (40,30) with color RGBA=(200,135,32,255)
// draw a white horizontal line fast
int rowStart = surface.GetRowStart(30);
for (int i = 0; i < 10; i++) {
// SetPixelAtRowStart() is good for blitting/copying existing images onto this one
surface.SetPixelAtRowStart(i + 40, rowStart, 255, 255, 255, 255);
}
// display the image
BitmapImage img = new BitmapImage();
img.SetSource(surface.GetImageStream());
imgWater.Source = img; // this is just a normal Silverlight Image
And, here's the GetImageStream() function for comparison with the previous implementation:
public Stream GetImageStream()
{
MemoryStream ms = new MemoryStream();
ms.Write(_buffer, 0, _buffer.Length);
ms.Seek(0, SeekOrigin.Begin);
return ms;
}
Compare this to the previous function, that had numerous for()-s, encoding logic, etc :)
hoho! I'm very happy for doing this!
Edit: here's the source code for the SetPixelXX functions - to prove they are actually not slow :)
public void SetPixelSlow(int col, int row, byte red, byte green, byte blue, byte alpha)
{
int start = _rowLength * row + col * 4 + 1;
int blockNum = start / _blockSize;
start += ((blockNum + 1) * 5);
start += _dataStart;
_buffer[start] = red;
_buffer[start + 1] = green;
_buffer[start + 2] = blue;
_buffer[start + 3] = alpha;
}
public void SetPixelAtRowStart(int col, int rowStart, byte red, byte green, byte blue, byte alpha)
{
int start = rowStart + (col << 2);
_buffer[start] = red;
_buffer[start + 1] = green;
_buffer[start + 2] = blue;
_buffer[start + 3] = alpha;
}
public int GetRowStart(int row)
{
int start = _rowLength * row + 1;
int blockNum = start / _blockSize;
start += ((blockNum + 1) * 5);
start += _dataStart;
return start;
}
Last night, inspired by the cool taskbar in Windows 7, I decided to see how easy it will be to make a similar control in Silverlight.
Here's the screenshot of the first stab on the Win7 taskbar in Silverlight:

Click here: http://www.nokola.com/NavSeven to see it in action.
There are a lot of things to be improved on the above control, but it was easy to do this first version.
Download the source code here: http://www.nokola.com/sources/NavSeven.zip
Attachment(s): buttonseven.jpg
Submission deadline is April 30, 2009
Check it out:
http://www.serverquestcontest.com/
Too bad I can't participate (I'm not eligible because I'm Microsoft employee)
Whoever reads this, please do your best! Thank you! :)
I'll still be doing my own game thingie in the meantime, even without a chance to win $5000
Last week I created a document that incorporates my experiences developing the Shock Silverlight online game so far.
The document discusses the basics of online games in Silverlight and has a lot of practical examples (code) and a working project that you can use to build your own game.
Don't make the mistakes I did! Happy coding!
Open Document: Anatomy of a Silverlight Game.docx
Download Source Code Project
Play Sample Game
Here are the abstract and contents of the doc:
Abstract:
Typical online games have a start screen, levels, storyline, transitions, high scores, chat, and other features that can take significant amount of time to develop.
There are challenges when building online games, such as full screen support and scaling; speed optimization; animations; real-time calculations.
Learn how to develop compelling Silverlight games faster, by using a base framework for the common game elements outlined above.
Contents:
About the Author
About this Document
Goal
Scope
Target Audience
Getting Started
1. Introduction: Why Care About the “Details”?
2. Components of an Online Game
3. Screen Layout
Visual Layers that Make Up Your Game
Game Interface Layer
In-game Controls Layer
Sounds Layer
Start Screen Layer
Main Screen Popup Controls Layer
4. Silverlight Game Internals
The Game Loop
Some Classes That You’ll Likely Use in Every Game
The Game Class
Defaults Class
Globals Class
Enumeration Classes
Sounds Class
Other Classes
Keyboard and Mouse
Full Screen Support
Returning from Full Screen to Embedded Mode
Aspect Ratio
More Info
Transitions
Sound and Music
5. Networking
Score
Chat and Multiplayer
Network Speed Optimizations
6. Host Integration
7. Cheat Protection
8. Tips and Tricks
9. Summary
Happy Reading!
Attachment(s): Anatomy of a Silverlight Game.docx
I'm very proud to announce version 2 or my online Silverlight game "Shock":
Play it here:http://www.nokola.com/shock
Edit: I appreciate if you leave your comments and suggestions in the comment field for the game.
Also, if you like it, please vote for it on http://silverlight.net/community/gallerydetail.aspx?cat=sl2&sort=2
Sub-set of the source code (v1, playable) is here: Download Shock source code

Attachment(s): Shock2.jpg
I found a pretty cool chill-out style game in Silverlight. Just go and draw your first animal :) it's pretty nice to see those things come to life.
Also there are some cool things you can play with friends and share the animals and joy :)
You don't need an account to play
http://shidonni.com/