The Rotating Cube

Rotating Cube ScreenshotContinuing to explore WPF, I wandered into the world of 3D. I decided to start small: let’s display a rotating cube. I built a little sample that is available here (17KB zip file) and the screenshot is to your right.

There is an excellent CodeProject sample by Prasad02 that shows a rotating cube, but it is much more involved. I took this sample as an inspiration and built my own from scratch, periodically taking a peek at Prasad’s work.

I also left my cube open (only 5 planes instead of 6) to explore the shading effects on the interior. The sample is entirely in XAML – I did not have to write a single line of C#. Some would say “I did not have to write a single line of code”, but here we risk to plunge into a long debate on what exactly is “code”. It’s a very interesting subject, but I will discuss it some other time 🙂

The cube is comprised of five planes of different colors and a gray interior. You are looking almost directly at the vertex, but I moved the vertex slightly off the line of sight, to make the picture more 3D. I had a hard time making interior shading look natural. I am afraid I did not succeed much. I think the problem is in the way WPF handles light sources – more about it in a separate article I guess. I also could not help but notice that the borders between the planes are quite coarse – WPF does not care to smooth the edges and the border looks uneven (i.e. suffers from pixelization), in any resolution. I guess smaller triangles and/or nicer textures would take care of that.

Also, you definitely need a tool to draw your bodies. Spelling out coordinates by hand is simply not an option. Unless you are a 3D prodigy, anything more complicated that a cube ought to make you slightly insane.

Note that the rotation make look weird, because we don’t really rotate the cube, we rotate the whole space together with the light sources, so the shading of the facets does not change. This is not what normally happens in real life. In real life while the body rotates, light sources remain static, and the facets change the color with rotation. One day I may come back to this sample to implement real rotation.

Note, that Silverlight (as of version 3) does not support 3D, so this sample cannot be converted to a Silverlight app.

Leave a Reply

Your email address will not be published. Required fields are marked *